{"version":3,"file":"index.b7bdd049.js","sources":["../../node_modules/@babel/runtime/helpers/esm/objectSpread.js","../../node_modules/i18next/dist/esm/i18next.js","../../node_modules/react-i18next/node_modules/@babel/runtime/helpers/esm/defineProperty.js","../../node_modules/react-i18next/node_modules/@babel/runtime/helpers/esm/createClass.js","../../node_modules/react-i18next/dist/es/context.js","../../node_modules/react-i18next/node_modules/@babel/runtime/helpers/esm/classCallCheck.js","../../node_modules/react-i18next/dist/es/utils.js","../../node_modules/react-i18next/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js","../../node_modules/react-i18next/node_modules/@babel/runtime/helpers/esm/slicedToArray.js","../../node_modules/react-i18next/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js","../../node_modules/react-i18next/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js","../../node_modules/react-i18next/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js","../../node_modules/react-i18next/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js","../../node_modules/react-i18next/dist/es/useTranslation.js","../../src/locales/resources.ts","../../src/i18n.ts","../../node_modules/react-redux/es/components/Context.js","../../node_modules/react-redux/es/utils/batch.js","../../node_modules/react-redux/es/utils/Subscription.js","../../node_modules/react-redux/es/utils/useIsomorphicLayoutEffect.js","../../node_modules/react-redux/es/components/Provider.js","../../node_modules/react-redux/es/hooks/useReduxContext.js","../../node_modules/react-redux/es/hooks/useStore.js","../../node_modules/react-redux/es/hooks/useDispatch.js","../../node_modules/react-redux/es/hooks/useSelector.js","../../node_modules/react-redux/es/index.js","../../node_modules/@fc-components/menu/src/menuItem.tsx","../../node_modules/@fc-components/menu/src/subMenu.tsx","../../node_modules/react-use/esm/useEffectOnce.js","../../node_modules/react-use/esm/useIsomorphicLayoutEffect.js","../../node_modules/react-use/esm/misc/util.js","../../node_modules/react-use/esm/factory/createGlobalState.js","../../node_modules/react-use/esm/misc/hookState.js","../../node_modules/@fc-components/menu/src/skimMenu.tsx","../../node_modules/@fc-components/menu/src/index.tsx","../../node_modules/@fc-components/menu/src/types.ts","../../node_modules/strict-uri-encode/index.js","../../node_modules/decode-uri-component/index.js","../../node_modules/split-on-first/index.js","../../node_modules/filter-obj/index.js","../../node_modules/query-string/index.js","../../src/utils/index.ts","../../src/store/common.ts","../../src/services/login.ts","../../src/utils/request.ts","../../src/services/common.ts","../../src/components/IconFont/index.tsx","../../src/components/menu/index.tsx","../../src/pages/NotFound/index.tsx","../../src/pages/NotFound/Page403.tsx","../../src/pages/login/index.tsx","../../src/pages/login/overview.tsx","../../src/pages/loginCallback/index.tsx","../../src/pages/loginCallback/cas.tsx","../../src/pages/loginCallback/oauth.tsx","../../src/components/AdvancedWrap/index.tsx","../../src/utils/constant.ts","../../src/services/warning.ts","../../src/pages/warning/strategy/license.tsx","../../src/components/pageLayout/index.tsx","../../node_modules/re-resizable/lib/resizer.js","../../node_modules/re-resizable/lib/index.js","../../src/components/LeftTree/index.tsx","../../src/components/BlankBusinessPlaceholder/index.tsx","../../src/components/BaseSearchInput/index.tsx","../../src/store/warningInterface/strategy.ts","../../src/pages/warning/const.ts","../../src/components/RefreshIcon/index.tsx","../../src/components/ColorTag/index.tsx","../../src/components/ImportAndDownloadModal/index.tsx","../../src/services/manage.ts","../../src/pages/warning/strategy/components/SwitchWithLabel.tsx","../../src/components/PromQLInput/CMTheme.tsx","../../node_modules/@babel/runtime/helpers/interopRequireDefault.js","../../node_modules/rc-pagination/lib/locale/zh_CN.js","../../node_modules/@babel/runtime/helpers/extends.js","../../node_modules/rc-picker/lib/locale/zh_CN.js","../../node_modules/antd/lib/time-picker/locale/zh_CN.js","../../node_modules/antd/lib/date-picker/locale/zh_CN.js","../../node_modules/antd/lib/calendar/locale/zh_CN.js","../../node_modules/antd/lib/locale/zh_CN.js","../../node_modules/rc-pagination/lib/locale/en_US.js","../../node_modules/rc-picker/lib/locale/en_US.js","../../node_modules/antd/lib/time-picker/locale/en_US.js","../../node_modules/antd/lib/date-picker/locale/en_US.js","../../node_modules/antd/lib/calendar/locale/en_US.js","../../node_modules/antd/lib/locale/default.js","../../node_modules/antd/lib/locale/en_US.js","../../src/components/ModalHOC.tsx","../../src/components/TimeRangePicker/config.ts","../../src/components/TimeRangePicker/utils.ts","../../src/components/TimeRangePicker/TimeRangePicker.tsx","../../src/components/TimeRangePicker/AutoRefresh/index.tsx","../../src/components/TimeRangePicker/TimeRangePickerWithRefresh.tsx","../../src/components/TimeRangePicker/RelativeTimeRangePicker/utils.ts","../../src/components/TimeRangePicker/RelativeTimeRangePicker/index.tsx","../../src/components/TimeRangePicker/index.tsx","../../src/services/dashboard.ts","../../src/components/PromQueryBuilder/components/FormItem.tsx","../../src/components/PromQueryBuilder/MetricSelect/index.tsx","../../src/components/PromQueryBuilder/LabelFilters/utils.ts","../../src/components/PromQueryBuilder/LabelFilters/LabelNameSelect.tsx","../../src/components/PromQueryBuilder/LabelFilters/LabelValueSelect.tsx","../../src/components/PromQueryBuilder/LabelFilters/index.tsx","../../node_modules/array-move/index.js","../../node_modules/invariant/browser.js","../../node_modules/react-sortable-hoc/dist/react-sortable-hoc.esm.js","../../src/components/PromQueryBuilder/types.ts","../../src/components/PromQueryBuilder/Operations/utils/renderer.ts","../../src/components/PromQueryBuilder/Operations/utils/addOperationHandler.ts","../../src/components/PromQueryBuilder/Operations/utils/createAggregationOperation.ts","../../src/components/PromQueryBuilder/Operations/utils/createRangeFunction.ts","../../src/components/PromQueryBuilder/Operations/utils/createFunction.ts","../../src/components/PromQueryBuilder/Operations/utils/index.ts","../../src/components/PromQueryBuilder/Operations/Operation.tsx","../../src/components/PromQueryBuilder/Operations/index.tsx","../../src/components/PromQueryBuilder/RawQuery/index.tsx","../../src/components/PromQueryBuilder/NestedQueryList/NestedQuery.tsx","../../src/components/PromQueryBuilder/NestedQueryList/index.tsx","../../node_modules/lezer-promql/index.es.js","../../src/components/PromQueryBuilder/utils/buildPromVisualQueryFromPromQL.ts","../../src/components/PromQueryBuilder/index.tsx","../../src/components/PromQueryBuilder/utils/index.ts","../../src/components/PromQueryBuilder/PromQueryBuilderModal.tsx","../../src/components/PromQLInput/PromQLInputWithBuilder.tsx","../../src/components/PromQLInput/index.tsx","../../src/pages/warning/strategy/components/AbnormalDetection/index.tsx","../../src/components/InputGroupWithFormItem/index.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/Values/index.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/GroupBy/configs.ts","../../src/pages/warning/strategy/components/ElasticsearchSettings/GroupBy/Filters.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/GroupBy/Terms.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/GroupBy/Histgram.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/GroupBy/index.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/Time/index.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/Rules/configs.ts","../../src/pages/warning/strategy/components/ElasticsearchSettings/Rules/Rule.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/Rules/index.tsx","../../node_modules/@fc-plot/ts-graph/dist/index.js","../../src/pages/dashboard/config.tsx","../../src/pages/dashboard/Renderer/config.ts","../../src/pages/dashboard/Renderer/utils/byteConverter.ts","../../src/pages/dashboard/Renderer/utils/valueFormatter.ts","../../src/pages/dashboard/Renderer/utils/getCalculatedValuesBySeries.ts","../../src/pages/dashboard/Renderer/Renderer/Timeseries/index.tsx","../../src/pages/warning/strategy/components/utils.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/GraphPreview.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/IndexSelect.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/Old.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/Queries/Value.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/Queries/index.tsx","../../src/pages/warning/strategy/components/AliyunSLSSettings/Triggers/Builder.tsx","../../src/pages/warning/strategy/components/AliyunSLSSettings/Triggers/Code.tsx","../../src/pages/warning/strategy/components/AliyunSLSSettings/Triggers/Trigger.tsx","../../src/pages/warning/strategy/components/AliyunSLSSettings/Triggers/index.tsx","../../src/pages/warning/strategy/components/ElasticsearchSettings/index.tsx","../../src/services/metric.ts","../../src/pages/metric/explorer/AliyunSLS/ProjectSelect.tsx","../../src/pages/metric/explorer/AliyunSLS/LogstoreSelect.tsx","../../node_modules/react-markdown/lib/uri-transformer.js","../../node_modules/unist-util-stringify-position/index.js","../../node_modules/vfile-message/index.js","../../node_modules/vfile/lib/minpath.browser.js","../../node_modules/vfile/lib/minproc.browser.js","../../node_modules/vfile/lib/minurl.shared.js","../../node_modules/vfile/lib/minurl.browser.js","../../node_modules/vfile/lib/index.js","../../node_modules/vfile/node_modules/is-buffer/index.js","../../node_modules/bail/index.js","../../node_modules/extend/index.js","../../node_modules/unified/node_modules/is-plain-obj/index.js","../../node_modules/trough/index.js","../../node_modules/unified/lib/index.js","../../node_modules/unified/node_modules/is-buffer/index.js","../../node_modules/mdast-util-to-string/index.js","../../node_modules/micromark-util-chunked/index.js","../../node_modules/micromark-util-combine-extensions/index.js","../../node_modules/micromark-util-character/lib/unicode-punctuation-regex.js","../../node_modules/micromark-util-character/index.js","../../node_modules/micromark-factory-space/index.js","../../node_modules/micromark/lib/initialize/content.js","../../node_modules/micromark/lib/initialize/document.js","../../node_modules/micromark-util-classify-character/index.js","../../node_modules/micromark-util-resolve-all/index.js","../../node_modules/micromark-core-commonmark/lib/attention.js","../../node_modules/micromark-core-commonmark/lib/autolink.js","../../node_modules/micromark-core-commonmark/lib/blank-line.js","../../node_modules/micromark-core-commonmark/lib/block-quote.js","../../node_modules/micromark-core-commonmark/lib/character-escape.js","../../node_modules/decode-named-character-reference/index.dom.js","../../node_modules/micromark-core-commonmark/lib/character-reference.js","../../node_modules/micromark-core-commonmark/lib/code-fenced.js","../../node_modules/micromark-core-commonmark/lib/code-indented.js","../../node_modules/micromark-core-commonmark/lib/code-text.js","../../node_modules/micromark-util-subtokenize/index.js","../../node_modules/micromark-core-commonmark/lib/content.js","../../node_modules/micromark-factory-destination/index.js","../../node_modules/micromark-factory-label/index.js","../../node_modules/micromark-factory-title/index.js","../../node_modules/micromark-factory-whitespace/index.js","../../node_modules/micromark-util-normalize-identifier/index.js","../../node_modules/micromark-core-commonmark/lib/definition.js","../../node_modules/micromark-core-commonmark/lib/hard-break-escape.js","../../node_modules/micromark-core-commonmark/lib/heading-atx.js","../../node_modules/micromark-util-html-tag-name/index.js","../../node_modules/micromark-core-commonmark/lib/html-flow.js","../../node_modules/micromark-core-commonmark/lib/html-text.js","../../node_modules/micromark-core-commonmark/lib/label-end.js","../../node_modules/micromark-core-commonmark/lib/label-start-image.js","../../node_modules/micromark-core-commonmark/lib/label-start-link.js","../../node_modules/micromark-core-commonmark/lib/line-ending.js","../../node_modules/micromark-core-commonmark/lib/thematic-break.js","../../node_modules/micromark-core-commonmark/lib/list.js","../../node_modules/micromark-core-commonmark/lib/setext-underline.js","../../node_modules/micromark/lib/initialize/flow.js","../../node_modules/micromark/lib/initialize/text.js","../../node_modules/micromark/lib/create-tokenizer.js","../../node_modules/micromark/lib/constructs.js","../../node_modules/micromark/lib/parse.js","../../node_modules/micromark/lib/preprocess.js","../../node_modules/micromark-util-decode-numeric-character-reference/index.js","../../node_modules/micromark-util-decode-string/index.js","../../node_modules/mdast-util-from-markdown/lib/index.js","../../node_modules/micromark/lib/postprocess.js","../../node_modules/remark-parse/lib/index.js","../../node_modules/unist-builder/index.js","../../node_modules/mdast-util-to-hast/lib/traverse.js","../../node_modules/unist-util-is/index.js","../../node_modules/unist-util-visit/node_modules/unist-util-visit-parents/index.js","../../node_modules/unist-util-visit/index.js","../../node_modules/unist-util-position/index.js","../../node_modules/mdast-util-definitions/node_modules/unist-util-visit-parents/index.js","../../node_modules/mdast-util-definitions/node_modules/unist-util-visit/index.js","../../node_modules/mdast-util-definitions/index.js","../../node_modules/mdast-util-to-hast/lib/handlers/thematic-break.js","../../node_modules/mdast-util-to-hast/lib/wrap.js","../../node_modules/mdast-util-to-hast/lib/handlers/list.js","../../node_modules/mdast-util-to-hast/lib/handlers/footnote-reference.js","../../node_modules/mdurl/encode.js","../../node_modules/mdast-util-to-hast/lib/revert.js","../../node_modules/mdast-util-to-hast/lib/handlers/list-item.js","../../node_modules/mdast-util-to-hast/lib/handlers/index.js","../../node_modules/mdast-util-to-hast/lib/handlers/blockquote.js","../../node_modules/mdast-util-to-hast/lib/handlers/break.js","../../node_modules/mdast-util-to-hast/lib/handlers/code.js","../../node_modules/mdast-util-to-hast/lib/handlers/delete.js","../../node_modules/mdast-util-to-hast/lib/handlers/emphasis.js","../../node_modules/mdast-util-to-hast/lib/handlers/footnote.js","../../node_modules/mdast-util-to-hast/lib/handlers/heading.js","../../node_modules/mdast-util-to-hast/lib/handlers/html.js","../../node_modules/mdast-util-to-hast/lib/handlers/image-reference.js","../../node_modules/mdast-util-to-hast/lib/handlers/image.js","../../node_modules/mdast-util-to-hast/lib/handlers/inline-code.js","../../node_modules/mdast-util-to-hast/lib/handlers/link-reference.js","../../node_modules/mdast-util-to-hast/lib/handlers/link.js","../../node_modules/mdast-util-to-hast/lib/handlers/paragraph.js","../../node_modules/mdast-util-to-hast/lib/handlers/root.js","../../node_modules/mdast-util-to-hast/lib/handlers/strong.js","../../node_modules/mdast-util-to-hast/lib/handlers/table.js","../../node_modules/mdast-util-to-hast/lib/handlers/text.js","../../node_modules/mdast-util-to-hast/lib/index.js","../../node_modules/unist-util-generated/index.js","../../node_modules/mdast-util-to-hast/lib/footer.js","../../node_modules/remark-rehype/index.js","../../node_modules/property-information/lib/util/schema.js","../../node_modules/property-information/lib/util/merge.js","../../node_modules/property-information/lib/normalize.js","../../node_modules/property-information/lib/util/info.js","../../node_modules/property-information/lib/util/types.js","../../node_modules/property-information/lib/util/defined-info.js","../../node_modules/property-information/lib/util/create.js","../../node_modules/property-information/lib/xlink.js","../../node_modules/property-information/lib/xml.js","../../node_modules/property-information/lib/util/case-sensitive-transform.js","../../node_modules/property-information/lib/util/case-insensitive-transform.js","../../node_modules/property-information/lib/xmlns.js","../../node_modules/property-information/lib/aria.js","../../node_modules/property-information/lib/html.js","../../node_modules/property-information/lib/svg.js","../../node_modules/property-information/lib/find.js","../../node_modules/property-information/lib/hast-to-react.js","../../node_modules/property-information/index.js","../../node_modules/react-markdown/lib/rehype-filter.js","../../node_modules/react-markdown/node_modules/react-is/cjs/react-is.production.min.js","../../node_modules/react-markdown/node_modules/react-is/index.js","../../node_modules/space-separated-tokens/index.js","../../node_modules/comma-separated-tokens/index.js","../../node_modules/inline-style-parser/index.js","../../node_modules/style-to-object/index.js","../../node_modules/react-markdown/lib/ast-to-react.js","../../node_modules/hast-util-whitespace/index.js","../../node_modules/react-markdown/lib/react-markdown.js","../../node_modules/micromark-extension-gfm/node_modules/micromark/dist/constant/has-own-property.js","../../node_modules/micromark-extension-gfm/node_modules/micromark/dist/util/chunked-splice.js","../../node_modules/micromark-extension-gfm/node_modules/micromark/dist/constant/splice.js","../../node_modules/micromark-extension-gfm/node_modules/micromark/dist/util/combine-extensions.js","../../node_modules/micromark-extension-gfm/node_modules/micromark/dist/util/miniflat.js","../../node_modules/micromark-extension-gfm-autolink-literal/node_modules/micromark/dist/util/regex-check.js","../../node_modules/micromark-extension-gfm-autolink-literal/node_modules/micromark/dist/constant/from-char-code.js","../../node_modules/micromark-extension-gfm-autolink-literal/node_modules/micromark/dist/character/ascii-alpha.js","../../node_modules/micromark-extension-gfm-autolink-literal/node_modules/micromark/dist/character/ascii-alphanumeric.js","../../node_modules/micromark-extension-gfm-autolink-literal/node_modules/micromark/dist/character/ascii-control.js","../../node_modules/micromark-extension-gfm-autolink-literal/node_modules/micromark/dist/character/markdown-line-ending.js","../../node_modules/micromark-extension-gfm-autolink-literal/node_modules/micromark/dist/character/unicode-punctuation.js","../../node_modules/micromark-extension-gfm-autolink-literal/node_modules/micromark/dist/constant/unicode-punctuation-regex.js","../../node_modules/micromark-extension-gfm-autolink-literal/node_modules/micromark/dist/character/unicode-whitespace.js","../../node_modules/micromark-extension-gfm-autolink-literal/syntax.js","../../node_modules/micromark-extension-gfm-autolink-literal/index.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/character/markdown-line-ending-or-space.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/constant/unicode-punctuation-regex.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/util/regex-check.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/constant/from-char-code.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/character/unicode-punctuation.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/character/unicode-whitespace.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/util/classify-character.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/util/chunked-splice.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/constant/splice.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/util/resolve-all.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/util/shallow.js","../../node_modules/micromark-extension-gfm-strikethrough/node_modules/micromark/dist/constant/assign.js","../../node_modules/micromark-extension-gfm-strikethrough/index.js","../../node_modules/micromark-extension-gfm-table/node_modules/micromark/dist/tokenize/factory-space.js","../../node_modules/micromark-extension-gfm-table/node_modules/micromark/dist/character/markdown-space.js","../../node_modules/micromark-extension-gfm-table/syntax.js","../../node_modules/micromark-extension-gfm-table/index.js","../../node_modules/micromark-extension-gfm-task-list-item/node_modules/micromark/dist/tokenize/factory-space.js","../../node_modules/micromark-extension-gfm-task-list-item/node_modules/micromark/dist/character/markdown-space.js","../../node_modules/micromark-extension-gfm-task-list-item/node_modules/micromark/dist/util/prefix-size.js","../../node_modules/micromark-extension-gfm-task-list-item/node_modules/micromark/dist/util/size-chunks.js","../../node_modules/micromark-extension-gfm-task-list-item/syntax.js","../../node_modules/micromark-extension-gfm-task-list-item/node_modules/micromark/dist/character/markdown-line-ending-or-space.js","../../node_modules/micromark-extension-gfm/syntax.js","../../node_modules/micromark-extension-gfm-task-list-item/index.js","../../node_modules/micromark-extension-gfm/index.js","../../node_modules/ccount/index.js","../../node_modules/unist-util-visit-parents/node_modules/unist-util-is/convert.js","../../node_modules/unist-util-visit-parents/index.js","../../node_modules/unist-util-visit-parents/color.browser.js","../../node_modules/mdast-util-find-and-replace/node_modules/unist-util-is/convert.js","../../node_modules/mdast-util-find-and-replace/index.js","../../node_modules/mdast-util-find-and-replace/node_modules/escape-string-regexp/index.js","../../node_modules/mdast-util-gfm-autolink-literal/node_modules/micromark/dist/constant/unicode-punctuation-regex.js","../../node_modules/mdast-util-gfm-autolink-literal/node_modules/micromark/dist/util/regex-check.js","../../node_modules/mdast-util-gfm-autolink-literal/node_modules/micromark/dist/constant/from-char-code.js","../../node_modules/mdast-util-gfm-autolink-literal/node_modules/micromark/dist/character/unicode-punctuation.js","../../node_modules/mdast-util-gfm-autolink-literal/node_modules/micromark/dist/character/unicode-whitespace.js","../../node_modules/mdast-util-gfm-autolink-literal/from-markdown.js","../../node_modules/mdast-util-gfm-strikethrough/from-markdown.js","../../node_modules/mdast-util-gfm-table/from-markdown.js","../../node_modules/mdast-util-gfm-task-list-item/from-markdown.js","../../node_modules/mdast-util-gfm/from-markdown.js","../../node_modules/mdast-util-gfm-autolink-literal/to-markdown.js","../../node_modules/mdast-util-to-markdown/lib/util/container-phrasing.js","../../node_modules/mdast-util-gfm-strikethrough/to-markdown.js","../../node_modules/mdast-util-to-markdown/lib/util/pattern-compile.js","../../node_modules/mdast-util-to-markdown/lib/handle/inline-code.js","../../node_modules/repeat-string/index.js","../../node_modules/markdown-table/index.js","../../node_modules/mdast-util-gfm-table/to-markdown.js","../../node_modules/mdast-util-to-markdown/lib/util/container-flow.js","../../node_modules/mdast-util-to-markdown/lib/util/indent-lines.js","../../node_modules/mdast-util-to-markdown/lib/handle/list-item.js","../../node_modules/mdast-util-to-markdown/lib/util/check-bullet.js","../../node_modules/mdast-util-to-markdown/lib/util/check-list-item-indent.js","../../node_modules/mdast-util-gfm-task-list-item/to-markdown.js","../../node_modules/mdast-util-gfm/to-markdown.js","../../node_modules/mdast-util-to-markdown/lib/configure.js","../../node_modules/remark-gfm/index.js","../../node_modules/parse5/lib/common/unicode.js","../../node_modules/parse5/lib/common/error-codes.js","../../node_modules/parse5/lib/tokenizer/preprocessor.js","../../node_modules/parse5/lib/tokenizer/named-entity-data.js","../../node_modules/parse5/lib/tokenizer/index.js","../../node_modules/parse5/lib/common/html.js","../../node_modules/parse5/lib/parser/open-element-stack.js","../../node_modules/parse5/lib/parser/formatting-element-list.js","../../node_modules/parse5/lib/utils/mixin.js","../../node_modules/parse5/lib/extensions/position-tracking/preprocessor-mixin.js","../../node_modules/parse5/lib/extensions/location-info/tokenizer-mixin.js","../../node_modules/parse5/lib/extensions/location-info/open-element-stack-mixin.js","../../node_modules/parse5/lib/extensions/location-info/parser-mixin.js","../../node_modules/parse5/lib/extensions/error-reporting/mixin-base.js","../../node_modules/parse5/lib/extensions/error-reporting/preprocessor-mixin.js","../../node_modules/parse5/lib/extensions/error-reporting/tokenizer-mixin.js","../../node_modules/parse5/lib/extensions/error-reporting/parser-mixin.js","../../node_modules/parse5/lib/tree-adapters/default.js","../../node_modules/parse5/lib/common/doctype.js","../../node_modules/parse5/lib/common/foreign-content.js","../../node_modules/parse5/lib/parser/index.js","../../node_modules/parse5/lib/utils/merge-options.js","../../node_modules/hast-util-parse-selector/index.js","../../node_modules/hastscript/lib/core.js","../../node_modules/hastscript/lib/html.js","../../node_modules/hastscript/lib/svg.js","../../node_modules/hastscript/lib/svg-case-sensitive-tag-names.js","../../node_modules/web-namespaces/index.js","../../node_modules/hast-util-from-parse5/lib/index.js","../../node_modules/vfile-location/index.js","../../node_modules/hast-to-hyperscript/index.js","../../node_modules/zwitch/index.js","../../node_modules/hast-util-to-parse5/lib/index.js","../../node_modules/html-void-elements/index.js","../../node_modules/hast-util-raw/lib/index.js","../../node_modules/rehype-raw/index.js","../../src/components/DataSource/components/Markdown/index.tsx","../../src/pages/metric/explorer/AliyunSLS/Query.tsx","../../src/pages/warning/strategy/components/AliyunSLSSettings/Queries/GraphPreview.tsx","../../src/pages/warning/strategy/components/AliyunSLSSettings/Queries/AdvancedSettings.tsx","../../src/pages/warning/strategy/components/AliyunSLSSettings/Queries/index.tsx","../../src/pages/warning/strategy/components/AliyunSLSSettings/index.tsx","../../src/pages/warning/strategy/components/CateSelect/index.tsx","../../src/pages/warning/strategy/components/ClusterSelect/index.tsx","../../src/pages/warning/strategy/components/operateForm.tsx","../../src/pages/warning/strategy/components/editModal.tsx","../../src/components/ColumnSelect/index.tsx","../../src/pages/warning/strategy/PageTable.tsx","../../src/pages/warning/strategy/index.tsx","../../src/pages/account/changePassword.tsx","../../src/pages/account/info.tsx","../../src/pages/account/profile.tsx","../../src/services/dashboardV2.ts","../../node_modules/uuid/dist/esm-browser/rng.js","../../node_modules/uuid/dist/esm-browser/regex.js","../../node_modules/uuid/dist/esm-browser/validate.js","../../node_modules/uuid/dist/esm-browser/stringify.js","../../node_modules/uuid/dist/esm-browser/v4.js","../../src/pages/dashboard/Components/ColorRangeMenu/config.ts","../../src/pages/dashboard/Editor/config.tsx","../../src/pages/dashboard/utils.ts","../../src/pages/dashboard/List/Form.tsx","../../node_modules/semver/internal/constants.js","../../node_modules/semver/internal/debug.js","../../node_modules/semver/internal/re.js","../../node_modules/semver/internal/parse-options.js","../../node_modules/semver/internal/identifiers.js","../../node_modules/semver/classes/semver.js","../../node_modules/semver/functions/parse.js","../../node_modules/semver/functions/valid.js","../../node_modules/semver/functions/clean.js","../../node_modules/semver/functions/inc.js","../../node_modules/semver/functions/compare.js","../../node_modules/semver/functions/eq.js","../../node_modules/semver/functions/diff.js","../../node_modules/semver/functions/major.js","../../node_modules/semver/functions/minor.js","../../node_modules/semver/functions/patch.js","../../node_modules/semver/functions/prerelease.js","../../node_modules/semver/functions/rcompare.js","../../node_modules/semver/functions/compare-loose.js","../../node_modules/semver/functions/compare-build.js","../../node_modules/semver/functions/sort.js","../../node_modules/semver/functions/rsort.js","../../node_modules/semver/functions/gt.js","../../node_modules/semver/functions/lt.js","../../node_modules/semver/functions/neq.js","../../node_modules/semver/functions/gte.js","../../node_modules/semver/functions/lte.js","../../node_modules/semver/functions/cmp.js","../../node_modules/semver/functions/coerce.js","../../node_modules/semver/classes/range.js","../../node_modules/semver/classes/comparator.js","../../node_modules/semver/functions/satisfies.js","../../node_modules/semver/ranges/to-comparators.js","../../node_modules/semver/ranges/max-satisfying.js","../../node_modules/semver/ranges/min-satisfying.js","../../node_modules/semver/ranges/min-version.js","../../node_modules/semver/ranges/valid.js","../../node_modules/semver/ranges/outside.js","../../node_modules/semver/ranges/gtr.js","../../node_modules/semver/ranges/ltr.js","../../node_modules/semver/ranges/intersects.js","../../node_modules/semver/ranges/simplify.js","../../node_modules/semver/ranges/subset.js","../../node_modules/semver/index.js","../../src/pages/help/migrate/utils.ts","../../src/pages/dashboard/List/utils.ts","../../src/pages/dashboard/List/Import.tsx","../../src/pages/dashboard/List/Header.tsx","../../src/pages/dashboard/List/Export.tsx","../../src/pages/dashboard/List/index.tsx","../../src/components/Resolution/index.tsx","../../src/components/Graph/config.jsx","../../src/components/Graph/util/normalizeSeries.tsx","../../src/components/D3Charts/src/interface.ts","../../src/components/Graph/util/getTooltipsContent.jsx","../../src/components/Graph/util/getYAxis.jsx","../../src/components/Graph/util/index.jsx","../../src/components/Graph/api.ts","../../src/components/Graph/Graph/Legend.tsx","../../src/components/Graph/GraphConfig/Comparison.tsx","../../src/components/Graph/GraphConfig/GraphConfigInner.tsx","../../node_modules/resize-detector/esm/index.js","../../src/components/D3Charts/src/utils.ts","../../src/components/D3Charts/src/xAxis.ts","../../src/components/D3Charts/src/yAxis.ts","../../src/components/D3Charts/src/tooltip.ts","../../src/components/D3Charts/src/line.ts","../../src/components/D3Charts/src/stackArea.ts","../../src/components/D3Charts/src/zoom.ts","../../src/components/D3Charts/src/legend.ts","../../src/components/D3Charts/src/index.ts","../../src/components/Graph/Graph/Graph.tsx","../../src/components/DateRangePicker/index.tsx","../../src/components/Graph/Graph/index.tsx","../../node_modules/zustand/esm/vanilla.js","../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.min.js","../../node_modules/use-sync-external-store/shim/index.js","../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.min.js","../../node_modules/use-sync-external-store/shim/with-selector.js","../../node_modules/zustand/esm/index.js","../../node_modules/react-hooks-global-state/dist/index.modern.js","../../src/pages/dashboard/globalState.ts","../../src/pages/dashboard/Renderer/Renderer/Stat/index.tsx","../../node_modules/@minko-fe/use-antd-resizable-header/dist/index.es.js","../../src/pages/dashboard/Renderer/utils/getOverridePropertiesByName.ts","../../src/pages/dashboard/Renderer/utils/localeCompare.ts","../../src/pages/dashboard/Renderer/Renderer/Table/index.tsx","../../src/pages/dashboard/Renderer/utils/formatToTable.ts","../../src/pages/dashboard/Renderer/Renderer/Table/utils.ts","../../node_modules/tslib/tslib.es6.js","../../node_modules/@antv/util/esm/is-array-like.js","../../node_modules/@antv/util/esm/contains.js","../../node_modules/@antv/util/esm/filter.js","../../node_modules/@antv/util/esm/is-type.js","../../node_modules/@antv/util/esm/is-function.js","../../node_modules/@antv/util/esm/is-nil.js","../../node_modules/@antv/util/esm/is-array.js","../../node_modules/@antv/util/esm/is-object.js","../../node_modules/@antv/util/esm/each.js","../../node_modules/@antv/util/esm/keys.js","../../node_modules/@antv/util/esm/is-match.js","../../node_modules/@antv/util/esm/is-object-like.js","../../node_modules/@antv/util/esm/is-plain-object.js","../../node_modules/@antv/util/esm/find.js","../../node_modules/@antv/util/esm/find-index.js","../../node_modules/@antv/util/esm/first-value.js","../../node_modules/@antv/util/esm/flatten.js","../../node_modules/@antv/util/esm/max.js","../../node_modules/@antv/util/esm/min.js","../../node_modules/@antv/util/esm/get-range.js","../../node_modules/@antv/util/esm/pull-at.js","../../node_modules/@antv/util/esm/reduce.js","../../node_modules/@antv/util/esm/remove.js","../../node_modules/@antv/util/esm/is-string.js","../../node_modules/@antv/util/esm/uniq.js","../../node_modules/@antv/util/esm/values-of-key.js","../../node_modules/@antv/util/esm/head.js","../../node_modules/@antv/util/esm/last.js","../../node_modules/@antv/util/esm/every.js","../../node_modules/@antv/util/esm/some.js","../../node_modules/@antv/util/esm/group-by.js","../../node_modules/@antv/util/esm/group-to-map.js","../../node_modules/@antv/util/esm/group.js","../../node_modules/@antv/util/esm/clamp.js","../../node_modules/@antv/util/esm/fixed-base.js","../../node_modules/@antv/util/esm/is-number.js","../../node_modules/@antv/util/esm/is-number-equal.js","../../node_modules/@antv/util/esm/max-by.js","../../node_modules/@antv/util/esm/mod.js","../../node_modules/@antv/util/esm/to-radian.js","../../node_modules/@antv/util/esm/has.js","../../node_modules/@antv/util/esm/values.js","../../node_modules/@antv/util/esm/to-string.js","../../node_modules/@antv/util/esm/lower-case.js","../../node_modules/@antv/util/esm/substitute.js","../../node_modules/@antv/util/esm/upper-first.js","../../node_modules/@antv/util/esm/get-type.js","../../node_modules/@antv/util/esm/is-boolean.js","../../node_modules/@antv/util/esm/is-date.js","../../node_modules/@antv/util/esm/is-prototype.js","../../node_modules/@antv/util/esm/is-undefined.js","../../node_modules/@antv/util/esm/is-element.js","../../node_modules/@antv/util/esm/mix.js","../../node_modules/@antv/util/esm/clone.js","../../node_modules/@antv/util/esm/debounce.js","../../node_modules/@antv/util/esm/memoize.js","../../node_modules/@antv/util/esm/deep-mix.js","../../node_modules/@antv/util/esm/index-of.js","../../node_modules/@antv/util/esm/is-empty.js","../../node_modules/@antv/util/esm/is-equal.js","../../node_modules/@antv/util/esm/measure-text-width.js","../../node_modules/@antv/util/esm/map.js","../../node_modules/@antv/util/esm/map-values.js","../../node_modules/@antv/util/esm/get.js","../../node_modules/@antv/util/esm/set.js","../../node_modules/@antv/util/esm/pick.js","../../node_modules/@antv/util/esm/omit.js","../../node_modules/@antv/util/esm/throttle.js","../../node_modules/@antv/util/esm/unique-id.js","../../node_modules/@antv/util/esm/noop.js","../../node_modules/@antv/util/esm/size.js","../../node_modules/@antv/g2/esm/constant.js","../../node_modules/@antv/util/esm/cache.js","../../node_modules/@antv/dom-util/esm/create-dom.js","../../node_modules/@antv/g2/esm/engine/index.js","../../node_modules/@antv/dom-util/esm/add-event-listener.js","../../node_modules/@antv/dom-util/esm/get-style.js","../../node_modules/@antv/dom-util/esm/get-outer-height.js","../../node_modules/@antv/dom-util/esm/get-height.js","../../node_modules/@antv/dom-util/esm/get-outer-width.js","../../node_modules/@antv/dom-util/esm/get-width.js","../../node_modules/@antv/dom-util/esm/modify-css.js","../../node_modules/@antv/g2/esm/util/dom.js","../../node_modules/@antv/event-emitter/esm/index.js","../../node_modules/@antv/g2/esm/base.js","../../node_modules/@antv/g-base/esm/util/path.js","../../node_modules/@antv/g-base/esm/event/graph-event.js","../../node_modules/@antv/g-base/esm/util/util.js","../../node_modules/@antv/g-base/esm/abstract/base.js","../../node_modules/detect-browser/es/index.js","../../node_modules/gl-matrix/esm/common.js","../../node_modules/gl-matrix/esm/vec3.js","../../node_modules/gl-matrix/esm/mat3.js","../../node_modules/gl-matrix/esm/vec2.js","../../node_modules/@antv/matrix-util/esm/ext.js","../../node_modules/@antv/g-base/esm/util/matrix.js","../../node_modules/@antv/g-base/esm/abstract/element.js","../../node_modules/@antv/g-base/esm/abstract/container.js","../../node_modules/@antv/g-base/node_modules/d3-timer/src/timer.js","../../node_modules/@antv/g-base/node_modules/d3-ease/src/quad.js","../../node_modules/@antv/g-base/node_modules/d3-ease/src/cubic.js","../../node_modules/@antv/g-base/node_modules/d3-ease/src/poly.js","../../node_modules/@antv/g-base/node_modules/d3-ease/src/sin.js","../../node_modules/@antv/g-base/node_modules/d3-ease/src/math.js","../../node_modules/@antv/g-base/node_modules/d3-ease/src/exp.js","../../node_modules/@antv/g-base/node_modules/d3-ease/src/circle.js","../../node_modules/@antv/g-base/node_modules/d3-ease/src/bounce.js","../../node_modules/@antv/g-base/node_modules/d3-ease/src/back.js","../../node_modules/@antv/g-base/node_modules/d3-ease/src/elastic.js","../../node_modules/@antv/g-base/node_modules/d3-ease/src/linear.js","../../node_modules/@antv/g-base/node_modules/d3-interpolate/src/constant.js","../../node_modules/@antv/g-base/node_modules/d3-interpolate/src/color.js","../../node_modules/@antv/g-base/node_modules/d3-interpolate/src/rgb.js","../../node_modules/@antv/g-base/node_modules/d3-interpolate/src/numberArray.js","../../node_modules/@antv/g-base/node_modules/d3-interpolate/src/array.js","../../node_modules/@antv/g-base/node_modules/d3-interpolate/src/date.js","../../node_modules/@antv/g-base/node_modules/d3-interpolate/src/number.js","../../node_modules/@antv/g-base/node_modules/d3-interpolate/src/object.js","../../node_modules/@antv/g-base/node_modules/d3-interpolate/src/string.js","../../node_modules/@antv/g-base/node_modules/d3-interpolate/src/value.js","../../node_modules/@antv/g-base/esm/util/color.js","../../node_modules/@antv/g-base/esm/animate/timeline.js","../../node_modules/@antv/g-base/esm/event/event-contoller.js","../../node_modules/@antv/g-base/esm/abstract/canvas.js","../../node_modules/@antv/g-base/esm/abstract/group.js","../../node_modules/@antv/g-base/esm/abstract/shape.js","../../node_modules/@antv/g-base/esm/bbox/register.js","../../node_modules/@antv/g-base/esm/bbox/rect.js","../../node_modules/@antv/g-base/esm/bbox/circle.js","../../node_modules/@antv/g-math/esm/util.js","../../node_modules/@antv/g-math/esm/line.js","../../node_modules/@antv/g-math/esm/bezier.js","../../node_modules/@antv/g-math/esm/quadratic.js","../../node_modules/@antv/g-math/esm/cubic.js","../../node_modules/@antv/g-math/esm/arc.js","../../node_modules/@antv/g-math/esm/polyline.js","../../node_modules/@antv/g-math/esm/segments.js","../../node_modules/@antv/g-base/esm/bbox/util.js","../../node_modules/@antv/g-base/esm/util/offscreen.js","../../node_modules/@antv/g-base/esm/util/text.js","../../node_modules/@antv/path-util/esm/parse-path.js","../../node_modules/@antv/path-util/esm/catmull-rom-2-bezier.js","../../node_modules/@antv/path-util/esm/parse-path-string.js","../../node_modules/@antv/path-util/esm/path-2-absolute.js","../../node_modules/@antv/path-util/esm/get-arc-params.js","../../node_modules/@antv/path-util/esm/path-2-segments.js","../../node_modules/@antv/path-util/esm/get-line-intersect.js","../../node_modules/@antv/path-util/esm/point-in-polygon.js","../../node_modules/@antv/path-util/esm/is-polygons-intersect.js","../../node_modules/@antv/g-base/esm/bbox/path.js","../../node_modules/@antv/g-base/esm/bbox/index.js","../../node_modules/@antv/g-base/esm/bbox/polyline.js","../../node_modules/@antv/g-base/esm/bbox/polygon.js","../../node_modules/@antv/g-base/esm/bbox/text.js","../../node_modules/@antv/g-base/esm/bbox/line.js","../../node_modules/@antv/g-base/esm/bbox/ellipse.js","../../node_modules/@antv/adjust/esm/constant.js","../../node_modules/@antv/adjust/esm/adjusts/adjust.js","../../node_modules/@antv/adjust/esm/factory.js","../../node_modules/@antv/adjust/node_modules/tslib/tslib.es6.js","../../node_modules/@antv/adjust/esm/adjusts/dodge.js","../../node_modules/@antv/adjust/esm/adjusts/jitter.js","../../node_modules/@antv/adjust/esm/adjusts/stack.js","../../node_modules/@antv/adjust/esm/adjusts/symmetric.js","../../node_modules/@antv/adjust/esm/index.js","../../node_modules/@antv/attr/esm/attributes/base.js","../../node_modules/@antv/attr/node_modules/tslib/tslib.es6.js","../../node_modules/@antv/color-util/esm/index.js","../../node_modules/@antv/attr/esm/attributes/color.js","../../node_modules/@antv/attr/esm/attributes/opacity.js","../../node_modules/@antv/attr/esm/attributes/position.js","../../node_modules/@antv/attr/esm/attributes/shape.js","../../node_modules/@antv/attr/esm/attributes/size.js","../../node_modules/@antv/scale/esm/tick-method/register.js","../../node_modules/@antv/scale/esm/base.js","../../node_modules/@antv/scale/esm/category/base.js","../../node_modules/fecha/lib/fecha.js","../../node_modules/@antv/scale/esm/util/time.js","../../node_modules/@antv/scale/esm/util/bisector.js","../../node_modules/@antv/scale/esm/category/time.js","../../node_modules/@antv/scale/esm/continuous/base.js","../../node_modules/@antv/scale/esm/continuous/linear.js","../../node_modules/@antv/scale/esm/util/math.js","../../node_modules/@antv/scale/esm/continuous/log.js","../../node_modules/@antv/scale/esm/continuous/pow.js","../../node_modules/@antv/scale/esm/continuous/time.js","../../node_modules/@antv/scale/esm/continuous/quantize.js","../../node_modules/@antv/scale/esm/continuous/quantile.js","../../node_modules/@antv/scale/esm/factory.js","../../node_modules/@antv/scale/esm/identity/index.js","../../node_modules/@antv/scale/esm/util/pretty-number.js","../../node_modules/@antv/scale/esm/util/extended.js","../../node_modules/@antv/scale/esm/tick-method/cat.js","../../node_modules/@antv/scale/esm/util/d3-linear.js","../../node_modules/@antv/scale/esm/util/interval.js","../../node_modules/@antv/scale/esm/util/strict-limit.js","../../node_modules/@antv/scale/esm/util/pretty.js","../../node_modules/@antv/scale/esm/tick-method/quantile.js","../../node_modules/@antv/scale/esm/tick-method/time-pretty.js","../../node_modules/@antv/scale/esm/tick-method/index.js","../../node_modules/@antv/scale/esm/tick-method/time-cat.js","../../node_modules/@antv/scale/esm/tick-method/linear.js","../../node_modules/@antv/scale/esm/tick-method/r-prettry.js","../../node_modules/@antv/scale/esm/tick-method/time.js","../../node_modules/@antv/scale/esm/tick-method/log.js","../../node_modules/@antv/scale/esm/tick-method/pow.js","../../node_modules/@antv/scale/esm/tick-method/d3-linear.js","../../node_modules/@antv/scale/esm/index.js","../../node_modules/@antv/attr/esm/factory.js","../../node_modules/@antv/attr/esm/index.js","../../node_modules/@antv/coord/esm/coord/base.js","../../node_modules/@antv/coord/esm/coord/cartesian.js","../../node_modules/@antv/coord/esm/coord/helix.js","../../node_modules/@antv/coord/esm/coord/polar.js","../../node_modules/@antv/coord/esm/factory.js","../../node_modules/@antv/coord/esm/index.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/util/path.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/event/graph-event.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/util/util.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/abstract/base.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/util/matrix.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/abstract/element.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/abstract/container.js","../../node_modules/@antv/component/node_modules/d3-timer/src/timer.js","../../node_modules/@antv/component/node_modules/d3-ease/src/quad.js","../../node_modules/@antv/component/node_modules/d3-ease/src/cubic.js","../../node_modules/@antv/component/node_modules/d3-ease/src/poly.js","../../node_modules/@antv/component/node_modules/d3-ease/src/sin.js","../../node_modules/@antv/component/node_modules/d3-ease/src/math.js","../../node_modules/@antv/component/node_modules/d3-ease/src/exp.js","../../node_modules/@antv/component/node_modules/d3-ease/src/circle.js","../../node_modules/@antv/component/node_modules/d3-ease/src/bounce.js","../../node_modules/@antv/component/node_modules/d3-ease/src/back.js","../../node_modules/@antv/component/node_modules/d3-ease/src/elastic.js","../../node_modules/@antv/component/node_modules/d3-ease/src/linear.js","../../node_modules/@antv/component/node_modules/d3-interpolate/src/constant.js","../../node_modules/@antv/component/node_modules/d3-interpolate/src/color.js","../../node_modules/@antv/component/node_modules/d3-interpolate/src/rgb.js","../../node_modules/@antv/component/node_modules/d3-interpolate/src/numberArray.js","../../node_modules/@antv/component/node_modules/d3-interpolate/src/array.js","../../node_modules/@antv/component/node_modules/d3-interpolate/src/date.js","../../node_modules/@antv/component/node_modules/d3-interpolate/src/number.js","../../node_modules/@antv/component/node_modules/d3-interpolate/src/object.js","../../node_modules/@antv/component/node_modules/d3-interpolate/src/string.js","../../node_modules/@antv/component/node_modules/d3-interpolate/src/value.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/util/color.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/animate/timeline.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/event/event-contoller.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/abstract/canvas.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/abstract/group.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/abstract/shape.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/bbox/register.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/bbox/rect.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/bbox/circle.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/bbox/util.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/util/offscreen.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/util/text.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/bbox/path.js","../../node_modules/@antv/component/esm/util/event.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/bbox/index.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/bbox/polyline.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/bbox/polygon.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/bbox/text.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/bbox/line.js","../../node_modules/@antv/component/node_modules/@antv/g-base/esm/bbox/ellipse.js","../../node_modules/@antv/component/esm/util/matrix.js","../../node_modules/@antv/component/esm/util/util.js","../../node_modules/@antv/component/esm/abstract/component.js","../../node_modules/@antv/component/esm/abstract/group-component.js","../../node_modules/@antv/util/esm/difference.js","../../node_modules/@antv/component/esm/util/text.js","../../node_modules/@antv/component/esm/util/label.js","../../node_modules/@antv/util/esm/get-ellipsis-text.js","../../node_modules/@antv/component/esm/util/graphic.js","../../node_modules/@antv/component/esm/util/theme.js","../../node_modules/@antv/component/esm/annotation/line.js","../../node_modules/@antv/component/esm/annotation/text.js","../../node_modules/@antv/component/esm/annotation/arc.js","../../node_modules/@antv/component/esm/annotation/region.js","../../node_modules/@antv/component/esm/annotation/image.js","../../node_modules/@antv/component/esm/annotation/data-marker.js","../../node_modules/@antv/component/esm/annotation/data-region.js","../../node_modules/@antv/component/esm/annotation/region-filter.js","../../node_modules/@antv/component/esm/annotation/shape.js","../../node_modules/@antv/component/esm/abstract/html-component.js","../../node_modules/@antv/component/esm/annotation/html.js","../../node_modules/@antv/component/esm/util/state.js","../../node_modules/@antv/component/esm/axis/base.js","../../node_modules/@antv/component/esm/axis/overlap/auto-ellipsis.js","../../node_modules/@antv/component/esm/axis/overlap/auto-hide.js","../../node_modules/@antv/component/esm/axis/overlap/auto-rotate.js","../../node_modules/@antv/component/esm/crosshair/html-theme.js","../../node_modules/@antv/component/esm/axis/line.js","../../node_modules/@antv/component/esm/axis/circle.js","../../node_modules/@antv/component/esm/crosshair/base.js","../../node_modules/@antv/component/esm/crosshair/line.js","../../node_modules/@antv/component/esm/crosshair/circle.js","../../node_modules/@antv/component/esm/crosshair/css-const.js","../../node_modules/@antv/component/esm/crosshair/html.js","../../node_modules/@antv/component/esm/grid/base.js","../../node_modules/@antv/component/esm/grid/circle.js","../../node_modules/@antv/component/esm/tooltip/html-theme.js","../../node_modules/@antv/component/esm/grid/line.js","../../node_modules/@antv/component/esm/legend/base.js","../../node_modules/@antv/component/esm/legend/category.js","../../node_modules/@antv/component/esm/legend/continuous.js","../../node_modules/@antv/component/esm/tooltip/css-const.js","../../node_modules/@antv/component/esm/tooltip/html.js","../../node_modules/@antv/component/esm/util/align.js","../../node_modules/@antv/component/esm/trend/constant.js","../../node_modules/@antv/component/esm/trend/path.js","../../node_modules/@antv/component/esm/trend/trend.js","../../node_modules/@antv/component/esm/slider/handler.js","../../node_modules/@antv/component/esm/slider/constant.js","../../node_modules/@antv/component/esm/slider/slider.js","../../node_modules/@antv/component/esm/scrollbar/scrollbar.js","../../node_modules/@antv/g2/esm/dependents.js","../../node_modules/@antv/g2/esm/util/graphics.js","../../node_modules/@antv/g2/esm/util/helper.js","../../node_modules/@antv/g2/esm/util/bbox.js","../../node_modules/@antv/g2/esm/util/coordinate.js","../../node_modules/@antv/g2/esm/util/scale.js","../../node_modules/@antv/g2/esm/util/axis.js","../../node_modules/@antv/g2/esm/facet/facet.js","../../node_modules/@antv/g2/esm/facet/index.js","../../node_modules/@antv/g2/esm/interaction/action/base.js","../../node_modules/@antv/g2/esm/interaction/action/callback.js","../../node_modules/@antv/g2/esm/interaction/action/register.js","../../node_modules/@antv/g2/esm/geometry/shape/util/path.js","../../node_modules/@antv/g2/esm/interaction/action/util.js","../../node_modules/@antv/g2/esm/interaction/context.js","../../node_modules/@antv/g2/esm/interaction/interaction.js","../../node_modules/@antv/g2/esm/interaction/grammar-interaction.js","../../node_modules/@antv/g2/esm/interaction/index.js","../../node_modules/@antv/g2/esm/theme/util/create-by-style-sheet.js","../../node_modules/@antv/g2/esm/theme/style-sheet/light.js","../../node_modules/@antv/g2/esm/theme/util/create-theme.js","../../node_modules/@antv/g2/esm/theme/index.js","../../node_modules/@antv/g2/esm/util/tooltip.js","../../node_modules/@antv/g2/esm/util/padding.js","../../node_modules/@antv/g2/esm/chart/controller/index.js","../../node_modules/@antv/g2/esm/chart/controller/coordinate.js","../../node_modules/@antv/g2/esm/chart/event.js","../../node_modules/@antv/g2/esm/chart/layout/index.js","../../node_modules/@antv/g2/esm/chart/util/scale-pool.js","../../node_modules/@antv/g2/esm/chart/layout/padding-cal.js","../../node_modules/@antv/g2/esm/chart/layout/auto.js","../../node_modules/@antv/g2/esm/chart/util/sync-view-padding.js","../../node_modules/@antv/g2/esm/chart/view.js","../../node_modules/@antv/g2/esm/chart/chart.js","../../node_modules/@antv/g2/esm/chart/controller/base.js","../../node_modules/@antv/g2/esm/chart/controller/tooltip.js","../../node_modules/@antv/g2/esm/animate/animation/index.js","../../node_modules/@antv/g2/esm/animate/index.js","../../node_modules/@antv/g2/esm/geometry/shape/constant.js","../../node_modules/@antv/g2/esm/geometry/element/index.js","../../node_modules/@antv/g2/esm/geometry/label/index.js","../../node_modules/@antv/g2/esm/geometry/shape/base.js","../../node_modules/@antv/g2/esm/geometry/util/is-model-change.js","../../node_modules/@antv/g2/esm/geometry/util/parse-fields.js","../../node_modules/@antv/g2/esm/geometry/util/diff.js","../../node_modules/@antv/g2/esm/geometry/base.js","../../node_modules/@antv/g2/esm/geometry/util/group-data.js","../../node_modules/@antv/g2/esm/util/transform.js","../../node_modules/@antv/g2/esm/geometry/label/util/index.js","../../node_modules/@antv/g2/esm/component/update-label.js","../../node_modules/@antv/g2/esm/component/labels.js","../../node_modules/@antv/util/esm/is-null.js","../../node_modules/@antv/g2/esm/geometry/label/base.js","../../node_modules/@antv/g2/esm/util/attr.js","../../node_modules/@antv/g2/esm/util/marker.js","../../node_modules/@antv/g2/esm/util/legend.js","../../node_modules/@antv/g2/esm/geometry/shape/util/get-path-points.js","../../node_modules/@antv/g2/esm/geometry/shape/util/get-style.js","../../node_modules/@antv/g2/esm/geometry/shape/util/split-points.js","../../node_modules/@antv/g2/esm/geometry/shape/line/util.js","../../node_modules/@antv/g2/esm/geometry/shape/line/index.js","../../node_modules/@antv/g2/esm/core.js","../../node_modules/@antv/g2/esm/theme/style-sheet/dark.js","../../node_modules/@antv/g-canvas/esm/util/util.js","../../node_modules/@antv/g-canvas/esm/util/parse.js","../../node_modules/@antv/g-canvas/esm/util/arc-params.js","../../node_modules/@antv/g-canvas/esm/util/arrow.js","../../node_modules/@antv/g-canvas/esm/util/draw.js","../../node_modules/@antv/g-canvas/esm/group.js","../../node_modules/@antv/g-canvas/esm/shape/base.js","../../node_modules/@antv/g-canvas/esm/shape/circle.js","../../node_modules/@antv/g-canvas/esm/shape/ellipse.js","../../node_modules/@antv/g-canvas/esm/shape/image.js","../../node_modules/@antv/g-canvas/esm/util/in-stroke/line.js","../../node_modules/@antv/g-canvas/esm/shape/line.js","../../node_modules/@antv/g-canvas/esm/shape/marker.js","../../node_modules/@antv/g-canvas/esm/util/in-path/point-in-path.js","../../node_modules/@antv/g-canvas/esm/util/in-path/polygon.js","../../node_modules/@antv/g-canvas/esm/util/in-stroke/arc.js","../../node_modules/@antv/g-canvas/esm/util/path.js","../../node_modules/@antv/g-canvas/esm/shape/path.js","../../node_modules/@antv/g-canvas/esm/util/in-stroke/polyline.js","../../node_modules/@antv/g-canvas/esm/shape/polygon.js","../../node_modules/@antv/g-canvas/esm/shape/polyline.js","../../node_modules/@antv/g-canvas/esm/shape/rect.js","../../node_modules/@antv/g-canvas/esm/util/in-stroke/rect-radius.js","../../node_modules/@antv/g-canvas/esm/util/in-stroke/rect.js","../../node_modules/@antv/g-canvas/esm/shape/text.js","../../node_modules/@antv/g-canvas/esm/util/hit.js","../../node_modules/@antv/g-canvas/esm/canvas.js","../../node_modules/@antv/util/esm/clear-animation-frame.js","../../node_modules/@antv/util/esm/request-animation-frame.js","../../node_modules/@antv/g-canvas/esm/index.js","../../node_modules/@antv/g-svg/esm/constant.js","../../node_modules/@antv/g-svg/esm/util/dom.js","../../node_modules/@antv/util/esm/to-array.js","../../node_modules/@antv/g-svg/esm/util/svg.js","../../node_modules/@antv/g-svg/esm/util/draw.js","../../node_modules/@antv/g-svg/esm/group.js","../../node_modules/@antv/g-svg/esm/shape/base.js","../../node_modules/@antv/g-svg/esm/shape/circle.js","../../node_modules/@antv/g-svg/esm/shape/dom.js","../../node_modules/@antv/g-svg/esm/shape/ellipse.js","../../node_modules/@antv/g-svg/esm/shape/image.js","../../node_modules/@antv/g-svg/esm/shape/line.js","../../node_modules/@antv/g-svg/esm/shape/marker/symbols.js","../../node_modules/@antv/g-svg/esm/shape/marker/index.js","../../node_modules/@antv/g-svg/esm/shape/path.js","../../node_modules/@antv/g-svg/esm/shape/polygon.js","../../node_modules/@antv/g-svg/esm/shape/polyline.js","../../node_modules/@antv/g-svg/esm/shape/rect.js","../../node_modules/@antv/g-svg/esm/util/format.js","../../node_modules/@antv/g-svg/esm/shape/text.js","../../node_modules/@antv/g-svg/esm/defs/gradient.js","../../node_modules/@antv/g-svg/esm/defs/shadow.js","../../node_modules/@antv/g-svg/esm/defs/arrow.js","../../node_modules/@antv/g-svg/esm/defs/clip.js","../../node_modules/@antv/g-svg/esm/defs/pattern.js","../../node_modules/@antv/g-svg/esm/defs/index.js","../../node_modules/@antv/g-svg/esm/canvas.js","../../node_modules/@antv/g-svg/esm/index.js","../../node_modules/@antv/g2/esm/geometry/path.js","../../node_modules/@antv/g2/esm/geometry/shape/area/util.js","../../node_modules/@antv/g2/esm/geometry/shape/area/index.js","../../node_modules/@antv/g2/esm/geometry/area.js","../../node_modules/@antv/g2/esm/geometry/shape/edge/index.js","../../node_modules/@antv/g2/esm/geometry/edge.js","../../node_modules/@antv/g2/esm/geometry/heatmap.js","../../node_modules/@antv/g2/esm/geometry/shape/interval/util.js","../../node_modules/@antv/g2/esm/geometry/util/shape-size.js","../../node_modules/@antv/g2/esm/geometry/shape/interval/index.js","../../node_modules/@antv/g2/esm/geometry/interval.js","../../node_modules/@antv/g2/esm/geometry/line.js","../../node_modules/@antv/g2/esm/geometry/shape/point/util.js","../../node_modules/@antv/g2/esm/geometry/shape/point/index.js","../../node_modules/@antv/g2/esm/geometry/point.js","../../node_modules/@antv/g2/esm/geometry/shape/polygon/index.js","../../node_modules/@antv/g2/esm/geometry/polygon.js","../../node_modules/@antv/g2/esm/geometry/shape/schema/index.js","../../node_modules/@antv/g2/esm/geometry/schema.js","../../node_modules/@antv/g2/esm/geometry/shape/violin/index.js","../../node_modules/@antv/g2/esm/geometry/violin.js","../../node_modules/@antv/g2/esm/geometry/shape/edge/util.js","../../node_modules/@antv/g2/esm/geometry/shape/area/line.js","../../node_modules/@antv/g2/esm/geometry/shape/area/smooth.js","../../node_modules/@antv/g2/esm/geometry/shape/area/smooth-line.js","../../node_modules/@antv/g2/esm/geometry/shape/edge/arc.js","../../node_modules/@antv/g2/esm/geometry/shape/edge/smooth.js","../../node_modules/@antv/g2/esm/geometry/shape/edge/vhv.js","../../node_modules/@antv/g2/esm/geometry/shape/interval/funnel.js","../../node_modules/@antv/g2/esm/geometry/shape/interval/hollow-rect.js","../../node_modules/@antv/g2/esm/geometry/shape/interval/line.js","../../node_modules/@antv/g2/esm/geometry/shape/interval/pyramid.js","../../node_modules/@antv/g2/esm/geometry/shape/interval/tick.js","../../node_modules/@antv/g2/esm/geometry/shape/line/step.js","../../node_modules/@antv/g2/esm/geometry/shape/schema/box.js","../../node_modules/@antv/g2/esm/geometry/shape/schema/candle.js","../../node_modules/@antv/g2/esm/geometry/shape/polygon/square.js","../../node_modules/@antv/g2/esm/geometry/shape/point/hollow.js","../../node_modules/@antv/g2/esm/geometry/shape/point/image.js","../../node_modules/@antv/g2/esm/geometry/shape/point/solid.js","../../node_modules/@antv/g2/esm/geometry/shape/violin/smooth.js","../../node_modules/@antv/g2/esm/geometry/shape/violin/hollow.js","../../node_modules/@antv/g2/esm/geometry/label/interval.js","../../node_modules/@antv/g2/esm/geometry/label/polar.js","../../node_modules/@antv/g2/esm/geometry/label/pie.js","../../node_modules/@antv/g2/esm/geometry/label/layout/pie/util.js","../../node_modules/@antv/g2/esm/geometry/label/layout/overlap.js","../../node_modules/@antv/g2/esm/util/collision-detect.js","../../node_modules/@antv/g2/esm/util/color.js","../../node_modules/@antv/g2/esm/util/context.js","../../node_modules/@antv/g2/esm/geometry/label/layout/interval/adjust-position.js","../../node_modules/@antv/g2/esm/geometry/label/layout/point/adjust-position.js","../../node_modules/@antv/g2/esm/geometry/label/layout/path/adjust-position.js","../../node_modules/@antv/g2/esm/util/text.js","../../node_modules/@antv/g2/esm/animate/animation/util.js","../../node_modules/@antv/g2/esm/animate/animation/sector-path-update.js","../../node_modules/@antv/g2/esm/animate/animation/zoom.js","../../node_modules/@antv/g2/esm/util/facet.js","../../node_modules/@antv/g2/esm/facet/circle.js","../../node_modules/@antv/g2/esm/facet/list.js","../../node_modules/@antv/g2/esm/facet/matrix.js","../../node_modules/@antv/g2/esm/facet/mirror.js","../../node_modules/@antv/g2/esm/facet/rect.js","../../node_modules/@antv/g2/esm/facet/tree.js","../../node_modules/@antv/g2/esm/util/stat.js","../../node_modules/@antv/g2/esm/util/annotation.js","../../node_modules/@antv/g2/esm/chart/controller/annotation.js","../../node_modules/@antv/g2/esm/util/grid.js","../../node_modules/@antv/g2/esm/chart/controller/axis.js","../../node_modules/@antv/g2/esm/util/direction.js","../../node_modules/@antv/g2/esm/chart/controller/legend.js","../../node_modules/@antv/g2/esm/chart/controller/slider.js","../../node_modules/@antv/g2/esm/chart/controller/scrollbar.js","../../node_modules/@antv/g2/esm/interaction/action/active-region.js","../../node_modules/@antv/g2/esm/interaction/action/component/tooltip/geometry.js","../../node_modules/@antv/g2/esm/interaction/action/component/tooltip/sibling.js","../../node_modules/@antv/g2/esm/interaction/action/component/tooltip/ellipsis-text.js","../../node_modules/@antv/g2/esm/interaction/action/element/state-base.js","../../node_modules/@antv/g2/esm/interaction/action/element/state.js","../../node_modules/@antv/g2/esm/interaction/action/element/active.js","../../node_modules/@antv/g2/esm/interaction/action/element/link-by-color.js","../../node_modules/@antv/g2/esm/interaction/action/element/range-state.js","../../node_modules/@antv/g2/esm/interaction/action/element/range-active.js","../../node_modules/@antv/g2/esm/interaction/action/element/single-state.js","../../node_modules/@antv/g2/esm/interaction/action/element/single-active.js","../../node_modules/@antv/g2/esm/interaction/action/element/highlight-util.js","../../node_modules/@antv/g2/esm/interaction/action/element/highlight.js","../../node_modules/@antv/g2/esm/interaction/action/element/range-highlight.js","../../node_modules/@antv/g2/esm/interaction/action/element/highlight-by-color.js","../../node_modules/@antv/g2/esm/interaction/action/element/highlight-by-x.js","../../node_modules/@antv/g2/esm/interaction/action/element/single-highlight.js","../../node_modules/@antv/g2/esm/interaction/action/element/range-selected.js","../../node_modules/@antv/g2/esm/interaction/action/element/selected.js","../../node_modules/@antv/g2/esm/interaction/action/element/single-selected.js","../../node_modules/@antv/g2/esm/interaction/action/component/list-state.js","../../node_modules/@antv/g2/esm/interaction/action/component/list-active.js","../../node_modules/@antv/g2/esm/interaction/action/component/list-highlight.js","../../node_modules/@antv/g2/esm/interaction/action/component/list-highlight-util.js","../../node_modules/@antv/g2/esm/interaction/action/component/list-selected.js","../../node_modules/@antv/g2/esm/interaction/action/component/list-unchecked.js","../../node_modules/@antv/g2/esm/interaction/action/component/list-checked.js","../../node_modules/@antv/g2/esm/interaction/action/mask/base.js","../../node_modules/@antv/g2/esm/interaction/action/mask/circle.js","../../node_modules/@antv/g2/esm/interaction/action/mask/rect.js","../../node_modules/@antv/g2/esm/interaction/action/mask/dim-rect.js","../../node_modules/@antv/g2/esm/interaction/action/data/range-filter.js","../../node_modules/@antv/g2/esm/interaction/action/mask/path.js","../../node_modules/@antv/g2/esm/interaction/action/mask/smooth-path.js","../../node_modules/@antv/g2/esm/interaction/action/cursor.js","../../node_modules/@antv/g2/esm/interaction/action/data/filter.js","../../node_modules/@antv/g2/esm/interaction/action/data/sibling-filter.js","../../node_modules/@antv/g2/esm/interaction/action/element/filter.js","../../node_modules/@antv/g2/esm/interaction/action/element/sibling-filter.js","../../node_modules/@antv/g2/esm/interaction/action/view/button.js","../../node_modules/@antv/g2/esm/interaction/action/view/drag.js","../../node_modules/@antv/g2/esm/interaction/action/view/move.js","../../node_modules/@antv/g2/esm/interaction/action/view/scale-transform.js","../../node_modules/@antv/g2/esm/interaction/action/view/scale-translate.js","../../node_modules/@antv/g2/esm/interaction/action/view/scale-zoom.js","../../node_modules/@antv/g2/esm/interaction/action/view/mousewheel-scroll.js","../../node_modules/@antv/g2plot/esm/utils/invariant.js","../../node_modules/@antv/g2/esm/index.js","../../node_modules/@antv/g2plot/esm/utils/flow.js","../../node_modules/@antv/g2plot/esm/utils/pick.js","../../node_modules/@antv/g2plot/esm/utils/template.js","../../node_modules/@antv/g2/esm/geometry/label/layout/pie/distribute.js","../../node_modules/@antv/g2/esm/geometry/label/layout/hide-overlap.js","../../node_modules/@antv/g2/esm/geometry/label/layout/limit-in-shape.js","../../node_modules/@antv/g2/esm/geometry/label/layout/limit-in-canvas.js","../../node_modules/@antv/g2/esm/geometry/label/layout/limit-in-plot.js","../../node_modules/@antv/g2/esm/geometry/label/layout/pie/outer.js","../../node_modules/@antv/g2/esm/geometry/label/layout/adjust-color.js","../../node_modules/@antv/g2/esm/geometry/label/layout/interval/hide-overlap.js","../../node_modules/@antv/g2/esm/geometry/label/layout/pie/spider.js","../../node_modules/@antv/g2/esm/animate/animation/fade.js","../../node_modules/@antv/g2/esm/animate/animation/grow-in.js","../../node_modules/@antv/g2/esm/animate/animation/scale-in.js","../../node_modules/@antv/g2/esm/animate/animation/wave-in.js","../../node_modules/@antv/g2/esm/animate/animation/position-update.js","../../node_modules/@antv/g2/esm/animate/animation/path-in.js","../../node_modules/@antv/g2plot/esm/utils/dom.js","../../node_modules/@antv/g2plot/esm/utils/geometry.js","../../node_modules/@antv/g2plot/esm/utils/view.js","../../node_modules/@antv/g2plot/esm/utils/label.js","../../node_modules/@antv/g2plot/esm/utils/path.js","../../node_modules/@antv/g2plot/esm/utils/deep-assign.js","../../node_modules/@antv/g2plot/esm/utils/kebab-case.js","../../node_modules/@antv/g2plot/esm/utils/statistic.js","../../node_modules/@antv/g2plot/esm/utils/context.js","../../node_modules/@antv/g2plot/esm/utils/measure-text.js","../../node_modules/@antv/g2plot/esm/utils/number.js","../../node_modules/@antv/g2plot/esm/utils/data.js","../../node_modules/@antv/g2plot/esm/utils/padding.js","../../node_modules/@antv/g2plot/esm/core/global.js","../../node_modules/@antv/g2plot/esm/core/locale.js","../../node_modules/@antv/g2plot/esm/locales/en_US.js","../../node_modules/size-sensor/lib/id.js","../../node_modules/size-sensor/lib/debounce.js","../../node_modules/size-sensor/lib/constant.js","../../node_modules/size-sensor/lib/sensors/object.js","../../node_modules/size-sensor/lib/sensors/resizeObserver.js","../../node_modules/size-sensor/lib/sensors/index.js","../../node_modules/size-sensor/lib/sensorPool.js","../../node_modules/size-sensor/lib/index.js","../../node_modules/@antv/g2plot/esm/core/plot.js","../../node_modules/@antv/g2plot/esm/constant.js","../../node_modules/@antv/g2plot/esm/utils/pattern/util.js","../../node_modules/@antv/g2plot/esm/utils/pattern/dot.js","../../node_modules/@antv/g2plot/esm/utils/pattern/line.js","../../node_modules/@antv/g2plot/esm/utils/pattern/square.js","../../node_modules/@antv/g2plot/esm/utils/pattern/index.js","../../node_modules/@antv/g2plot/esm/adaptor/pattern.js","../../node_modules/@antv/g2plot/esm/adaptor/common.js","../../node_modules/@antv/g2plot/esm/utils/tooltip.js","../../node_modules/@antv/g2plot/esm/adaptor/geometries/base.js","../../node_modules/@antv/g2plot/esm/adaptor/geometries/area.js","../../node_modules/@antv/g2plot/esm/adaptor/geometries/line.js","../../node_modules/@antv/g2plot/esm/adaptor/geometries/point.js","../../node_modules/@antv/g2plot/esm/adaptor/geometries/interval.js","../../node_modules/@antv/g2plot/esm/adaptor/geometries/polygon.js","../../node_modules/@antv/g2plot/esm/adaptor/geometries/edge.js","../../node_modules/@antv/g2plot/esm/adaptor/geometries/schema.js","../../node_modules/@antv/g2plot/esm/plots/line/constants.js","../../node_modules/@antv/g2plot/esm/plots/line/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/line/interactions/index.js","../../node_modules/@antv/g2plot/esm/plots/line/interactions/marker-active.js","../../node_modules/@antv/g2plot/esm/plots/line/index.js","../../node_modules/@antv/g2plot/esm/utils/transform/percent.js","../../node_modules/@antv/g2plot/esm/plots/area/constants.js","../../node_modules/@antv/g2plot/esm/plots/area/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/area/index.js","../../node_modules/@antv/g2plot/esm/utils/conversion.js","../../node_modules/@antv/g2plot/esm/adaptor/conversion-tag.js","../../node_modules/@antv/g2plot/esm/adaptor/connected-area.js","../../node_modules/@antv/g2plot/esm/interactions/actions/reset-button.js","../../node_modules/@antv/g2plot/esm/interactions/brush.js","../../node_modules/@antv/g2plot/esm/adaptor/brush.js","../../node_modules/@antv/g2plot/esm/plots/column/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/column/constants.js","../../node_modules/@antv/g2plot/esm/plots/column/index.js","../../node_modules/@antv/g2plot/esm/plots/bar/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/bar/constants.js","../../node_modules/@antv/g2plot/esm/plots/bar/index.js","../../node_modules/@antv/g2plot/esm/plots/pie/contants.js","../../node_modules/@antv/g2plot/esm/plots/pie/utils.js","../../node_modules/@antv/g2plot/esm/utils/matrix.js","../../node_modules/@antv/g2plot/esm/plots/pie/interactions/actions/legend-active.js","../../node_modules/@antv/g2plot/esm/plots/pie/interactions/actions/statistic-active.js","../../node_modules/@antv/g2plot/esm/plots/pie/interactions/util.js","../../node_modules/@antv/g2plot/esm/plots/pie/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/pie/interactions/index.js","../../node_modules/@antv/g2plot/esm/plots/pie/index.js","../../node_modules/@antv/g2plot/esm/plots/rose/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/rose/constant.js","../../node_modules/@antv/g2plot/esm/plots/rose/index.js","../../node_modules/@antv/g2plot/esm/utils/transform/word-cloud.js","../../node_modules/@antv/g2plot/esm/plots/word-cloud/utils.js","../../node_modules/@antv/g2plot/esm/plots/word-cloud/constant.js","../../node_modules/@antv/g2plot/esm/plots/word-cloud/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/word-cloud/shapes/word-cloud.js","../../node_modules/d3-regression/dist/d3-regression.esm.js","../../node_modules/@antv/g2plot/esm/plots/word-cloud/index.js","../../node_modules/@antv/g2plot/esm/plots/scatter/util.js","../../node_modules/@antv/g2plot/esm/plots/scatter/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/scatter/constant.js","../../node_modules/@antv/g2plot/esm/interactions/drag-move.js","../../node_modules/@antv/g2plot/esm/plots/scatter/index.js","../../node_modules/@antv/g2plot/esm/plots/dual-axes/types.js","../../node_modules/@antv/g2plot/esm/plots/radar/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/radar/interactions/radar-tooltip-action.js","../../node_modules/@antv/g2plot/esm/plots/radar/interactions/index.js","../../node_modules/@antv/g2plot/esm/plots/radar/index.js","../../node_modules/@antv/g2plot/esm/plots/dual-axes/constant.js","../../node_modules/@antv/g2plot/esm/plots/dual-axes/util/option.js","../../node_modules/@antv/g2plot/esm/plots/dual-axes/util/legend.js","../../node_modules/@antv/g2plot/esm/plots/dual-axes/util/render-sider.js","../../node_modules/@antv/g2plot/esm/plots/dual-axes/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/dual-axes/util/geometry.js","../../node_modules/@antv/g2plot/esm/plots/dual-axes/index.js","../../node_modules/@antv/g2plot/esm/plots/tiny-line/constants.js","../../node_modules/@antv/g2plot/esm/plots/tiny-line/utils.js","../../node_modules/@antv/g2plot/esm/plots/tiny-area/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/tiny-line/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/tiny-line/index.js","../../node_modules/@antv/g2plot/esm/plots/tiny-column/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/tiny-column/constants.js","../../node_modules/@antv/g2plot/esm/plots/tiny-column/index.js","../../node_modules/@antv/g2plot/esm/plots/tiny-area/constants.js","../../node_modules/@antv/g2plot/esm/plots/tiny-area/index.js","../../node_modules/@antv/g2plot/esm/utils/transform/histogram.js","../../node_modules/@antv/util/esm/sort-by.js","../../node_modules/@antv/g2plot/esm/plots/histogram/constant.js","../../node_modules/@antv/g2plot/esm/plots/histogram/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/histogram/index.js","../../node_modules/@antv/g2plot/esm/plots/progress/constants.js","../../node_modules/@antv/g2plot/esm/plots/progress/utils.js","../../node_modules/@antv/g2plot/esm/plots/progress/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/progress/index.js","../../node_modules/@antv/g2plot/esm/plots/ring-progress/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/ring-progress/constants.js","../../node_modules/@antv/g2plot/esm/plots/ring-progress/index.js","../../node_modules/@antv/g2plot/esm/plots/heatmap/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/heatmap/constant.js","../../node_modules/@antv/g2plot/esm/plots/box/constant.js","../../node_modules/@antv/g2plot/esm/plots/heatmap/shapes/circle.js","../../node_modules/@antv/g2plot/esm/plots/heatmap/shapes/square.js","../../node_modules/@antv/g2plot/esm/plots/heatmap/index.js","../../node_modules/@antv/g2plot/esm/plots/box/utils.js","../../node_modules/@antv/g2plot/esm/plots/box/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/box/index.js","../../node_modules/pdfast/src/helper.js","../../node_modules/pdfast/src/index.js","../../node_modules/@antv/g2plot/esm/utils/transform/quantile.js","../../node_modules/@antv/g2plot/esm/plots/violin/utils.js","../../node_modules/@antv/g2plot/esm/plots/violin/constant.js","../../node_modules/@antv/g2plot/esm/plots/violin/adaptor.js","../../node_modules/@antv/g2plot/esm/adaptor/geometries/violin.js","../../node_modules/@antv/g2plot/esm/plots/violin/index.js","../../node_modules/@antv/g2plot/esm/utils/color/blend.js","../../node_modules/fmin/src/blas1.js","../../node_modules/fmin/src/nelderMead.js","../../node_modules/fmin/src/linesearch.js","../../node_modules/fmin/src/conjugateGradient.js","../../node_modules/@antv/g2plot/esm/plots/venn/layout/circleintersection.js","../../node_modules/@antv/g2plot/esm/plots/venn/layout/layout.js","../../node_modules/fmin/src/bisect.js","../../node_modules/@antv/g2plot/esm/plots/venn/layout/diagram.js","../../node_modules/@antv/g2plot/esm/plots/venn/constant.js","../../node_modules/@antv/g2plot/esm/plots/venn/utils.js","../../node_modules/@antv/g2plot/esm/plots/venn/interactions/util.js","../../node_modules/@antv/g2plot/esm/plots/venn/shape.js","../../node_modules/@antv/g2plot/esm/plots/venn/label.js","../../node_modules/@antv/g2plot/esm/plots/venn/interactions/actions/active.js","../../node_modules/@antv/g2plot/esm/plots/venn/interactions/actions/highlight.js","../../node_modules/@antv/g2plot/esm/plots/venn/interactions/actions/selected.js","../../node_modules/@antv/g2plot/esm/plots/venn/interactions/index.js","../../node_modules/@antv/g2plot/esm/plots/venn/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/venn/index.js","../../node_modules/@antv/g2plot/esm/plots/stock/constant.js","../../node_modules/@antv/g2plot/esm/plots/funnel/constant.js","../../node_modules/@antv/g2plot/esm/plots/stock/utils.js","../../node_modules/@antv/g2plot/esm/plots/stock/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/stock/index.js","../../node_modules/@antv/g2plot/esm/plots/funnel/geometries/common.js","../../node_modules/@antv/g2plot/esm/plots/funnel/geometries/basic.js","../../node_modules/@antv/g2plot/esm/plots/funnel/geometries/compare.js","../../node_modules/@antv/g2plot/esm/plots/funnel/geometries/facet.js","../../node_modules/@antv/g2plot/esm/plots/funnel/geometries/dynamic-height.js","../../node_modules/@antv/g2plot/esm/plots/funnel/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/funnel/index.js","../../node_modules/@antv/g2plot/esm/plots/liquid/utils.js","../../node_modules/@antv/g2plot/esm/plots/liquid/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/liquid/constants.js","../../node_modules/@antv/g2plot/esm/plots/liquid/shapes/liquid.js","../../node_modules/@antv/g2plot/esm/plots/bullet/utils.js","../../node_modules/@antv/g2plot/esm/plots/bullet/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/liquid/index.js","../../node_modules/@antv/g2plot/esm/plots/bullet/constant.js","../../node_modules/@antv/g2plot/esm/plots/bullet/index.js","../../node_modules/@antv/g2plot/esm/utils/hierarchy/util.js","../../node_modules/@antv/g2plot/esm/plots/sunburst/constant.js","../../node_modules/@antv/g2plot/esm/interactions/actions/drill-down.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/cluster.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/count.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/index.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/pack/enclose.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/array.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/pack/siblings.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/accessors.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/constant.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/pack/index.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/treemap/round.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/treemap/dice.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/partition.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/each.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/eachAfter.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/eachBefore.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/find.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/sum.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/sort.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/path.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/ancestors.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/descendants.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/leaves.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/links.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/hierarchy/iterator.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/stratify.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/tree.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/treemap/slice.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/treemap/squarify.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/treemap/index.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/treemap/resquarify.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/treemap/binary.js","../../node_modules/@antv/g2plot/node_modules/d3-hierarchy/src/treemap/sliceDice.js","../../node_modules/@antv/g2plot/esm/utils/hierarchy/partition.js","../../node_modules/@antv/g2plot/esm/utils/hierarchy/treemap.js","../../node_modules/@antv/g2plot/esm/plots/gauge/constants.js","../../node_modules/@antv/g2plot/esm/plots/sunburst/utils.js","../../node_modules/@antv/g2plot/esm/plots/sunburst/adaptor.js","../../node_modules/@antv/g2plot/esm/interactions/drill-down.js","../../node_modules/@antv/g2plot/esm/plots/sunburst/index.js","../../node_modules/@antv/g2plot/esm/plots/gauge/utils.js","../../node_modules/@antv/g2plot/esm/plots/gauge/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/gauge/shapes/indicator.js","../../node_modules/@antv/g2plot/esm/plots/gauge/shapes/meter-gauge.js","../../node_modules/@antv/g2plot/esm/plots/gauge/index.js","../../node_modules/@antv/g2plot/esm/plots/waterfall/constant.js","../../node_modules/@antv/g2plot/esm/plots/waterfall/utils.js","../../node_modules/@antv/g2plot/esm/plots/waterfall/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/radial-bar/utils.js","../../node_modules/@antv/g2plot/esm/plots/radial-bar/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/waterfall/shape.js","../../node_modules/@antv/g2plot/esm/plots/waterfall/index.js","../../node_modules/@antv/g2plot/esm/plots/radial-bar/constant.js","../../node_modules/@antv/g2plot/esm/plots/radial-bar/index.js","../../node_modules/@antv/g2plot/esm/plots/bidirectional-bar/utils.js","../../node_modules/@antv/g2plot/esm/plots/bidirectional-bar/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/bidirectional-bar/constant.js","../../node_modules/@antv/g2plot/esm/plots/treemap/utils.js","../../node_modules/@antv/g2plot/esm/plots/treemap/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/bidirectional-bar/index.js","../../node_modules/@antv/g2plot/esm/plots/treemap/constant.js","../../node_modules/@antv/g2plot/esm/plots/sankey/sankey/align.js","../../node_modules/@antv/g2plot/esm/plots/sankey/sankey/helper.js","../../node_modules/@antv/g2plot/esm/plots/sankey/sankey/sankey.js","../../node_modules/@antv/g2plot/esm/plots/treemap/index.js","../../node_modules/@antv/g2plot/esm/plots/sankey/layout.js","../../node_modules/@antv/util/esm/min-by.js","../../node_modules/@antv/g2plot/esm/plots/sankey/circle.js","../../node_modules/@antv/g2plot/esm/plots/sankey/helper.js","../../node_modules/@antv/g2plot/esm/plots/sankey/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/sankey/constant.js","../../node_modules/@antv/g2plot/esm/plots/sankey/interactions/node-draggable.js","../../node_modules/@antv/g2plot/esm/plots/sankey/interactions/actions/node-drag.js","../../node_modules/@antv/g2plot/esm/plots/sankey/index.js","../../node_modules/@antv/g2plot/esm/utils/transform/chord.js","../../node_modules/@antv/g2plot/esm/plots/chord/constant.js","../../node_modules/@antv/g2plot/esm/plots/chord/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/chord/index.js","../../node_modules/@antv/g2plot/esm/utils/hierarchy/pack.js","../../node_modules/@antv/g2plot/esm/plots/circle-packing/utils.js","../../node_modules/@antv/g2plot/esm/plots/circle-packing/constant.js","../../node_modules/@antv/g2plot/esm/plots/circle-packing/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/circle-packing/index.js","../../node_modules/@antv/g2plot/esm/plugin/index.js","../../node_modules/@antv/g2plot/esm/plots/mix/utils.js","../../node_modules/@antv/g2plot/esm/plots/mix/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/mix/interactions/association.js","../../node_modules/@antv/g2plot/esm/plots/mix/interactions/utils.js","../../node_modules/@antv/g2plot/esm/plots/mix/index.js","../../node_modules/@antv/g2plot/esm/plots/facet/adaptor.js","../../node_modules/@antv/g2plot/esm/plots/facet/utils.js","../../node_modules/@antv/g2plot/esm/plots/facet/constant.js","../../node_modules/@antv/g2plot/esm/lab.js","../../node_modules/@antv/g2plot/esm/plots/facet/index.js","../../node_modules/@antv/g2plot/esm/index.js","../../node_modules/@antv/g2plot/esm/locales/zh_CN.js","../../node_modules/@ant-design/plots/es/util/createNode.js","../../node_modules/@ant-design/plots/es/util/utils.js","../../node_modules/@ant-design/plots/es/hooks/useChart.js","../../node_modules/@ant-design/plots/es/errorBoundary/index.js","../../node_modules/react-content-loader/dist/react-content-loader.es.js","../../node_modules/@ant-design/plots/es/util/createLoading.js","../../node_modules/@ant-design/plots/es/components/pie/index.js","../../node_modules/@ant-design/plots/es/util/getChart.js","../../src/components/G2PieChart/index.tsx","../../src/pages/dashboard/Renderer/Renderer/Pie/index.tsx","../../node_modules/d3-hexbin/src/hexbin.js","../../src/pages/dashboard/Renderer/Renderer/Hexbin/utils.ts","../../src/pages/dashboard/Renderer/Renderer/Hexbin/render.ts","../../src/pages/dashboard/Renderer/Renderer/Hexbin/index.tsx","../../src/pages/dashboard/Renderer/Renderer/BarGauge/index.tsx","../../src/pages/dashboard/Editor/Components/Markdown/index.tsx","../../src/pages/dashboard/VariableConfig/constant.tsx","../../src/pages/dashboard/Renderer/Renderer/Text/index.tsx","../../src/pages/dashboard/Renderer/Renderer/Gauge/Gauge.tsx","../../src/pages/dashboard/Renderer/Renderer/Gauge/utils.ts","../../src/pages/dashboard/Renderer/utils/squares.ts","../../src/pages/dashboard/Renderer/Renderer/Gauge/index.tsx","../../src/pages/dashboard/Renderer/utils/replaceExpressionBracket.ts","../../src/pages/dashboard/Renderer/datasource/utils/index.tsx","../../src/pages/dashboard/Renderer/datasource/prometheus.ts","../../src/pages/dashboard/Renderer/datasource/elasticSearch.tsx","../../src/pages/dashboard/Renderer/datasource/elasticSearchLog.tsx","../../src/pages/dashboard/Renderer/datasource/aliyunSLS.ts","../../src/pages/dashboard/Renderer/Renderer/index.tsx","../../src/pages/dashboard/Renderer/datasource/useQuery.tsx","../../src/pages/chart/index.tsx","../../src/pages/dashboard/VariableConfig/DisplayItem.tsx","../../src/pages/dashboard/Editor/QueryEditor/components/ClusterSelect/index.tsx","../../src/pages/dashboard/VariableConfig/EditItem.tsx","../../src/pages/dashboard/VariableConfig/EditItems.tsx","../../src/pages/dashboard/VariableConfig/index.tsx","../../src/pages/dashboard/Components/ModalHOC.tsx","../../src/pages/dashboard/DashboardLinks/Edit.tsx","../../src/pages/dashboard/DashboardLinks/index.tsx","../../src/pages/dashboard/Panels/utils.ts","../../src/pages/dashboard/Panels/Row.tsx","../../src/pages/dashboard/Editor/Components/Collapse/index.tsx","../../src/pages/dashboard/Editor/Components/Collapse/Panel.tsx","../../src/pages/dashboard/Editor/Fields/Tooltip/index.tsx","../../src/pages/dashboard/Editor/Fields/Legend/index.tsx","../../src/pages/dashboard/Editor/Options/Timeseries/GraphStyles.tsx","../../src/pages/dashboard/Editor/Fields/StandardOptions/index.tsx","../../node_modules/lodash/isString.js","../../node_modules/lodash/_castFunction.js","../../node_modules/lodash/forOwn.js","../../node_modules/reactcss/lib/flattenNames.js","../../node_modules/lodash/cloneDeep.js","../../node_modules/reactcss/lib/mergeClasses.js","../../node_modules/reactcss/lib/autoprefix.js","../../node_modules/reactcss/lib/components/hover.js","../../node_modules/reactcss/lib/components/active.js","../../node_modules/reactcss/lib/loop.js","../../node_modules/reactcss/lib/index.js","../../node_modules/react-color/es/helpers/alpha.js","../../node_modules/react-color/es/helpers/checkboard.js","../../node_modules/react-color/es/components/common/Checkboard.js","../../node_modules/react-color/es/components/common/Alpha.js","../../node_modules/react-color/es/components/common/EditableInput.js","../../node_modules/react-color/es/helpers/hue.js","../../node_modules/react-color/es/components/common/Hue.js","../../node_modules/lodash-es/eq.js","../../node_modules/lodash-es/_assocIndexOf.js","../../node_modules/lodash-es/_listCacheDelete.js","../../node_modules/lodash-es/_ListCache.js","../../node_modules/lodash-es/_listCacheClear.js","../../node_modules/lodash-es/_listCacheGet.js","../../node_modules/lodash-es/_listCacheHas.js","../../node_modules/lodash-es/_listCacheSet.js","../../node_modules/lodash-es/_freeGlobal.js","../../node_modules/lodash-es/_root.js","../../node_modules/lodash-es/_Symbol.js","../../node_modules/lodash-es/_getRawTag.js","../../node_modules/lodash-es/_objectToString.js","../../node_modules/lodash-es/_baseGetTag.js","../../node_modules/lodash-es/isObject.js","../../node_modules/lodash-es/isFunction.js","../../node_modules/lodash-es/_coreJsData.js","../../node_modules/lodash-es/_isMasked.js","../../node_modules/lodash-es/_toSource.js","../../node_modules/lodash-es/_baseIsNative.js","../../node_modules/lodash-es/_getNative.js","../../node_modules/lodash-es/_getValue.js","../../node_modules/lodash-es/_Map.js","../../node_modules/lodash-es/_nativeCreate.js","../../node_modules/lodash-es/_hashGet.js","../../node_modules/lodash-es/_hashHas.js","../../node_modules/lodash-es/_Hash.js","../../node_modules/lodash-es/_getMapData.js","../../node_modules/lodash-es/_isKeyable.js","../../node_modules/lodash-es/_MapCache.js","../../node_modules/lodash-es/_hashClear.js","../../node_modules/lodash-es/_hashDelete.js","../../node_modules/lodash-es/_hashSet.js","../../node_modules/lodash-es/_mapCacheClear.js","../../node_modules/lodash-es/_mapCacheDelete.js","../../node_modules/lodash-es/_mapCacheGet.js","../../node_modules/lodash-es/_mapCacheHas.js","../../node_modules/lodash-es/_mapCacheSet.js","../../node_modules/lodash-es/_Stack.js","../../node_modules/lodash-es/_stackClear.js","../../node_modules/lodash-es/_stackDelete.js","../../node_modules/lodash-es/_stackGet.js","../../node_modules/lodash-es/_stackHas.js","../../node_modules/lodash-es/_stackSet.js","../../node_modules/lodash-es/_defineProperty.js","../../node_modules/lodash-es/_baseAssignValue.js","../../node_modules/lodash-es/_assignMergeValue.js","../../node_modules/lodash-es/_baseFor.js","../../node_modules/lodash-es/_createBaseFor.js","../../node_modules/lodash-es/_cloneBuffer.js","../../node_modules/lodash-es/_Uint8Array.js","../../node_modules/lodash-es/_cloneTypedArray.js","../../node_modules/lodash-es/_cloneArrayBuffer.js","../../node_modules/lodash-es/_baseCreate.js","../../node_modules/lodash-es/_overArg.js","../../node_modules/lodash-es/_getPrototype.js","../../node_modules/lodash-es/_isPrototype.js","../../node_modules/lodash-es/isObjectLike.js","../../node_modules/lodash-es/_baseIsArguments.js","../../node_modules/lodash-es/isArguments.js","../../node_modules/lodash-es/isArray.js","../../node_modules/lodash-es/isLength.js","../../node_modules/lodash-es/isArrayLike.js","../../node_modules/lodash-es/isBuffer.js","../../node_modules/lodash-es/stubFalse.js","../../node_modules/lodash-es/isPlainObject.js","../../node_modules/lodash-es/_baseIsTypedArray.js","../../node_modules/lodash-es/_nodeUtil.js","../../node_modules/lodash-es/_baseUnary.js","../../node_modules/lodash-es/isTypedArray.js","../../node_modules/lodash-es/_safeGet.js","../../node_modules/lodash-es/_assignValue.js","../../node_modules/lodash-es/_isIndex.js","../../node_modules/lodash-es/_arrayLikeKeys.js","../../node_modules/lodash-es/_baseTimes.js","../../node_modules/lodash-es/_baseKeysIn.js","../../node_modules/lodash-es/_nativeKeysIn.js","../../node_modules/lodash-es/keysIn.js","../../node_modules/lodash-es/toPlainObject.js","../../node_modules/lodash-es/_copyObject.js","../../node_modules/lodash-es/_baseMergeDeep.js","../../node_modules/lodash-es/isArrayLikeObject.js","../../node_modules/lodash-es/_copyArray.js","../../node_modules/lodash-es/_initCloneObject.js","../../node_modules/lodash-es/_baseMerge.js","../../node_modules/lodash-es/identity.js","../../node_modules/lodash-es/_apply.js","../../node_modules/lodash-es/_overRest.js","../../node_modules/lodash-es/constant.js","../../node_modules/lodash-es/_baseSetToString.js","../../node_modules/lodash-es/_shortOut.js","../../node_modules/lodash-es/_setToString.js","../../node_modules/lodash-es/_baseRest.js","../../node_modules/lodash-es/merge.js","../../node_modules/lodash-es/_createAssigner.js","../../node_modules/lodash-es/_isIterateeCall.js","../../node_modules/react-color/es/components/common/Raised.js","../../node_modules/lodash-es/now.js","../../node_modules/lodash-es/_trimmedEndIndex.js","../../node_modules/lodash-es/_baseTrim.js","../../node_modules/lodash-es/isSymbol.js","../../node_modules/lodash-es/toNumber.js","../../node_modules/lodash-es/debounce.js","../../node_modules/react-color/es/helpers/saturation.js","../../node_modules/react-color/es/components/common/Saturation.js","../../node_modules/lodash-es/throttle.js","../../node_modules/lodash-es/_arrayEach.js","../../node_modules/lodash-es/_nativeKeys.js","../../node_modules/lodash-es/_baseKeys.js","../../node_modules/lodash-es/keys.js","../../node_modules/lodash-es/_baseEach.js","../../node_modules/lodash-es/_createBaseEach.js","../../node_modules/lodash-es/_baseForOwn.js","../../node_modules/lodash-es/forEach.js","../../node_modules/lodash-es/_castFunction.js","../../node_modules/tinycolor2/tinycolor.js","../../node_modules/react-color/es/helpers/color.js","../../node_modules/react-color/es/components/common/ColorWrap.js","../../node_modules/react-color/es/helpers/interaction.js","../../node_modules/react-color/es/components/common/Swatch.js","../../node_modules/react-color/es/components/alpha/Alpha.js","../../node_modules/lodash-es/_arrayMap.js","../../node_modules/react-color/es/components/alpha/AlphaPointer.js","../../node_modules/lodash-es/_SetCache.js","../../node_modules/lodash-es/_arraySome.js","../../node_modules/lodash-es/_setCacheAdd.js","../../node_modules/lodash-es/_setCacheHas.js","../../node_modules/lodash-es/_equalArrays.js","../../node_modules/lodash-es/_cacheHas.js","../../node_modules/lodash-es/_mapToArray.js","../../node_modules/lodash-es/_setToArray.js","../../node_modules/lodash-es/_equalByTag.js","../../node_modules/lodash-es/_getSymbols.js","../../node_modules/lodash-es/_arrayFilter.js","../../node_modules/lodash-es/stubArray.js","../../node_modules/lodash-es/_getAllKeys.js","../../node_modules/lodash-es/_baseGetAllKeys.js","../../node_modules/lodash-es/_arrayPush.js","../../node_modules/lodash-es/_equalObjects.js","../../node_modules/lodash-es/_DataView.js","../../node_modules/lodash-es/_Promise.js","../../node_modules/lodash-es/_Set.js","../../node_modules/lodash-es/_WeakMap.js","../../node_modules/lodash-es/_getTag.js","../../node_modules/lodash-es/_baseIsEqualDeep.js","../../node_modules/lodash-es/_baseIsEqual.js","../../node_modules/lodash-es/_isStrictComparable.js","../../node_modules/lodash-es/_matchesStrictComparable.js","../../node_modules/lodash-es/_baseMatches.js","../../node_modules/lodash-es/_getMatchData.js","../../node_modules/lodash-es/_baseIsMatch.js","../../node_modules/lodash-es/_isKey.js","../../node_modules/lodash-es/memoize.js","../../node_modules/lodash-es/_stringToPath.js","../../node_modules/lodash-es/_memoizeCapped.js","../../node_modules/lodash-es/_baseToString.js","../../node_modules/lodash-es/_castPath.js","../../node_modules/lodash-es/toString.js","../../node_modules/lodash-es/_toKey.js","../../node_modules/lodash-es/_baseGet.js","../../node_modules/lodash-es/_baseHasIn.js","../../node_modules/lodash-es/hasIn.js","../../node_modules/lodash-es/_hasPath.js","../../node_modules/lodash-es/_baseMatchesProperty.js","../../node_modules/lodash-es/get.js","../../node_modules/lodash-es/property.js","../../node_modules/lodash-es/_baseProperty.js","../../node_modules/lodash-es/_basePropertyDeep.js","../../node_modules/lodash-es/_baseMap.js","../../node_modules/lodash-es/map.js","../../node_modules/lodash-es/_baseIteratee.js","../../node_modules/react-color/es/components/block/BlockSwatches.js","../../node_modules/react-color/es/components/block/Block.js","../../node_modules/material-colors/dist/colors.es2015.js","../../node_modules/react-color/es/components/circle/CircleSwatch.js","../../node_modules/react-color/es/components/circle/Circle.js","../../node_modules/lodash-es/isUndefined.js","../../node_modules/@icons/material/UnfoldMoreHorizontalIcon.js","../../node_modules/react-color/es/components/chrome/ChromeFields.js","../../node_modules/react-color/es/components/chrome/ChromePointer.js","../../node_modules/react-color/es/components/chrome/ChromePointerCircle.js","../../node_modules/react-color/es/components/chrome/Chrome.js","../../node_modules/react-color/es/components/compact/CompactColor.js","../../node_modules/react-color/es/components/compact/CompactFields.js","../../node_modules/react-color/es/components/compact/Compact.js","../../node_modules/react-color/es/components/github/GithubSwatch.js","../../node_modules/react-color/es/components/github/Github.js","../../node_modules/react-color/es/components/hue/HuePointer.js","../../node_modules/react-color/es/components/hue/Hue.js","../../node_modules/react-color/es/components/material/Material.js","../../node_modules/react-color/es/components/photoshop/PhotoshopFields.js","../../node_modules/react-color/es/components/photoshop/PhotoshopPointerCircle.js","../../node_modules/react-color/es/components/photoshop/PhotoshopPointer.js","../../node_modules/react-color/es/components/photoshop/PhotoshopButton.js","../../node_modules/react-color/es/components/photoshop/PhotoshopPreviews.js","../../node_modules/react-color/es/components/photoshop/Photoshop.js","../../node_modules/react-color/es/components/sketch/SketchFields.js","../../node_modules/react-color/es/components/sketch/SketchPresetColors.js","../../node_modules/react-color/es/components/sketch/Sketch.js","../../node_modules/react-color/es/components/slider/SliderSwatch.js","../../node_modules/react-color/es/components/slider/SliderSwatches.js","../../node_modules/react-color/es/components/slider/Slider.js","../../node_modules/react-color/es/components/slider/SliderPointer.js","../../node_modules/@icons/material/CheckIcon.js","../../node_modules/react-color/es/components/swatches/SwatchesColor.js","../../node_modules/react-color/es/components/swatches/SwatchesGroup.js","../../node_modules/react-color/es/components/swatches/Swatches.js","../../node_modules/react-color/es/components/twitter/Twitter.js","../../node_modules/react-color/es/components/google/GooglePointerCircle.js","../../node_modules/react-color/es/components/google/GooglePointer.js","../../node_modules/react-color/es/components/google/GoogleFields.js","../../node_modules/react-color/es/components/google/Google.js","../../src/pages/dashboard/Components/ColorPicker/index.tsx","../../src/components/useOnClickOutside.tsx","../../src/pages/dashboard/Editor/Fields/Thresholds/index.tsx","../../src/pages/dashboard/Editor/Options/Timeseries/index.tsx","../../src/pages/dashboard/Editor/Options/Stat/GraphStyles.tsx","../../src/pages/dashboard/Editor/Fields/ValueMappings/index.tsx","../../src/pages/dashboard/Editor/Options/Stat/index.tsx","../../src/pages/dashboard/Editor/Options/Table/GraphStyles.tsx","../../src/pages/dashboard/Editor/Fields/Overrides/index.tsx","../../src/pages/dashboard/Editor/Options/Table/index.tsx","../../src/pages/dashboard/Editor/Options/Pie/GraphStyles.tsx","../../src/pages/dashboard/Editor/Options/Pie/index.tsx","../../src/pages/dashboard/Editor/Options/Hexbin/GraphStyles.tsx","../../src/pages/dashboard/Editor/Options/Hexbin/index.tsx","../../src/pages/dashboard/Editor/Options/BarGauge/GraphStyles.tsx","../../src/pages/dashboard/Editor/Options/BarGauge/index.tsx","../../src/pages/dashboard/Editor/Options/Text/GraphStyles.tsx","../../src/pages/dashboard/Editor/Options/Text/index.tsx","../../src/pages/dashboard/Editor/Options/Gauge/GraphStyles.tsx","../../src/pages/dashboard/Editor/Options/Gauge/index.tsx","../../src/pages/dashboard/Editor/Options/index.tsx","../../src/pages/dashboard/Renderer/utils/getFirstUnusedLetter.ts","../../src/pages/dashboard/Editor/QueryEditor/Prometheus.tsx","../../src/pages/dashboard/Editor/QueryEditor/Elasticsearch.tsx","../../src/pages/dashboard/Editor/QueryEditor/ElasticsearchLog.tsx","../../src/pages/metric/explorer/AliyunSLS/AdvancedSettings.tsx","../../src/pages/dashboard/Editor/QueryEditor/config.ts","../../src/pages/dashboard/Editor/QueryEditor/AliyunSLS.tsx","../../src/pages/dashboard/Editor/TransformationsEditor/OrganizeFields/OrganizeFields.tsx","../../src/pages/dashboard/Editor/TransformationsEditor/OrganizeFields/index.tsx","../../src/pages/dashboard/Editor/QueryEditor/index.tsx","../../src/pages/dashboard/Editor/Form.tsx","../../src/pages/dashboard/Editor/util.tsx","../../src/pages/dashboard/Editor/index.tsx","../../src/pages/dashboard/Panels/index.tsx","../../src/pages/dashboard/Detail/Title.tsx","../../src/pages/dashboard/Detail/Detail.tsx","../../src/pages/dashboard/Detail/index.tsx","../../src/pages/dashboard/Share/index.tsx","../../src/pages/user/const.ts","../../src/pages/user/component/userForm/index.tsx","../../src/pages/user/component/teamForm/index.tsx","../../src/store/manageInterface/index.ts","../../src/pages/user/component/businessForm/index.tsx","../../src/pages/user/component/passwordForm/index.tsx","../../src/components/BaseTable/index.tsx","../../src/pages/user/component/addUser/index.tsx","../../src/pages/user/component/createModal/index.tsx","../../src/pages/user/groups.tsx","../../src/pages/user/users.tsx","../../src/pages/user/business.tsx","../../node_modules/@codemirror/theme-one-dark/dist/index.js","../../node_modules/@uiw/react-codemirror/esm/theme/light.js","../../node_modules/react/cjs/react-jsx-runtime.production.min.js","../../node_modules/react/jsx-runtime.js","../../node_modules/@uiw/react-codemirror/esm/index.js","../../node_modules/@uiw/react-codemirror/esm/useCodeMirror.js","../../node_modules/@lezer/json/dist/index.es.js","../../node_modules/@codemirror/lang-json/dist/index.js","../../src/pages/metric/explorer/Elasticsearch/utils.tsx","../../src/pages/metric/explorer/components/FieldsSidebar/FieldsList.tsx","../../src/pages/metric/explorer/components/FieldsSidebar/index.tsx","../../src/pages/metric/explorer/Elasticsearch/index.tsx","../../src/pages/metric/explorer/Elasticsearch/metricQuery.tsx","../../src/components/PromGraphCpt/services.ts","../../src/components/PromGraphCpt/Table.tsx","../../src/components/PromGraphCpt/components/GraphStandardOptions.tsx","../../src/components/PromGraphCpt/Graph.tsx","../../src/components/PromGraphCpt/components/QueryStatsView.tsx","../../src/components/PromGraphCpt/components/MetricsExplorer.tsx","../../src/components/PromGraphCpt/index.tsx","../../src/pages/metric/explorer/Prometheus/index.tsx","../../src/pages/metric/explorer/AliyunSLS/utils.tsx","../../src/pages/metric/explorer/AliyunSLS/RawTable.tsx","../../src/pages/metric/explorer/AliyunSLS/Raw.tsx","../../src/pages/metric/explorer/AliyunSLS/Metric.tsx","../../src/pages/metric/explorer/AliyunSLS/index.tsx","../../src/pages/metric/explorer/index.tsx","../../src/services/metricViews.ts","../../src/pages/monitor/object/metricViews/utils.ts","../../src/pages/monitor/object/metricViews/Form.tsx","../../src/pages/monitor/object/metricViews/Export.tsx","../../src/pages/monitor/object/metricViews/List.tsx","../../src/pages/monitor/object/metricViews/LabelsValues.tsx","../../src/pages/monitor/object/metricViews/config.tsx","../../src/pages/monitor/object/metricViews/graphStandardOptions/Line.tsx","../../src/pages/dashboard/Components/ColorRangeMenu/index.tsx","../../src/pages/monitor/object/metricViews/graphStandardOptions/Hexbin.tsx","../../src/pages/monitor/object/metricViews/Graph.tsx","../../src/pages/monitor/object/metricViews/Metrics.tsx","../../src/pages/monitor/object/index.tsx","../../src/services/indicator.ts","../../src/pages/monitor/indicator/index.tsx","../../src/pages/warning/strategy/add.tsx","../../src/pages/warning/strategy/edit.tsx","../../src/pages/event/Graph.tsx","../../src/pages/warning/strategy/Jobs/Graph.tsx","../../src/pages/warning/strategy/Jobs/index.tsx","../../src/pages/warning/shield/index.tsx","../../src/services/shield.ts","../../src/pages/warning/shield/components/tagItem.tsx","../../src/pages/warning/shield/components/CateSelect/index.tsx","../../src/pages/warning/shield/components/ClusterSelect/index.tsx","../../src/pages/warning/shield/components/operateForm.tsx","../../src/pages/warning/shield/add.tsx","../../src/pages/warning/shield/edit.tsx","../../src/services/subscribe.ts","../../src/pages/warning/subscribe/index.tsx","../../src/pages/warning/subscribe/components/ruleModal.tsx","../../src/pages/warning/subscribe/components/tagItem.tsx","../../src/pages/warning/subscribe/components/operateForm.tsx","../../src/pages/warning/subscribe/add.tsx","../../src/pages/warning/subscribe/edit.tsx","../../node_modules/react-highlight-words/dist/main.js","../../src/components/Dantd/hooks/use-debounce/index.tsx","../../src/components/Dantd/components/locale/zh_CN.tsx","../../src/components/Dantd/components/locale/index.tsx","../../src/components/Dantd/components/locale/en_US.tsx","../../src/components/Dantd/components/utils.ts","../../src/components/Dantd/components/query-form/use-media.ts","../../src/components/Dantd/components/query-form/use-media-antd-query.ts","../../node_modules/react-fast-compare/index.js","../../src/components/Dantd/hooks/use-deep-compare-effect/useCustomCompareEffect.ts","../../src/components/Dantd/hooks/use-deep-compare-effect/index.ts","../../src/components/Dantd/components/query-form/QueryForm.tsx","../../src/components/Dantd/components/data-table/config.tsx","../../src/components/Dantd/components/data-table/DataTable.tsx","../../src/pages/event/cardLeft.tsx","../../src/pages/event/card.tsx","../../src/pages/event/index.tsx","../../src/pages/event/Preview/AlgoGraph.tsx","../../src/pages/event/Preview/ElasticsearchGraph.tsx","../../src/pages/event/Preview/AliyunSLSGraph.tsx","../../src/pages/event/Preview/index.tsx","../../src/pages/event/LogsDetail/index.tsx","../../src/pages/event/LogsDetail/AliyunSLS.tsx","../../src/pages/event/LogsDetail/Elasticsearch.tsx","../../src/pages/event/Detail/Prometheus.tsx","../../src/pages/event/Detail/AliyunSLS.tsx","../../src/pages/event/detail.tsx","../../src/pages/event/Detail/Elasticsearch.tsx","../../src/pages/historyEvents/ClusterSelect/index.tsx","../../node_modules/doc-path/dist/path.js","../../node_modules/deeks/lib/deeks.js","../../node_modules/deeks/lib/utils.js","../../node_modules/json-2-csv/lib/utils.js","../../node_modules/json-2-csv/lib/json2csv.js","../../node_modules/json-2-csv/lib/csv2json.js","../../node_modules/json-2-csv/lib/converter.js","../../src/pages/historyEvents/exportEvents.ts","../../src/pages/historyEvents/index.tsx","../../src/services/monObjectManage.ts","../../src/pages/monObjectManage/List.tsx","../../src/pages/monObjectManage/clipboard.tsx","../../src/pages/monObjectManage/BusinessGroup/index.tsx","../../src/pages/monObjectManage/index.tsx","../../src/pages/demo/index.tsx","../../src/utils/api.ts","../../src/components/BaseModal/modalControl.tsx","../../src/pages/taskTpl/bindTags.tsx","../../src/pages/taskTpl/unBindTags.tsx","../../src/pages/taskTpl/index.tsx","../../node_modules/ace-builds/src-noconflict/mode-sh.js","../../node_modules/ace-builds/src-noconflict/theme-monokai.js","../../src/pages/taskTpl/editor.tsx","../../node_modules/ace-builds/src-noconflict/theme-kuroir.js","../../src/pages/taskTpl/tplForm.tsx","../../src/pages/taskTpl/add.tsx","../../src/pages/taskTpl/detail.tsx","../../src/pages/taskTpl/modify.tsx","../../src/pages/taskTpl/clone.tsx","../../src/pages/task/index.tsx","../../src/pages/task/add.tsx","../../src/pages/task/FieldCopy/index.tsx","../../src/pages/task/FieldCopy/clipboard.tsx","../../src/pages/task/result.tsx","../../src/pages/task/detail.tsx","../../src/pages/help/version.tsx","../../src/pages/help/contact.tsx","../../src/pages/help/migrate/Dashboard.tsx","../../src/pages/help/migrate/index.tsx","../../src/pages/help/servers/index.tsx","../../src/services/help.ts","../../src/components/DataSource/TimeSeriesSource/config.tsx","../../src/components/DataSource/TimeSeriesSource/services.ts","../../src/components/DataSource/components/SourceCards/index.tsx","../../src/components/DataSource/TimeSeriesSource/Rename.tsx","../../src/components/DataSource/LogSource/services.ts","../../src/components/DataSource/components/LogPopover/index.tsx","../../src/components/DataSource/components/TableSource/index.tsx","../../src/components/Code/index.tsx","../../src/components/DataSource/TimeSeriesSource/Detail/index.tsx","../../src/components/DataSource/TimeSeriesSource/Detail/Prometheus.tsx","../../src/pages/datasource/TimeSeriesSource/Detail/index.tsx","../../src/components/DataSource/LogSource/Detail/index.tsx","../../src/components/DataSource/LogSource/Detail/ElasticSearch.tsx","../../src/components/DataSource/LogSource/Detail/AliyunSLS.tsx","../../src/pages/datasource/LogSource/Detail/index.tsx","../../src/pages/datasource/Detail.tsx","../../src/pages/datasource/index.tsx","../../src/components/BreadCrumb/index.tsx","../../src/components/DataSource/TimeSeriesSource/Form/index.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/Name.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/HTTP.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/FormItem.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/BasicAuth.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/Footer.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/Description.tsx","../../src/components/DataSource/TimeSeriesSource/Form/Prometheus.tsx","../../src/pages/datasource/TimeSeriesSource/Form/index.tsx","../../src/components/DataSource/LogSource/Form/index.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/Headers.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/EsDetail.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/WriteConfig.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/HTTPList.tsx","../../src/components/DataSource/LogSource/Form/ElasticSearch.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/Auth.tsx","../../src/components/DataSource/TimeSeriesSource/Form/items/ServiceEntry.tsx","../../src/components/DataSource/LogSource/Form/AliyunSLS.tsx","../../src/pages/datasource/LogSource/Form/index.tsx","../../src/pages/datasource/Form.tsx","../../src/services/recording.ts","../../src/pages/recordingRules/components/editModal.tsx","../../src/pages/recordingRules/PageTable.tsx","../../src/pages/recordingRules/index.tsx","../../src/pages/recordingRules/components/operateForm.tsx","../../src/pages/recordingRules/add.tsx","../../src/pages/recordingRules/edit.tsx","../../src/routers/index.tsx","../../node_modules/redux/es/redux.js","../../node_modules/@redux-saga/symbols/dist/redux-saga-symbols.esm.js","../../node_modules/@redux-saga/is/dist/redux-saga-is.esm.js","../../node_modules/@redux-saga/delay-p/dist/redux-saga-delay-p.esm.js","../../node_modules/@redux-saga/core/dist/io-6de156f3.js","../../node_modules/@redux-saga/core/dist/redux-saga-core.esm.js","../../node_modules/@redux-saga/deferred/dist/redux-saga-deferred.esm.js","../../node_modules/@redux-saga/core/dist/redux-saga-effects.esm.js","../../src/store/miniDva/loadingPlugin.ts","../../src/store/miniDva/index.ts","../../src/store/miniDva/plugin.ts","../../src/module/common.ts","../../src/store/businessInterface/resource.ts","../../src/services/resource.ts","../../src/module/resource.ts","../../src/services/account.ts","../../src/module/account.ts","../../src/module/warning.ts","../../src/module/shield.ts","../../src/module/event.ts","../../src/store/index.ts","../../src/pages/taskOutput/index.jsx","../../src/pages/taskOutput/host.jsx","../../src/App.tsx","../../src/main.tsx"],"sourcesContent":["import defineProperty from \"./defineProperty.js\";\nexport default function _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? Object(arguments[i]) : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}","import _typeof from '@babel/runtime/helpers/esm/typeof';\nimport _objectSpread from '@babel/runtime/helpers/esm/objectSpread';\nimport _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck';\nimport _createClass from '@babel/runtime/helpers/esm/createClass';\nimport _possibleConstructorReturn from '@babel/runtime/helpers/esm/possibleConstructorReturn';\nimport _getPrototypeOf from '@babel/runtime/helpers/esm/getPrototypeOf';\nimport _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized';\nimport _inherits from '@babel/runtime/helpers/esm/inherits';\n\nvar consoleLogger = {\n type: 'logger',\n log: function log(args) {\n this.output('log', args);\n },\n warn: function warn(args) {\n this.output('warn', args);\n },\n error: function error(args) {\n this.output('error', args);\n },\n output: function output(type, args) {\n if (console && console[type]) console[type].apply(console, args);\n }\n};\n\nvar Logger = function () {\n function Logger(concreteLogger) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n _classCallCheck(this, Logger);\n\n this.init(concreteLogger, options);\n }\n\n _createClass(Logger, [{\n key: \"init\",\n value: function init(concreteLogger) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n this.prefix = options.prefix || 'i18next:';\n this.logger = concreteLogger || consoleLogger;\n this.options = options;\n this.debug = options.debug;\n }\n }, {\n key: \"setDebug\",\n value: function setDebug(bool) {\n this.debug = bool;\n }\n }, {\n key: \"log\",\n value: function log() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return this.forward(args, 'log', '', true);\n }\n }, {\n key: \"warn\",\n value: function warn() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n return this.forward(args, 'warn', '', true);\n }\n }, {\n key: \"error\",\n value: function error() {\n for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n args[_key3] = arguments[_key3];\n }\n\n return this.forward(args, 'error', '');\n }\n }, {\n key: \"deprecate\",\n value: function deprecate() {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n\n return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);\n }\n }, {\n key: \"forward\",\n value: function forward(args, lvl, prefix, debugOnly) {\n if (debugOnly && !this.debug) return null;\n if (typeof args[0] === 'string') args[0] = \"\".concat(prefix).concat(this.prefix, \" \").concat(args[0]);\n return this.logger[lvl](args);\n }\n }, {\n key: \"create\",\n value: function create(moduleName) {\n return new Logger(this.logger, _objectSpread({}, {\n prefix: \"\".concat(this.prefix, \":\").concat(moduleName, \":\")\n }, this.options));\n }\n }]);\n\n return Logger;\n}();\n\nvar baseLogger = new Logger();\n\nvar EventEmitter = function () {\n function EventEmitter() {\n _classCallCheck(this, EventEmitter);\n\n this.observers = {};\n }\n\n _createClass(EventEmitter, [{\n key: \"on\",\n value: function on(events, listener) {\n var _this = this;\n\n events.split(' ').forEach(function (event) {\n _this.observers[event] = _this.observers[event] || [];\n\n _this.observers[event].push(listener);\n });\n return this;\n }\n }, {\n key: \"off\",\n value: function off(event, listener) {\n if (!this.observers[event]) return;\n\n if (!listener) {\n delete this.observers[event];\n return;\n }\n\n this.observers[event] = this.observers[event].filter(function (l) {\n return l !== listener;\n });\n }\n }, {\n key: \"emit\",\n value: function emit(event) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n if (this.observers[event]) {\n var cloned = [].concat(this.observers[event]);\n cloned.forEach(function (observer) {\n observer.apply(void 0, args);\n });\n }\n\n if (this.observers['*']) {\n var _cloned = [].concat(this.observers['*']);\n\n _cloned.forEach(function (observer) {\n observer.apply(observer, [event].concat(args));\n });\n }\n }\n }]);\n\n return EventEmitter;\n}();\n\nfunction defer() {\n var res;\n var rej;\n var promise = new Promise(function (resolve, reject) {\n res = resolve;\n rej = reject;\n });\n promise.resolve = res;\n promise.reject = rej;\n return promise;\n}\nfunction makeString(object) {\n if (object == null) return '';\n return '' + object;\n}\nfunction copy(a, s, t) {\n a.forEach(function (m) {\n if (s[m]) t[m] = s[m];\n });\n}\n\nfunction getLastOfPath(object, path, Empty) {\n function cleanKey(key) {\n return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;\n }\n\n function canNotTraverseDeeper() {\n return !object || typeof object === 'string';\n }\n\n var stack = typeof path !== 'string' ? [].concat(path) : path.split('.');\n\n while (stack.length > 1) {\n if (canNotTraverseDeeper()) return {};\n var key = cleanKey(stack.shift());\n if (!object[key] && Empty) object[key] = new Empty();\n\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n object = object[key];\n } else {\n object = {};\n }\n }\n\n if (canNotTraverseDeeper()) return {};\n return {\n obj: object,\n k: cleanKey(stack.shift())\n };\n}\n\nfunction setPath(object, path, newValue) {\n var _getLastOfPath = getLastOfPath(object, path, Object),\n obj = _getLastOfPath.obj,\n k = _getLastOfPath.k;\n\n obj[k] = newValue;\n}\nfunction pushPath(object, path, newValue, concat) {\n var _getLastOfPath2 = getLastOfPath(object, path, Object),\n obj = _getLastOfPath2.obj,\n k = _getLastOfPath2.k;\n\n obj[k] = obj[k] || [];\n if (concat) obj[k] = obj[k].concat(newValue);\n if (!concat) obj[k].push(newValue);\n}\nfunction getPath(object, path) {\n var _getLastOfPath3 = getLastOfPath(object, path),\n obj = _getLastOfPath3.obj,\n k = _getLastOfPath3.k;\n\n if (!obj) return undefined;\n return obj[k];\n}\nfunction getPathWithDefaults(data, defaultData, key) {\n var value = getPath(data, key);\n\n if (value !== undefined) {\n return value;\n }\n\n return getPath(defaultData, key);\n}\nfunction deepExtend(target, source, overwrite) {\n for (var prop in source) {\n if (prop !== '__proto__' && prop !== 'constructor') {\n if (prop in target) {\n if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {\n if (overwrite) target[prop] = source[prop];\n } else {\n deepExtend(target[prop], source[prop], overwrite);\n }\n } else {\n target[prop] = source[prop];\n }\n }\n }\n\n return target;\n}\nfunction regexEscape(str) {\n return str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, '\\\\$&');\n}\nvar _entityMap = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '/': '/'\n};\nfunction escape(data) {\n if (typeof data === 'string') {\n return data.replace(/[&<>\"'\\/]/g, function (s) {\n return _entityMap[s];\n });\n }\n\n return data;\n}\nvar isIE10 = typeof window !== 'undefined' && window.navigator && window.navigator.userAgent && window.navigator.userAgent.indexOf('MSIE') > -1;\n\nfunction deepFind(obj, path) {\n var keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';\n if (!obj) return undefined;\n if (obj[path]) return obj[path];\n var paths = path.split(keySeparator);\n var current = obj;\n\n for (var i = 0; i < paths.length; ++i) {\n if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) {\n return undefined;\n }\n\n if (current[paths[i]] === undefined) {\n var j = 2;\n var p = paths.slice(i, i + j).join(keySeparator);\n var mix = current[p];\n\n while (mix === undefined && paths.length > i + j) {\n j++;\n p = paths.slice(i, i + j).join(keySeparator);\n mix = current[p];\n }\n\n if (mix === undefined) return undefined;\n if (typeof mix === 'string') return mix;\n if (p && typeof mix[p] === 'string') return mix[p];\n var joinedPath = paths.slice(i + j).join(keySeparator);\n if (joinedPath) return deepFind(mix, joinedPath, keySeparator);\n return undefined;\n }\n\n current = current[paths[i]];\n }\n\n return current;\n}\n\nvar ResourceStore = function (_EventEmitter) {\n _inherits(ResourceStore, _EventEmitter);\n\n function ResourceStore(data) {\n var _this;\n\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n ns: ['translation'],\n defaultNS: 'translation'\n };\n\n _classCallCheck(this, ResourceStore);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(ResourceStore).call(this));\n\n if (isIE10) {\n EventEmitter.call(_assertThisInitialized(_this));\n }\n\n _this.data = data || {};\n _this.options = options;\n\n if (_this.options.keySeparator === undefined) {\n _this.options.keySeparator = '.';\n }\n\n if (_this.options.ignoreJSONStructure === undefined) {\n _this.options.ignoreJSONStructure = true;\n }\n\n return _this;\n }\n\n _createClass(ResourceStore, [{\n key: \"addNamespaces\",\n value: function addNamespaces(ns) {\n if (this.options.ns.indexOf(ns) < 0) {\n this.options.ns.push(ns);\n }\n }\n }, {\n key: \"removeNamespaces\",\n value: function removeNamespaces(ns) {\n var index = this.options.ns.indexOf(ns);\n\n if (index > -1) {\n this.options.ns.splice(index, 1);\n }\n }\n }, {\n key: \"getResource\",\n value: function getResource(lng, ns, key) {\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n var ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;\n var path = [lng, ns];\n if (key && typeof key !== 'string') path = path.concat(key);\n if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);\n\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n }\n\n var result = getPath(this.data, path);\n if (result || !ignoreJSONStructure || typeof key !== 'string') return result;\n return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);\n }\n }, {\n key: \"addResource\",\n value: function addResource(lng, ns, key, value) {\n var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {\n silent: false\n };\n var keySeparator = this.options.keySeparator;\n if (keySeparator === undefined) keySeparator = '.';\n var path = [lng, ns];\n if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);\n\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n value = ns;\n ns = path[1];\n }\n\n this.addNamespaces(ns);\n setPath(this.data, path, value);\n if (!options.silent) this.emit('added', lng, ns, key, value);\n }\n }, {\n key: \"addResources\",\n value: function addResources(lng, ns, resources) {\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {\n silent: false\n };\n\n for (var m in resources) {\n if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {\n silent: true\n });\n }\n\n if (!options.silent) this.emit('added', lng, ns, resources);\n }\n }, {\n key: \"addResourceBundle\",\n value: function addResourceBundle(lng, ns, resources, deep, overwrite) {\n var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {\n silent: false\n };\n var path = [lng, ns];\n\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n deep = resources;\n resources = ns;\n ns = path[1];\n }\n\n this.addNamespaces(ns);\n var pack = getPath(this.data, path) || {};\n\n if (deep) {\n deepExtend(pack, resources, overwrite);\n } else {\n pack = _objectSpread({}, pack, resources);\n }\n\n setPath(this.data, path, pack);\n if (!options.silent) this.emit('added', lng, ns, resources);\n }\n }, {\n key: \"removeResourceBundle\",\n value: function removeResourceBundle(lng, ns) {\n if (this.hasResourceBundle(lng, ns)) {\n delete this.data[lng][ns];\n }\n\n this.removeNamespaces(ns);\n this.emit('removed', lng, ns);\n }\n }, {\n key: \"hasResourceBundle\",\n value: function hasResourceBundle(lng, ns) {\n return this.getResource(lng, ns) !== undefined;\n }\n }, {\n key: \"getResourceBundle\",\n value: function getResourceBundle(lng, ns) {\n if (!ns) ns = this.options.defaultNS;\n if (this.options.compatibilityAPI === 'v1') return _objectSpread({}, {}, this.getResource(lng, ns));\n return this.getResource(lng, ns);\n }\n }, {\n key: \"getDataByLanguage\",\n value: function getDataByLanguage(lng) {\n return this.data[lng];\n }\n }, {\n key: \"toJSON\",\n value: function toJSON() {\n return this.data;\n }\n }]);\n\n return ResourceStore;\n}(EventEmitter);\n\nvar postProcessor = {\n processors: {},\n addPostProcessor: function addPostProcessor(module) {\n this.processors[module.name] = module;\n },\n handle: function handle(processors, value, key, options, translator) {\n var _this = this;\n\n processors.forEach(function (processor) {\n if (_this.processors[processor]) value = _this.processors[processor].process(value, key, options, translator);\n });\n return value;\n }\n};\n\nvar checkedLoadedFor = {};\n\nvar Translator = function (_EventEmitter) {\n _inherits(Translator, _EventEmitter);\n\n function Translator(services) {\n var _this;\n\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n _classCallCheck(this, Translator);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(Translator).call(this));\n\n if (isIE10) {\n EventEmitter.call(_assertThisInitialized(_this));\n }\n\n copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, _assertThisInitialized(_this));\n _this.options = options;\n\n if (_this.options.keySeparator === undefined) {\n _this.options.keySeparator = '.';\n }\n\n _this.logger = baseLogger.create('translator');\n return _this;\n }\n\n _createClass(Translator, [{\n key: \"changeLanguage\",\n value: function changeLanguage(lng) {\n if (lng) this.language = lng;\n }\n }, {\n key: \"exists\",\n value: function exists(key) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n interpolation: {}\n };\n var resolved = this.resolve(key, options);\n return resolved && resolved.res !== undefined;\n }\n }, {\n key: \"extractFromKey\",\n value: function extractFromKey(key, options) {\n var nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;\n if (nsSeparator === undefined) nsSeparator = ':';\n var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n var namespaces = options.ns || this.options.defaultNS;\n\n if (nsSeparator && key.indexOf(nsSeparator) > -1) {\n var m = key.match(this.interpolator.nestingRegexp);\n\n if (m && m.length > 0) {\n return {\n key: key,\n namespaces: namespaces\n };\n }\n\n var parts = key.split(nsSeparator);\n if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();\n key = parts.join(keySeparator);\n }\n\n if (typeof namespaces === 'string') namespaces = [namespaces];\n return {\n key: key,\n namespaces: namespaces\n };\n }\n }, {\n key: \"translate\",\n value: function translate(keys, options, lastKey) {\n var _this2 = this;\n\n if (_typeof(options) !== 'object' && this.options.overloadTranslationOptionHandler) {\n options = this.options.overloadTranslationOptionHandler(arguments);\n }\n\n if (!options) options = {};\n if (keys === undefined || keys === null) return '';\n if (!Array.isArray(keys)) keys = [String(keys)];\n var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n\n var _this$extractFromKey = this.extractFromKey(keys[keys.length - 1], options),\n key = _this$extractFromKey.key,\n namespaces = _this$extractFromKey.namespaces;\n\n var namespace = namespaces[namespaces.length - 1];\n var lng = options.lng || this.language;\n var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;\n\n if (lng && lng.toLowerCase() === 'cimode') {\n if (appendNamespaceToCIMode) {\n var nsSeparator = options.nsSeparator || this.options.nsSeparator;\n return namespace + nsSeparator + key;\n }\n\n return key;\n }\n\n var resolved = this.resolve(keys, options);\n var res = resolved && resolved.res;\n var resUsedKey = resolved && resolved.usedKey || key;\n var resExactUsedKey = resolved && resolved.exactUsedKey || key;\n var resType = Object.prototype.toString.apply(res);\n var noObject = ['[object Number]', '[object Function]', '[object RegExp]'];\n var joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;\n var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;\n var handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';\n\n if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {\n if (!options.returnObjects && !this.options.returnObjects) {\n if (!this.options.returnedObjectHandler) {\n this.logger.warn('accessing an object - but returnObjects options is not enabled!');\n }\n\n return this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, _objectSpread({}, options, {\n ns: namespaces\n })) : \"key '\".concat(key, \" (\").concat(this.language, \")' returned an object instead of string.\");\n }\n\n if (keySeparator) {\n var resTypeIsArray = resType === '[object Array]';\n var copy = resTypeIsArray ? [] : {};\n var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;\n\n for (var m in res) {\n if (Object.prototype.hasOwnProperty.call(res, m)) {\n var deepKey = \"\".concat(newKeyToUse).concat(keySeparator).concat(m);\n copy[m] = this.translate(deepKey, _objectSpread({}, options, {\n joinArrays: false,\n ns: namespaces\n }));\n if (copy[m] === deepKey) copy[m] = res[m];\n }\n }\n\n res = copy;\n }\n } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {\n res = res.join(joinArrays);\n if (res) res = this.extendTranslation(res, keys, options, lastKey);\n } else {\n var usedDefault = false;\n var usedKey = false;\n var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';\n var hasDefaultValue = Translator.hasDefaultValue(options);\n var defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count) : '';\n var defaultValue = options[\"defaultValue\".concat(defaultValueSuffix)] || options.defaultValue;\n\n if (!this.isValidLookup(res) && hasDefaultValue) {\n usedDefault = true;\n res = defaultValue;\n }\n\n if (!this.isValidLookup(res)) {\n usedKey = true;\n res = key;\n }\n\n var updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;\n\n if (usedKey || usedDefault || updateMissing) {\n this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);\n\n if (keySeparator) {\n var fk = this.resolve(key, _objectSpread({}, options, {\n keySeparator: false\n }));\n if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');\n }\n\n var lngs = [];\n var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);\n\n if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {\n for (var i = 0; i < fallbackLngs.length; i++) {\n lngs.push(fallbackLngs[i]);\n }\n } else if (this.options.saveMissingTo === 'all') {\n lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);\n } else {\n lngs.push(options.lng || this.language);\n }\n\n var send = function send(l, k, fallbackValue) {\n if (_this2.options.missingKeyHandler) {\n _this2.options.missingKeyHandler(l, namespace, k, updateMissing ? fallbackValue : res, updateMissing, options);\n } else if (_this2.backendConnector && _this2.backendConnector.saveMissing) {\n _this2.backendConnector.saveMissing(l, namespace, k, updateMissing ? fallbackValue : res, updateMissing, options);\n }\n\n _this2.emit('missingKey', l, namespace, k, res);\n };\n\n if (this.options.saveMissing) {\n if (this.options.saveMissingPlurals && needsPluralHandling) {\n lngs.forEach(function (language) {\n _this2.pluralResolver.getSuffixes(language).forEach(function (suffix) {\n send([language], key + suffix, options[\"defaultValue\".concat(suffix)] || defaultValue);\n });\n });\n } else {\n send(lngs, key, defaultValue);\n }\n }\n }\n\n res = this.extendTranslation(res, keys, options, resolved, lastKey);\n if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = \"\".concat(namespace, \":\").concat(key);\n if (usedKey && this.options.parseMissingKeyHandler) res = this.options.parseMissingKeyHandler(res);\n }\n\n return res;\n }\n }, {\n key: \"extendTranslation\",\n value: function extendTranslation(res, key, options, resolved, lastKey) {\n var _this3 = this;\n\n if (this.i18nFormat && this.i18nFormat.parse) {\n res = this.i18nFormat.parse(res, options, resolved.usedLng, resolved.usedNS, resolved.usedKey, {\n resolved: resolved\n });\n } else if (!options.skipInterpolation) {\n if (options.interpolation) this.interpolator.init(_objectSpread({}, options, {\n interpolation: _objectSpread({}, this.options.interpolation, options.interpolation)\n }));\n var skipOnVariables = options.interpolation && options.interpolation.skipOnVariables || this.options.interpolation.skipOnVariables;\n var nestBef;\n\n if (skipOnVariables) {\n var nb = res.match(this.interpolator.nestingRegexp);\n nestBef = nb && nb.length;\n }\n\n var data = options.replace && typeof options.replace !== 'string' ? options.replace : options;\n if (this.options.interpolation.defaultVariables) data = _objectSpread({}, this.options.interpolation.defaultVariables, data);\n res = this.interpolator.interpolate(res, data, options.lng || this.language, options);\n\n if (skipOnVariables) {\n var na = res.match(this.interpolator.nestingRegexp);\n var nestAft = na && na.length;\n if (nestBef < nestAft) options.nest = false;\n }\n\n if (options.nest !== false) res = this.interpolator.nest(res, function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (lastKey && lastKey[0] === args[0] && !options.context) {\n _this3.logger.warn(\"It seems you are nesting recursively key: \".concat(args[0], \" in key: \").concat(key[0]));\n\n return null;\n }\n\n return _this3.translate.apply(_this3, args.concat([key]));\n }, options);\n if (options.interpolation) this.interpolator.reset();\n }\n\n var postProcess = options.postProcess || this.options.postProcess;\n var postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;\n\n if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {\n res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread({\n i18nResolved: resolved\n }, options) : options, this);\n }\n\n return res;\n }\n }, {\n key: \"resolve\",\n value: function resolve(keys) {\n var _this4 = this;\n\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var found;\n var usedKey;\n var exactUsedKey;\n var usedLng;\n var usedNS;\n if (typeof keys === 'string') keys = [keys];\n keys.forEach(function (k) {\n if (_this4.isValidLookup(found)) return;\n\n var extracted = _this4.extractFromKey(k, options);\n\n var key = extracted.key;\n usedKey = key;\n var namespaces = extracted.namespaces;\n if (_this4.options.fallbackNS) namespaces = namespaces.concat(_this4.options.fallbackNS);\n var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';\n var needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';\n var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng);\n namespaces.forEach(function (ns) {\n if (_this4.isValidLookup(found)) return;\n usedNS = ns;\n\n if (!checkedLoadedFor[\"\".concat(codes[0], \"-\").concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) {\n checkedLoadedFor[\"\".concat(codes[0], \"-\").concat(ns)] = true;\n\n _this4.logger.warn(\"key \\\"\".concat(usedKey, \"\\\" for languages \\\"\").concat(codes.join(', '), \"\\\" won't get resolved as namespace \\\"\").concat(usedNS, \"\\\" was not yet loaded\"), 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n }\n\n codes.forEach(function (code) {\n if (_this4.isValidLookup(found)) return;\n usedLng = code;\n var finalKey = key;\n var finalKeys = [finalKey];\n\n if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) {\n _this4.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);\n } else {\n var pluralSuffix;\n if (needsPluralHandling) pluralSuffix = _this4.pluralResolver.getSuffix(code, options.count);\n if (needsPluralHandling && needsContextHandling) finalKeys.push(finalKey + pluralSuffix);\n if (needsContextHandling) finalKeys.push(finalKey += \"\".concat(_this4.options.contextSeparator).concat(options.context));\n if (needsPluralHandling) finalKeys.push(finalKey += pluralSuffix);\n }\n\n var possibleKey;\n\n while (possibleKey = finalKeys.pop()) {\n if (!_this4.isValidLookup(found)) {\n exactUsedKey = possibleKey;\n found = _this4.getResource(code, ns, possibleKey, options);\n }\n }\n });\n });\n });\n return {\n res: found,\n usedKey: usedKey,\n exactUsedKey: exactUsedKey,\n usedLng: usedLng,\n usedNS: usedNS\n };\n }\n }, {\n key: \"isValidLookup\",\n value: function isValidLookup(res) {\n return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');\n }\n }, {\n key: \"getResource\",\n value: function getResource(code, ns, key) {\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);\n return this.resourceStore.getResource(code, ns, key, options);\n }\n }], [{\n key: \"hasDefaultValue\",\n value: function hasDefaultValue(options) {\n var prefix = 'defaultValue';\n\n for (var option in options) {\n if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {\n return true;\n }\n }\n\n return false;\n }\n }]);\n\n return Translator;\n}(EventEmitter);\n\nfunction capitalize(string) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n}\n\nvar LanguageUtil = function () {\n function LanguageUtil(options) {\n _classCallCheck(this, LanguageUtil);\n\n this.options = options;\n this.whitelist = this.options.supportedLngs || false;\n this.supportedLngs = this.options.supportedLngs || false;\n this.logger = baseLogger.create('languageUtils');\n }\n\n _createClass(LanguageUtil, [{\n key: \"getScriptPartFromCode\",\n value: function getScriptPartFromCode(code) {\n if (!code || code.indexOf('-') < 0) return null;\n var p = code.split('-');\n if (p.length === 2) return null;\n p.pop();\n if (p[p.length - 1].toLowerCase() === 'x') return null;\n return this.formatLanguageCode(p.join('-'));\n }\n }, {\n key: \"getLanguagePartFromCode\",\n value: function getLanguagePartFromCode(code) {\n if (!code || code.indexOf('-') < 0) return code;\n var p = code.split('-');\n return this.formatLanguageCode(p[0]);\n }\n }, {\n key: \"formatLanguageCode\",\n value: function formatLanguageCode(code) {\n if (typeof code === 'string' && code.indexOf('-') > -1) {\n var specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];\n var p = code.split('-');\n\n if (this.options.lowerCaseLng) {\n p = p.map(function (part) {\n return part.toLowerCase();\n });\n } else if (p.length === 2) {\n p[0] = p[0].toLowerCase();\n p[1] = p[1].toUpperCase();\n if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());\n } else if (p.length === 3) {\n p[0] = p[0].toLowerCase();\n if (p[1].length === 2) p[1] = p[1].toUpperCase();\n if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();\n if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());\n if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());\n }\n\n return p.join('-');\n }\n\n return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;\n }\n }, {\n key: \"isWhitelisted\",\n value: function isWhitelisted(code) {\n this.logger.deprecate('languageUtils.isWhitelisted', 'function \"isWhitelisted\" will be renamed to \"isSupportedCode\" in the next major - please make sure to rename it\\'s usage asap.');\n return this.isSupportedCode(code);\n }\n }, {\n key: \"isSupportedCode\",\n value: function isSupportedCode(code) {\n if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {\n code = this.getLanguagePartFromCode(code);\n }\n\n return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;\n }\n }, {\n key: \"getBestMatchFromCodes\",\n value: function getBestMatchFromCodes(codes) {\n var _this = this;\n\n if (!codes) return null;\n var found;\n codes.forEach(function (code) {\n if (found) return;\n\n var cleanedLng = _this.formatLanguageCode(code);\n\n if (!_this.options.supportedLngs || _this.isSupportedCode(cleanedLng)) found = cleanedLng;\n });\n\n if (!found && this.options.supportedLngs) {\n codes.forEach(function (code) {\n if (found) return;\n\n var lngOnly = _this.getLanguagePartFromCode(code);\n\n if (_this.isSupportedCode(lngOnly)) return found = lngOnly;\n found = _this.options.supportedLngs.find(function (supportedLng) {\n if (supportedLng.indexOf(lngOnly) === 0) return supportedLng;\n });\n });\n }\n\n if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];\n return found;\n }\n }, {\n key: \"getFallbackCodes\",\n value: function getFallbackCodes(fallbacks, code) {\n if (!fallbacks) return [];\n if (typeof fallbacks === 'function') fallbacks = fallbacks(code);\n if (typeof fallbacks === 'string') fallbacks = [fallbacks];\n if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;\n if (!code) return fallbacks[\"default\"] || [];\n var found = fallbacks[code];\n if (!found) found = fallbacks[this.getScriptPartFromCode(code)];\n if (!found) found = fallbacks[this.formatLanguageCode(code)];\n if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];\n if (!found) found = fallbacks[\"default\"];\n return found || [];\n }\n }, {\n key: \"toResolveHierarchy\",\n value: function toResolveHierarchy(code, fallbackCode) {\n var _this2 = this;\n\n var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);\n var codes = [];\n\n var addCode = function addCode(c) {\n if (!c) return;\n\n if (_this2.isSupportedCode(c)) {\n codes.push(c);\n } else {\n _this2.logger.warn(\"rejecting language code not found in supportedLngs: \".concat(c));\n }\n };\n\n if (typeof code === 'string' && code.indexOf('-') > -1) {\n if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));\n if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));\n if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));\n } else if (typeof code === 'string') {\n addCode(this.formatLanguageCode(code));\n }\n\n fallbackCodes.forEach(function (fc) {\n if (codes.indexOf(fc) < 0) addCode(_this2.formatLanguageCode(fc));\n });\n return codes;\n }\n }]);\n\n return LanguageUtil;\n}();\n\nvar sets = [{\n lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],\n nr: [1, 2],\n fc: 1\n}, {\n lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kk', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'],\n nr: [1, 2],\n fc: 2\n}, {\n lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],\n nr: [1],\n fc: 3\n}, {\n lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],\n nr: [1, 2, 5],\n fc: 4\n}, {\n lngs: ['ar'],\n nr: [0, 1, 2, 3, 11, 100],\n fc: 5\n}, {\n lngs: ['cs', 'sk'],\n nr: [1, 2, 5],\n fc: 6\n}, {\n lngs: ['csb', 'pl'],\n nr: [1, 2, 5],\n fc: 7\n}, {\n lngs: ['cy'],\n nr: [1, 2, 3, 8],\n fc: 8\n}, {\n lngs: ['fr'],\n nr: [1, 2],\n fc: 9\n}, {\n lngs: ['ga'],\n nr: [1, 2, 3, 7, 11],\n fc: 10\n}, {\n lngs: ['gd'],\n nr: [1, 2, 3, 20],\n fc: 11\n}, {\n lngs: ['is'],\n nr: [1, 2],\n fc: 12\n}, {\n lngs: ['jv'],\n nr: [0, 1],\n fc: 13\n}, {\n lngs: ['kw'],\n nr: [1, 2, 3, 4],\n fc: 14\n}, {\n lngs: ['lt'],\n nr: [1, 2, 10],\n fc: 15\n}, {\n lngs: ['lv'],\n nr: [1, 2, 0],\n fc: 16\n}, {\n lngs: ['mk'],\n nr: [1, 2],\n fc: 17\n}, {\n lngs: ['mnk'],\n nr: [0, 1, 2],\n fc: 18\n}, {\n lngs: ['mt'],\n nr: [1, 2, 11, 20],\n fc: 19\n}, {\n lngs: ['or'],\n nr: [2, 1],\n fc: 2\n}, {\n lngs: ['ro'],\n nr: [1, 2, 20],\n fc: 20\n}, {\n lngs: ['sl'],\n nr: [5, 1, 2, 3],\n fc: 21\n}, {\n lngs: ['he', 'iw'],\n nr: [1, 2, 20, 21],\n fc: 22\n}];\nvar _rulesPluralsTypes = {\n 1: function _(n) {\n return Number(n > 1);\n },\n 2: function _(n) {\n return Number(n != 1);\n },\n 3: function _(n) {\n return 0;\n },\n 4: function _(n) {\n return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);\n },\n 5: function _(n) {\n return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);\n },\n 6: function _(n) {\n return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);\n },\n 7: function _(n) {\n return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);\n },\n 8: function _(n) {\n return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);\n },\n 9: function _(n) {\n return Number(n >= 2);\n },\n 10: function _(n) {\n return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);\n },\n 11: function _(n) {\n return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);\n },\n 12: function _(n) {\n return Number(n % 10 != 1 || n % 100 == 11);\n },\n 13: function _(n) {\n return Number(n !== 0);\n },\n 14: function _(n) {\n return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);\n },\n 15: function _(n) {\n return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);\n },\n 16: function _(n) {\n return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);\n },\n 17: function _(n) {\n return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);\n },\n 18: function _(n) {\n return Number(n == 0 ? 0 : n == 1 ? 1 : 2);\n },\n 19: function _(n) {\n return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);\n },\n 20: function _(n) {\n return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);\n },\n 21: function _(n) {\n return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);\n },\n 22: function _(n) {\n return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);\n }\n};\n\nfunction createRules() {\n var rules = {};\n sets.forEach(function (set) {\n set.lngs.forEach(function (l) {\n rules[l] = {\n numbers: set.nr,\n plurals: _rulesPluralsTypes[set.fc]\n };\n });\n });\n return rules;\n}\n\nvar PluralResolver = function () {\n function PluralResolver(languageUtils) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n _classCallCheck(this, PluralResolver);\n\n this.languageUtils = languageUtils;\n this.options = options;\n this.logger = baseLogger.create('pluralResolver');\n this.rules = createRules();\n }\n\n _createClass(PluralResolver, [{\n key: \"addRule\",\n value: function addRule(lng, obj) {\n this.rules[lng] = obj;\n }\n }, {\n key: \"getRule\",\n value: function getRule(code) {\n return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];\n }\n }, {\n key: \"needsPlural\",\n value: function needsPlural(code) {\n var rule = this.getRule(code);\n return rule && rule.numbers.length > 1;\n }\n }, {\n key: \"getPluralFormsOfKey\",\n value: function getPluralFormsOfKey(code, key) {\n return this.getSuffixes(code).map(function (suffix) {\n return key + suffix;\n });\n }\n }, {\n key: \"getSuffixes\",\n value: function getSuffixes(code) {\n var _this = this;\n\n var rule = this.getRule(code);\n\n if (!rule) {\n return [];\n }\n\n return rule.numbers.map(function (number) {\n return _this.getSuffix(code, number);\n });\n }\n }, {\n key: \"getSuffix\",\n value: function getSuffix(code, count) {\n var _this2 = this;\n\n var rule = this.getRule(code);\n\n if (rule) {\n var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));\n var suffix = rule.numbers[idx];\n\n if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {\n if (suffix === 2) {\n suffix = 'plural';\n } else if (suffix === 1) {\n suffix = '';\n }\n }\n\n var returnSuffix = function returnSuffix() {\n return _this2.options.prepend && suffix.toString() ? _this2.options.prepend + suffix.toString() : suffix.toString();\n };\n\n if (this.options.compatibilityJSON === 'v1') {\n if (suffix === 1) return '';\n if (typeof suffix === 'number') return \"_plural_\".concat(suffix.toString());\n return returnSuffix();\n } else if (this.options.compatibilityJSON === 'v2') {\n return returnSuffix();\n } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {\n return returnSuffix();\n }\n\n return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();\n }\n\n this.logger.warn(\"no plural rule found for: \".concat(code));\n return '';\n }\n }]);\n\n return PluralResolver;\n}();\n\nvar Interpolator = function () {\n function Interpolator() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n _classCallCheck(this, Interpolator);\n\n this.logger = baseLogger.create('interpolator');\n this.options = options;\n\n this.format = options.interpolation && options.interpolation.format || function (value) {\n return value;\n };\n\n this.init(options);\n }\n\n _createClass(Interpolator, [{\n key: \"init\",\n value: function init() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n if (!options.interpolation) options.interpolation = {\n escapeValue: true\n };\n var iOpts = options.interpolation;\n this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;\n this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;\n this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;\n this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';\n this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';\n this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';\n this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';\n this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';\n this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');\n this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');\n this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';\n this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;\n this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;\n this.resetRegExp();\n }\n }, {\n key: \"reset\",\n value: function reset() {\n if (this.options) this.init(this.options);\n }\n }, {\n key: \"resetRegExp\",\n value: function resetRegExp() {\n var regexpStr = \"\".concat(this.prefix, \"(.+?)\").concat(this.suffix);\n this.regexp = new RegExp(regexpStr, 'g');\n var regexpUnescapeStr = \"\".concat(this.prefix).concat(this.unescapePrefix, \"(.+?)\").concat(this.unescapeSuffix).concat(this.suffix);\n this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');\n var nestingRegexpStr = \"\".concat(this.nestingPrefix, \"(.+?)\").concat(this.nestingSuffix);\n this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');\n }\n }, {\n key: \"interpolate\",\n value: function interpolate(str, data, lng, options) {\n var _this = this;\n\n var match;\n var value;\n var replaces;\n var defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};\n\n function regexSafe(val) {\n return val.replace(/\\$/g, '$$$$');\n }\n\n var handleFormat = function handleFormat(key) {\n if (key.indexOf(_this.formatSeparator) < 0) {\n var path = getPathWithDefaults(data, defaultData, key);\n return _this.alwaysFormat ? _this.format(path, undefined, lng, _objectSpread({}, options, data, {\n interpolationkey: key\n })) : path;\n }\n\n var p = key.split(_this.formatSeparator);\n var k = p.shift().trim();\n var f = p.join(_this.formatSeparator).trim();\n return _this.format(getPathWithDefaults(data, defaultData, k), f, lng, _objectSpread({}, options, data, {\n interpolationkey: k\n }));\n };\n\n this.resetRegExp();\n var missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;\n var skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables || this.options.interpolation.skipOnVariables;\n var todos = [{\n regex: this.regexpUnescape,\n safeValue: function safeValue(val) {\n return regexSafe(val);\n }\n }, {\n regex: this.regexp,\n safeValue: function safeValue(val) {\n return _this.escapeValue ? regexSafe(_this.escape(val)) : regexSafe(val);\n }\n }];\n todos.forEach(function (todo) {\n replaces = 0;\n\n while (match = todo.regex.exec(str)) {\n value = handleFormat(match[1].trim());\n\n if (value === undefined) {\n if (typeof missingInterpolationHandler === 'function') {\n var temp = missingInterpolationHandler(str, match, options);\n value = typeof temp === 'string' ? temp : '';\n } else if (skipOnVariables) {\n value = match[0];\n continue;\n } else {\n _this.logger.warn(\"missed to pass in variable \".concat(match[1], \" for interpolating \").concat(str));\n\n value = '';\n }\n } else if (typeof value !== 'string' && !_this.useRawValueToEscape) {\n value = makeString(value);\n }\n\n var safeValue = todo.safeValue(value);\n str = str.replace(match[0], safeValue);\n\n if (skipOnVariables) {\n todo.regex.lastIndex += safeValue.length;\n todo.regex.lastIndex -= match[0].length;\n } else {\n todo.regex.lastIndex = 0;\n }\n\n replaces++;\n\n if (replaces >= _this.maxReplaces) {\n break;\n }\n }\n });\n return str;\n }\n }, {\n key: \"nest\",\n value: function nest(str, fc) {\n var _this2 = this;\n\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var match;\n var value;\n\n var clonedOptions = _objectSpread({}, options);\n\n clonedOptions.applyPostProcessor = false;\n delete clonedOptions.defaultValue;\n\n function handleHasOptions(key, inheritedOptions) {\n var sep = this.nestingOptionsSeparator;\n if (key.indexOf(sep) < 0) return key;\n var c = key.split(new RegExp(\"\".concat(sep, \"[ ]*{\")));\n var optionsString = \"{\".concat(c[1]);\n key = c[0];\n optionsString = this.interpolate(optionsString, clonedOptions);\n optionsString = optionsString.replace(/'/g, '\"');\n\n try {\n clonedOptions = JSON.parse(optionsString);\n if (inheritedOptions) clonedOptions = _objectSpread({}, inheritedOptions, clonedOptions);\n } catch (e) {\n this.logger.warn(\"failed parsing options string in nesting for key \".concat(key), e);\n return \"\".concat(key).concat(sep).concat(optionsString);\n }\n\n delete clonedOptions.defaultValue;\n return key;\n }\n\n while (match = this.nestingRegexp.exec(str)) {\n var formatters = [];\n var doReduce = false;\n\n if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {\n var r = match[1].split(this.formatSeparator).map(function (elem) {\n return elem.trim();\n });\n match[1] = r.shift();\n formatters = r;\n doReduce = true;\n }\n\n value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);\n if (value && match[0] === str && typeof value !== 'string') return value;\n if (typeof value !== 'string') value = makeString(value);\n\n if (!value) {\n this.logger.warn(\"missed to resolve \".concat(match[1], \" for nesting \").concat(str));\n value = '';\n }\n\n if (doReduce) {\n value = formatters.reduce(function (v, f) {\n return _this2.format(v, f, options.lng, _objectSpread({}, options, {\n interpolationkey: match[1].trim()\n }));\n }, value.trim());\n }\n\n str = str.replace(match[0], value);\n this.regexp.lastIndex = 0;\n }\n\n return str;\n }\n }]);\n\n return Interpolator;\n}();\n\nfunction remove(arr, what) {\n var found = arr.indexOf(what);\n\n while (found !== -1) {\n arr.splice(found, 1);\n found = arr.indexOf(what);\n }\n}\n\nvar Connector = function (_EventEmitter) {\n _inherits(Connector, _EventEmitter);\n\n function Connector(backend, store, services) {\n var _this;\n\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n\n _classCallCheck(this, Connector);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(Connector).call(this));\n\n if (isIE10) {\n EventEmitter.call(_assertThisInitialized(_this));\n }\n\n _this.backend = backend;\n _this.store = store;\n _this.services = services;\n _this.languageUtils = services.languageUtils;\n _this.options = options;\n _this.logger = baseLogger.create('backendConnector');\n _this.state = {};\n _this.queue = [];\n\n if (_this.backend && _this.backend.init) {\n _this.backend.init(services, options.backend, options);\n }\n\n return _this;\n }\n\n _createClass(Connector, [{\n key: \"queueLoad\",\n value: function queueLoad(languages, namespaces, options, callback) {\n var _this2 = this;\n\n var toLoad = [];\n var pending = [];\n var toLoadLanguages = [];\n var toLoadNamespaces = [];\n languages.forEach(function (lng) {\n var hasAllNamespaces = true;\n namespaces.forEach(function (ns) {\n var name = \"\".concat(lng, \"|\").concat(ns);\n\n if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) {\n _this2.state[name] = 2;\n } else if (_this2.state[name] < 0) ; else if (_this2.state[name] === 1) {\n if (pending.indexOf(name) < 0) pending.push(name);\n } else {\n _this2.state[name] = 1;\n hasAllNamespaces = false;\n if (pending.indexOf(name) < 0) pending.push(name);\n if (toLoad.indexOf(name) < 0) toLoad.push(name);\n if (toLoadNamespaces.indexOf(ns) < 0) toLoadNamespaces.push(ns);\n }\n });\n if (!hasAllNamespaces) toLoadLanguages.push(lng);\n });\n\n if (toLoad.length || pending.length) {\n this.queue.push({\n pending: pending,\n loaded: {},\n errors: [],\n callback: callback\n });\n }\n\n return {\n toLoad: toLoad,\n pending: pending,\n toLoadLanguages: toLoadLanguages,\n toLoadNamespaces: toLoadNamespaces\n };\n }\n }, {\n key: \"loaded\",\n value: function loaded(name, err, data) {\n var s = name.split('|');\n var lng = s[0];\n var ns = s[1];\n if (err) this.emit('failedLoading', lng, ns, err);\n\n if (data) {\n this.store.addResourceBundle(lng, ns, data);\n }\n\n this.state[name] = err ? -1 : 2;\n var loaded = {};\n this.queue.forEach(function (q) {\n pushPath(q.loaded, [lng], ns);\n remove(q.pending, name);\n if (err) q.errors.push(err);\n\n if (q.pending.length === 0 && !q.done) {\n Object.keys(q.loaded).forEach(function (l) {\n if (!loaded[l]) loaded[l] = [];\n\n if (q.loaded[l].length) {\n q.loaded[l].forEach(function (ns) {\n if (loaded[l].indexOf(ns) < 0) loaded[l].push(ns);\n });\n }\n });\n q.done = true;\n\n if (q.errors.length) {\n q.callback(q.errors);\n } else {\n q.callback();\n }\n }\n });\n this.emit('loaded', loaded);\n this.queue = this.queue.filter(function (q) {\n return !q.done;\n });\n }\n }, {\n key: \"read\",\n value: function read(lng, ns, fcName) {\n var _this3 = this;\n\n var tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;\n var wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 350;\n var callback = arguments.length > 5 ? arguments[5] : undefined;\n if (!lng.length) return callback(null, {});\n return this.backend[fcName](lng, ns, function (err, data) {\n if (err && data && tried < 5) {\n setTimeout(function () {\n _this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback);\n }, wait);\n return;\n }\n\n callback(err, data);\n });\n }\n }, {\n key: \"prepareLoading\",\n value: function prepareLoading(languages, namespaces) {\n var _this4 = this;\n\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var callback = arguments.length > 3 ? arguments[3] : undefined;\n\n if (!this.backend) {\n this.logger.warn('No backend was added via i18next.use. Will not load resources.');\n return callback && callback();\n }\n\n if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);\n if (typeof namespaces === 'string') namespaces = [namespaces];\n var toLoad = this.queueLoad(languages, namespaces, options, callback);\n\n if (!toLoad.toLoad.length) {\n if (!toLoad.pending.length) callback();\n return null;\n }\n\n toLoad.toLoad.forEach(function (name) {\n _this4.loadOne(name);\n });\n }\n }, {\n key: \"load\",\n value: function load(languages, namespaces, callback) {\n this.prepareLoading(languages, namespaces, {}, callback);\n }\n }, {\n key: \"reload\",\n value: function reload(languages, namespaces, callback) {\n this.prepareLoading(languages, namespaces, {\n reload: true\n }, callback);\n }\n }, {\n key: \"loadOne\",\n value: function loadOne(name) {\n var _this5 = this;\n\n var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n var s = name.split('|');\n var lng = s[0];\n var ns = s[1];\n this.read(lng, ns, 'read', undefined, undefined, function (err, data) {\n if (err) _this5.logger.warn(\"\".concat(prefix, \"loading namespace \").concat(ns, \" for language \").concat(lng, \" failed\"), err);\n if (!err && data) _this5.logger.log(\"\".concat(prefix, \"loaded namespace \").concat(ns, \" for language \").concat(lng), data);\n\n _this5.loaded(name, err, data);\n });\n }\n }, {\n key: \"saveMissing\",\n value: function saveMissing(languages, namespace, key, fallbackValue, isUpdate) {\n var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};\n\n if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {\n this.logger.warn(\"did not save key \\\"\".concat(key, \"\\\" as the namespace \\\"\").concat(namespace, \"\\\" was not yet loaded\"), 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n return;\n }\n\n if (key === undefined || key === null || key === '') return;\n\n if (this.backend && this.backend.create) {\n this.backend.create(languages, namespace, key, fallbackValue, null, _objectSpread({}, options, {\n isUpdate: isUpdate\n }));\n }\n\n if (!languages || !languages[0]) return;\n this.store.addResource(languages[0], namespace, key, fallbackValue);\n }\n }]);\n\n return Connector;\n}(EventEmitter);\n\nfunction get() {\n return {\n debug: false,\n initImmediate: true,\n ns: ['translation'],\n defaultNS: ['translation'],\n fallbackLng: ['dev'],\n fallbackNS: false,\n whitelist: false,\n nonExplicitWhitelist: false,\n supportedLngs: false,\n nonExplicitSupportedLngs: false,\n load: 'all',\n preload: false,\n simplifyPluralSuffix: true,\n keySeparator: '.',\n nsSeparator: ':',\n pluralSeparator: '_',\n contextSeparator: '_',\n partialBundledLanguages: false,\n saveMissing: false,\n updateMissing: false,\n saveMissingTo: 'fallback',\n saveMissingPlurals: true,\n missingKeyHandler: false,\n missingInterpolationHandler: false,\n postProcess: false,\n postProcessPassResolved: false,\n returnNull: true,\n returnEmptyString: true,\n returnObjects: false,\n joinArrays: false,\n returnedObjectHandler: false,\n parseMissingKeyHandler: false,\n appendNamespaceToMissingKey: false,\n appendNamespaceToCIMode: false,\n overloadTranslationOptionHandler: function handle(args) {\n var ret = {};\n if (_typeof(args[1]) === 'object') ret = args[1];\n if (typeof args[1] === 'string') ret.defaultValue = args[1];\n if (typeof args[2] === 'string') ret.tDescription = args[2];\n\n if (_typeof(args[2]) === 'object' || _typeof(args[3]) === 'object') {\n var options = args[3] || args[2];\n Object.keys(options).forEach(function (key) {\n ret[key] = options[key];\n });\n }\n\n return ret;\n },\n interpolation: {\n escapeValue: true,\n format: function format(value, _format, lng, options) {\n return value;\n },\n prefix: '{{',\n suffix: '}}',\n formatSeparator: ',',\n unescapePrefix: '-',\n nestingPrefix: '$t(',\n nestingSuffix: ')',\n nestingOptionsSeparator: ',',\n maxReplaces: 1000,\n skipOnVariables: false\n }\n };\n}\nfunction transformOptions(options) {\n if (typeof options.ns === 'string') options.ns = [options.ns];\n if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];\n if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];\n\n if (options.whitelist) {\n if (options.whitelist && options.whitelist.indexOf('cimode') < 0) {\n options.whitelist = options.whitelist.concat(['cimode']);\n }\n\n options.supportedLngs = options.whitelist;\n }\n\n if (options.nonExplicitWhitelist) {\n options.nonExplicitSupportedLngs = options.nonExplicitWhitelist;\n }\n\n if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {\n options.supportedLngs = options.supportedLngs.concat(['cimode']);\n }\n\n return options;\n}\n\nfunction noop() {}\n\nvar I18n = function (_EventEmitter) {\n _inherits(I18n, _EventEmitter);\n\n function I18n() {\n var _this;\n\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var callback = arguments.length > 1 ? arguments[1] : undefined;\n\n _classCallCheck(this, I18n);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(I18n).call(this));\n\n if (isIE10) {\n EventEmitter.call(_assertThisInitialized(_this));\n }\n\n _this.options = transformOptions(options);\n _this.services = {};\n _this.logger = baseLogger;\n _this.modules = {\n external: []\n };\n\n if (callback && !_this.isInitialized && !options.isClone) {\n if (!_this.options.initImmediate) {\n _this.init(options, callback);\n\n return _possibleConstructorReturn(_this, _assertThisInitialized(_this));\n }\n\n setTimeout(function () {\n _this.init(options, callback);\n }, 0);\n }\n\n return _this;\n }\n\n _createClass(I18n, [{\n key: \"init\",\n value: function init() {\n var _this2 = this;\n\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var callback = arguments.length > 1 ? arguments[1] : undefined;\n\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n if (options.whitelist && !options.supportedLngs) {\n this.logger.deprecate('whitelist', 'option \"whitelist\" will be renamed to \"supportedLngs\" in the next major - please make sure to rename this option asap.');\n }\n\n if (options.nonExplicitWhitelist && !options.nonExplicitSupportedLngs) {\n this.logger.deprecate('whitelist', 'options \"nonExplicitWhitelist\" will be renamed to \"nonExplicitSupportedLngs\" in the next major - please make sure to rename this option asap.');\n }\n\n this.options = _objectSpread({}, get(), this.options, transformOptions(options));\n this.format = this.options.interpolation.format;\n if (!callback) callback = noop;\n\n function createClassOnDemand(ClassOrObject) {\n if (!ClassOrObject) return null;\n if (typeof ClassOrObject === 'function') return new ClassOrObject();\n return ClassOrObject;\n }\n\n if (!this.options.isClone) {\n if (this.modules.logger) {\n baseLogger.init(createClassOnDemand(this.modules.logger), this.options);\n } else {\n baseLogger.init(null, this.options);\n }\n\n var lu = new LanguageUtil(this.options);\n this.store = new ResourceStore(this.options.resources, this.options);\n var s = this.services;\n s.logger = baseLogger;\n s.resourceStore = this.store;\n s.languageUtils = lu;\n s.pluralResolver = new PluralResolver(lu, {\n prepend: this.options.pluralSeparator,\n compatibilityJSON: this.options.compatibilityJSON,\n simplifyPluralSuffix: this.options.simplifyPluralSuffix\n });\n s.interpolator = new Interpolator(this.options);\n s.utils = {\n hasLoadedNamespace: this.hasLoadedNamespace.bind(this)\n };\n s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);\n s.backendConnector.on('*', function (event) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n _this2.emit.apply(_this2, [event].concat(args));\n });\n\n if (this.modules.languageDetector) {\n s.languageDetector = createClassOnDemand(this.modules.languageDetector);\n s.languageDetector.init(s, this.options.detection, this.options);\n }\n\n if (this.modules.i18nFormat) {\n s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);\n if (s.i18nFormat.init) s.i18nFormat.init(this);\n }\n\n this.translator = new Translator(this.services, this.options);\n this.translator.on('*', function (event) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n _this2.emit.apply(_this2, [event].concat(args));\n });\n this.modules.external.forEach(function (m) {\n if (m.init) m.init(_this2);\n });\n }\n\n if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {\n var codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];\n }\n\n if (!this.services.languageDetector && !this.options.lng) {\n this.logger.warn('init: no languageDetector is used and no lng is defined');\n }\n\n var storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];\n storeApi.forEach(function (fcName) {\n _this2[fcName] = function () {\n var _this2$store;\n\n return (_this2$store = _this2.store)[fcName].apply(_this2$store, arguments);\n };\n });\n var storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];\n storeApiChained.forEach(function (fcName) {\n _this2[fcName] = function () {\n var _this2$store2;\n\n (_this2$store2 = _this2.store)[fcName].apply(_this2$store2, arguments);\n\n return _this2;\n };\n });\n var deferred = defer();\n\n var load = function load() {\n var finish = function finish(err, t) {\n if (_this2.isInitialized) _this2.logger.warn('init: i18next is already initialized. You should call init just once!');\n _this2.isInitialized = true;\n if (!_this2.options.isClone) _this2.logger.log('initialized', _this2.options);\n\n _this2.emit('initialized', _this2.options);\n\n deferred.resolve(t);\n callback(err, t);\n };\n\n if (_this2.languages && _this2.options.compatibilityAPI !== 'v1' && !_this2.isInitialized) return finish(null, _this2.t.bind(_this2));\n\n _this2.changeLanguage(_this2.options.lng, finish);\n };\n\n if (this.options.resources || !this.options.initImmediate) {\n load();\n } else {\n setTimeout(load, 0);\n }\n\n return deferred;\n }\n }, {\n key: \"loadResources\",\n value: function loadResources(language) {\n var _this3 = this;\n\n var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;\n var usedCallback = callback;\n var usedLng = typeof language === 'string' ? language : this.language;\n if (typeof language === 'function') usedCallback = language;\n\n if (!this.options.resources || this.options.partialBundledLanguages) {\n if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback();\n var toLoad = [];\n\n var append = function append(lng) {\n if (!lng) return;\n\n var lngs = _this3.services.languageUtils.toResolveHierarchy(lng);\n\n lngs.forEach(function (l) {\n if (toLoad.indexOf(l) < 0) toLoad.push(l);\n });\n };\n\n if (!usedLng) {\n var fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n fallbacks.forEach(function (l) {\n return append(l);\n });\n } else {\n append(usedLng);\n }\n\n if (this.options.preload) {\n this.options.preload.forEach(function (l) {\n return append(l);\n });\n }\n\n this.services.backendConnector.load(toLoad, this.options.ns, usedCallback);\n } else {\n usedCallback(null);\n }\n }\n }, {\n key: \"reloadResources\",\n value: function reloadResources(lngs, ns, callback) {\n var deferred = defer();\n if (!lngs) lngs = this.languages;\n if (!ns) ns = this.options.ns;\n if (!callback) callback = noop;\n this.services.backendConnector.reload(lngs, ns, function (err) {\n deferred.resolve();\n callback(err);\n });\n return deferred;\n }\n }, {\n key: \"use\",\n value: function use(module) {\n if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');\n if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');\n\n if (module.type === 'backend') {\n this.modules.backend = module;\n }\n\n if (module.type === 'logger' || module.log && module.warn && module.error) {\n this.modules.logger = module;\n }\n\n if (module.type === 'languageDetector') {\n this.modules.languageDetector = module;\n }\n\n if (module.type === 'i18nFormat') {\n this.modules.i18nFormat = module;\n }\n\n if (module.type === 'postProcessor') {\n postProcessor.addPostProcessor(module);\n }\n\n if (module.type === '3rdParty') {\n this.modules.external.push(module);\n }\n\n return this;\n }\n }, {\n key: \"changeLanguage\",\n value: function changeLanguage(lng, callback) {\n var _this4 = this;\n\n this.isLanguageChangingTo = lng;\n var deferred = defer();\n this.emit('languageChanging', lng);\n\n var done = function done(err, l) {\n if (l) {\n _this4.language = l;\n _this4.languages = _this4.services.languageUtils.toResolveHierarchy(l);\n\n _this4.translator.changeLanguage(l);\n\n _this4.isLanguageChangingTo = undefined;\n\n _this4.emit('languageChanged', l);\n\n _this4.logger.log('languageChanged', l);\n } else {\n _this4.isLanguageChangingTo = undefined;\n }\n\n deferred.resolve(function () {\n return _this4.t.apply(_this4, arguments);\n });\n if (callback) callback(err, function () {\n return _this4.t.apply(_this4, arguments);\n });\n };\n\n var setLng = function setLng(lngs) {\n if (!lng && !lngs && _this4.services.languageDetector) lngs = [];\n var l = typeof lngs === 'string' ? lngs : _this4.services.languageUtils.getBestMatchFromCodes(lngs);\n\n if (l) {\n if (!_this4.language) {\n _this4.language = l;\n _this4.languages = _this4.services.languageUtils.toResolveHierarchy(l);\n }\n\n if (!_this4.translator.language) _this4.translator.changeLanguage(l);\n if (_this4.services.languageDetector) _this4.services.languageDetector.cacheUserLanguage(l);\n }\n\n _this4.loadResources(l, function (err) {\n done(err, l);\n });\n };\n\n if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {\n setLng(this.services.languageDetector.detect());\n } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {\n this.services.languageDetector.detect(setLng);\n } else {\n setLng(lng);\n }\n\n return deferred;\n }\n }, {\n key: \"getFixedT\",\n value: function getFixedT(lng, ns) {\n var _this5 = this;\n\n var fixedT = function fixedT(key, opts) {\n var options;\n\n if (_typeof(opts) !== 'object') {\n for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {\n rest[_key3 - 2] = arguments[_key3];\n }\n\n options = _this5.options.overloadTranslationOptionHandler([key, opts].concat(rest));\n } else {\n options = _objectSpread({}, opts);\n }\n\n options.lng = options.lng || fixedT.lng;\n options.lngs = options.lngs || fixedT.lngs;\n options.ns = options.ns || fixedT.ns;\n return _this5.t(key, options);\n };\n\n if (typeof lng === 'string') {\n fixedT.lng = lng;\n } else {\n fixedT.lngs = lng;\n }\n\n fixedT.ns = ns;\n return fixedT;\n }\n }, {\n key: \"t\",\n value: function t() {\n var _this$translator;\n\n return this.translator && (_this$translator = this.translator).translate.apply(_this$translator, arguments);\n }\n }, {\n key: \"exists\",\n value: function exists() {\n var _this$translator2;\n\n return this.translator && (_this$translator2 = this.translator).exists.apply(_this$translator2, arguments);\n }\n }, {\n key: \"setDefaultNamespace\",\n value: function setDefaultNamespace(ns) {\n this.options.defaultNS = ns;\n }\n }, {\n key: \"hasLoadedNamespace\",\n value: function hasLoadedNamespace(ns) {\n var _this6 = this;\n\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (!this.isInitialized) {\n this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);\n return false;\n }\n\n if (!this.languages || !this.languages.length) {\n this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);\n return false;\n }\n\n var lng = this.languages[0];\n var fallbackLng = this.options ? this.options.fallbackLng : false;\n var lastLng = this.languages[this.languages.length - 1];\n if (lng.toLowerCase() === 'cimode') return true;\n\n var loadNotPending = function loadNotPending(l, n) {\n var loadState = _this6.services.backendConnector.state[\"\".concat(l, \"|\").concat(n)];\n\n return loadState === -1 || loadState === 2;\n };\n\n if (options.precheck) {\n var preResult = options.precheck(this, loadNotPending);\n if (preResult !== undefined) return preResult;\n }\n\n if (this.hasResourceBundle(lng, ns)) return true;\n if (!this.services.backendConnector.backend) return true;\n if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;\n return false;\n }\n }, {\n key: \"loadNamespaces\",\n value: function loadNamespaces(ns, callback) {\n var _this7 = this;\n\n var deferred = defer();\n\n if (!this.options.ns) {\n callback && callback();\n return Promise.resolve();\n }\n\n if (typeof ns === 'string') ns = [ns];\n ns.forEach(function (n) {\n if (_this7.options.ns.indexOf(n) < 0) _this7.options.ns.push(n);\n });\n this.loadResources(function (err) {\n deferred.resolve();\n if (callback) callback(err);\n });\n return deferred;\n }\n }, {\n key: \"loadLanguages\",\n value: function loadLanguages(lngs, callback) {\n var deferred = defer();\n if (typeof lngs === 'string') lngs = [lngs];\n var preloaded = this.options.preload || [];\n var newLngs = lngs.filter(function (lng) {\n return preloaded.indexOf(lng) < 0;\n });\n\n if (!newLngs.length) {\n if (callback) callback();\n return Promise.resolve();\n }\n\n this.options.preload = preloaded.concat(newLngs);\n this.loadResources(function (err) {\n deferred.resolve();\n if (callback) callback(err);\n });\n return deferred;\n }\n }, {\n key: \"dir\",\n value: function dir(lng) {\n if (!lng) lng = this.languages && this.languages.length > 0 ? this.languages[0] : this.language;\n if (!lng) return 'rtl';\n var rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam'];\n return rtlLngs.indexOf(this.services.languageUtils.getLanguagePartFromCode(lng)) >= 0 ? 'rtl' : 'ltr';\n }\n }, {\n key: \"createInstance\",\n value: function createInstance() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var callback = arguments.length > 1 ? arguments[1] : undefined;\n return new I18n(options, callback);\n }\n }, {\n key: \"cloneInstance\",\n value: function cloneInstance() {\n var _this8 = this;\n\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;\n\n var mergedOptions = _objectSpread({}, this.options, options, {\n isClone: true\n });\n\n var clone = new I18n(mergedOptions);\n var membersToCopy = ['store', 'services', 'language'];\n membersToCopy.forEach(function (m) {\n clone[m] = _this8[m];\n });\n clone.services = _objectSpread({}, this.services);\n clone.services.utils = {\n hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n };\n clone.translator = new Translator(clone.services, clone.options);\n clone.translator.on('*', function (event) {\n for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {\n args[_key4 - 1] = arguments[_key4];\n }\n\n clone.emit.apply(clone, [event].concat(args));\n });\n clone.init(mergedOptions, callback);\n clone.translator.options = clone.options;\n clone.translator.backendConnector.services.utils = {\n hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n };\n return clone;\n }\n }, {\n key: \"toJSON\",\n value: function toJSON() {\n return {\n options: this.options,\n store: this.store,\n language: this.language,\n languages: this.languages\n };\n }\n }]);\n\n return I18n;\n}(EventEmitter);\n\nvar i18next = new I18n();\n\nexport default i18next;\n","export default function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n}","import _classCallCheck from \"@babel/runtime/helpers/classCallCheck\";\nimport _createClass from \"@babel/runtime/helpers/createClass\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nimport React from 'react';\nvar defaultOptions = {\n bindI18n: 'languageChanged',\n bindI18nStore: '',\n transEmptyNodeValue: '',\n transSupportBasicHtmlNodes: true,\n transWrapTextNodes: '',\n transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'],\n useSuspense: true\n};\nvar i18nInstance;\nexport var I18nContext = React.createContext();\nexport function setDefaults() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n defaultOptions = _objectSpread(_objectSpread({}, defaultOptions), options);\n}\nexport function getDefaults() {\n return defaultOptions;\n}\nexport var ReportNamespaces = function () {\n function ReportNamespaces() {\n _classCallCheck(this, ReportNamespaces);\n\n this.usedNamespaces = {};\n }\n\n _createClass(ReportNamespaces, [{\n key: \"addUsedNamespaces\",\n value: function addUsedNamespaces(namespaces) {\n var _this = this;\n\n namespaces.forEach(function (ns) {\n if (!_this.usedNamespaces[ns]) _this.usedNamespaces[ns] = true;\n });\n }\n }, {\n key: \"getUsedNamespaces\",\n value: function getUsedNamespaces() {\n return Object.keys(this.usedNamespaces);\n }\n }]);\n\n return ReportNamespaces;\n}();\nexport function setI18n(instance) {\n i18nInstance = instance;\n}\nexport function getI18n() {\n return i18nInstance;\n}\nexport var initReactI18next = {\n type: '3rdParty',\n init: function init(instance) {\n setDefaults(instance.options.react);\n setI18n(instance);\n }\n};\nexport function composeInitialProps(ForComponent) {\n return function (ctx) {\n return new Promise(function (resolve) {\n var i18nInitialProps = getInitialProps();\n\n if (ForComponent.getInitialProps) {\n ForComponent.getInitialProps(ctx).then(function (componentsInitialProps) {\n resolve(_objectSpread(_objectSpread({}, componentsInitialProps), i18nInitialProps));\n });\n } else {\n resolve(i18nInitialProps);\n }\n });\n };\n}\nexport function getInitialProps() {\n var i18n = getI18n();\n var namespaces = i18n.reportNamespaces ? i18n.reportNamespaces.getUsedNamespaces() : [];\n var ret = {};\n var initialI18nStore = {};\n i18n.languages.forEach(function (l) {\n initialI18nStore[l] = {};\n namespaces.forEach(function (ns) {\n initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {};\n });\n });\n ret.initialI18nStore = initialI18nStore;\n ret.initialLanguage = i18n.language;\n return ret;\n}","export default function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}","export function warn() {\n if (console && console.warn) {\n var _console;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (typeof args[0] === 'string') args[0] = \"react-i18next:: \".concat(args[0]);\n\n (_console = console).warn.apply(_console, args);\n }\n}\nvar alreadyWarned = {};\nexport function warnOnce() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n if (typeof args[0] === 'string' && alreadyWarned[args[0]]) return;\n if (typeof args[0] === 'string') alreadyWarned[args[0]] = new Date();\n warn.apply(void 0, args);\n}\nexport function loadNamespaces(i18n, ns, cb) {\n i18n.loadNamespaces(ns, function () {\n if (i18n.isInitialized) {\n cb();\n } else {\n var initialized = function initialized() {\n setTimeout(function () {\n i18n.off('initialized', initialized);\n }, 0);\n cb();\n };\n\n i18n.on('initialized', initialized);\n }\n });\n}\nexport function hasLoadedNamespace(ns, i18n) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n if (!i18n.languages || !i18n.languages.length) {\n warnOnce('i18n.languages were undefined or empty', i18n.languages);\n return true;\n }\n\n var lng = i18n.languages[0];\n var fallbackLng = i18n.options ? i18n.options.fallbackLng : false;\n var lastLng = i18n.languages[i18n.languages.length - 1];\n if (lng.toLowerCase() === 'cimode') return true;\n\n var loadNotPending = function loadNotPending(l, n) {\n var loadState = i18n.services.backendConnector.state[\"\".concat(l, \"|\").concat(n)];\n return loadState === -1 || loadState === 2;\n };\n\n if (options.bindI18n && options.bindI18n.indexOf('languageChanging') > -1 && i18n.services.backendConnector.backend && i18n.isLanguageChangingTo && !loadNotPending(i18n.isLanguageChangingTo, ns)) return false;\n if (i18n.hasResourceBundle(lng, ns)) return true;\n if (!i18n.services.backendConnector.backend) return true;\n if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;\n return false;\n}\nexport function getDisplayName(Component) {\n return Component.displayName || Component.name || (typeof Component === 'string' && Component.length > 0 ? Component : 'Unknown');\n}","export default function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) {\n arr2[i] = arr[i];\n }\n\n return arr2;\n}","import arrayWithHoles from \"./arrayWithHoles.js\";\nimport iterableToArrayLimit from \"./iterableToArrayLimit.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableRest from \"./nonIterableRest.js\";\nexport default function _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}","export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}","export default function _iterableToArrayLimit(arr, i) {\n var _i = arr == null ? null : typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"];\n\n if (_i == null) return;\n var _arr = [];\n var _n = true;\n var _d = false;\n\n var _s, _e;\n\n try {\n for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}","export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}","import _slicedToArray from \"@babel/runtime/helpers/slicedToArray\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nimport { useState, useEffect, useContext, useRef } from 'react';\nimport { getI18n, getDefaults, ReportNamespaces, I18nContext } from './context';\nimport { warnOnce, loadNamespaces, hasLoadedNamespace } from './utils';\nexport function useTranslation(ns) {\n var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var i18nFromProps = props.i18n;\n\n var _ref = useContext(I18nContext) || {},\n i18nFromContext = _ref.i18n,\n defaultNSFromContext = _ref.defaultNS;\n\n var i18n = i18nFromProps || i18nFromContext || getI18n();\n if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces();\n\n if (!i18n) {\n warnOnce('You will need to pass in an i18next instance by using initReactI18next');\n\n var notReadyT = function notReadyT(k) {\n return Array.isArray(k) ? k[k.length - 1] : k;\n };\n\n var retNotReady = [notReadyT, {}, false];\n retNotReady.t = notReadyT;\n retNotReady.i18n = {};\n retNotReady.ready = false;\n return retNotReady;\n }\n\n if (i18n.options.react && i18n.options.react.wait !== undefined) warnOnce('It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.');\n\n var i18nOptions = _objectSpread(_objectSpread(_objectSpread({}, getDefaults()), i18n.options.react), props);\n\n var useSuspense = i18nOptions.useSuspense;\n var namespaces = ns || defaultNSFromContext || i18n.options && i18n.options.defaultNS;\n namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation'];\n if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces);\n var ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(function (n) {\n return hasLoadedNamespace(n, i18n, i18nOptions);\n });\n\n function getT() {\n return i18n.getFixedT(null, i18nOptions.nsMode === 'fallback' ? namespaces : namespaces[0]);\n }\n\n var _useState = useState(getT),\n _useState2 = _slicedToArray(_useState, 2),\n t = _useState2[0],\n setT = _useState2[1];\n\n var isMounted = useRef(true);\n useEffect(function () {\n var bindI18n = i18nOptions.bindI18n,\n bindI18nStore = i18nOptions.bindI18nStore;\n isMounted.current = true;\n\n if (!ready && !useSuspense) {\n loadNamespaces(i18n, namespaces, function () {\n if (isMounted.current) setT(getT);\n });\n }\n\n function boundReset() {\n if (isMounted.current) setT(getT);\n }\n\n if (bindI18n && i18n) i18n.on(bindI18n, boundReset);\n if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, boundReset);\n return function () {\n isMounted.current = false;\n if (bindI18n && i18n) bindI18n.split(' ').forEach(function (e) {\n return i18n.off(e, boundReset);\n });\n if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(function (e) {\n return i18n.store.off(e, boundReset);\n });\n };\n }, [i18n, namespaces.join()]);\n var isInitial = useRef(true);\n useEffect(function () {\n if (isMounted.current && !isInitial.current) {\n setT(getT);\n }\n\n isInitial.current = false;\n }, [i18n]);\n var ret = [t, i18n, ready];\n ret.t = t;\n ret.i18n = i18n;\n ret.ready = ready;\n if (ready) return ret;\n if (!ready && !useSuspense) return ret;\n throw new Promise(function (resolve) {\n loadNamespaces(i18n, namespaces, function () {\n resolve();\n });\n });\n}","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport en from './en.json';\nimport zh from './zh.json';\n\nconst resources = {\n en: {\n translation: en,\n },\n zh: {\n translation: zh,\n },\n};\n\nexport default resources;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport i18n from 'i18next';\nimport { initReactI18next } from 'react-i18next';\nimport resources from './locales/resources';\n\n// the translations\n// (tip move them in a JSON file and import them,\n// or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui)\n\ni18n\n .use(initReactI18next) // passes i18n down to react-i18next\n .init({\n resources,\n lng: localStorage.getItem('language') || 'zh', // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources\n // you can use the i18n.changeLanguage function to change the language manually: https://www.i18next.com/overview/api#changelanguage\n // if you're using a language detector, do not define the lng option\n\n interpolation: {\n escapeValue: false, // react already safes from xss\n },\n });\n\nexport default i18n;\n","import React from 'react';\nexport var ReactReduxContext = /*#__PURE__*/React.createContext(null);\n\nif (process.env.NODE_ENV !== 'production') {\n ReactReduxContext.displayName = 'ReactRedux';\n}\n\nexport default ReactReduxContext;","// Default to a dummy \"batch\" implementation that just runs the callback\nfunction defaultNoopBatch(callback) {\n callback();\n}\n\nvar batch = defaultNoopBatch; // Allow injecting another batching function later\n\nexport var setBatch = function setBatch(newBatch) {\n return batch = newBatch;\n}; // Supply a getter just to skip dealing with ESM bindings\n\nexport var getBatch = function getBatch() {\n return batch;\n};","import { getBatch } from './batch'; // encapsulates the subscription logic for connecting a component to the redux store, as\n// well as nesting subscriptions of descendant components, so that we can ensure the\n// ancestor components re-render before descendants\n\nvar nullListeners = {\n notify: function notify() {}\n};\n\nfunction createListenerCollection() {\n var batch = getBatch();\n var first = null;\n var last = null;\n return {\n clear: function clear() {\n first = null;\n last = null;\n },\n notify: function notify() {\n batch(function () {\n var listener = first;\n\n while (listener) {\n listener.callback();\n listener = listener.next;\n }\n });\n },\n get: function get() {\n var listeners = [];\n var listener = first;\n\n while (listener) {\n listeners.push(listener);\n listener = listener.next;\n }\n\n return listeners;\n },\n subscribe: function subscribe(callback) {\n var isSubscribed = true;\n var listener = last = {\n callback: callback,\n next: null,\n prev: last\n };\n\n if (listener.prev) {\n listener.prev.next = listener;\n } else {\n first = listener;\n }\n\n return function unsubscribe() {\n if (!isSubscribed || first === null) return;\n isSubscribed = false;\n\n if (listener.next) {\n listener.next.prev = listener.prev;\n } else {\n last = listener.prev;\n }\n\n if (listener.prev) {\n listener.prev.next = listener.next;\n } else {\n first = listener.next;\n }\n };\n }\n };\n}\n\nvar Subscription = /*#__PURE__*/function () {\n function Subscription(store, parentSub) {\n this.store = store;\n this.parentSub = parentSub;\n this.unsubscribe = null;\n this.listeners = nullListeners;\n this.handleChangeWrapper = this.handleChangeWrapper.bind(this);\n }\n\n var _proto = Subscription.prototype;\n\n _proto.addNestedSub = function addNestedSub(listener) {\n this.trySubscribe();\n return this.listeners.subscribe(listener);\n };\n\n _proto.notifyNestedSubs = function notifyNestedSubs() {\n this.listeners.notify();\n };\n\n _proto.handleChangeWrapper = function handleChangeWrapper() {\n if (this.onStateChange) {\n this.onStateChange();\n }\n };\n\n _proto.isSubscribed = function isSubscribed() {\n return Boolean(this.unsubscribe);\n };\n\n _proto.trySubscribe = function trySubscribe() {\n if (!this.unsubscribe) {\n this.unsubscribe = this.parentSub ? this.parentSub.addNestedSub(this.handleChangeWrapper) : this.store.subscribe(this.handleChangeWrapper);\n this.listeners = createListenerCollection();\n }\n };\n\n _proto.tryUnsubscribe = function tryUnsubscribe() {\n if (this.unsubscribe) {\n this.unsubscribe();\n this.unsubscribe = null;\n this.listeners.clear();\n this.listeners = nullListeners;\n }\n };\n\n return Subscription;\n}();\n\nexport { Subscription as default };","import { useEffect, useLayoutEffect } from 'react'; // React currently throws a warning when using useLayoutEffect on the server.\n// To get around it, we can conditionally useEffect on the server (no-op) and\n// useLayoutEffect in the browser. We need useLayoutEffect to ensure the store\n// subscription callback always has the selector from the latest render commit\n// available, otherwise a store update may happen between render and the effect,\n// which may cause missed updates; we also must ensure the store subscription\n// is created synchronously, otherwise a store update may occur before the\n// subscription is created and an inconsistent state may be observed\n\nexport var useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? useLayoutEffect : useEffect;","import React, { useMemo } from 'react';\nimport PropTypes from 'prop-types';\nimport { ReactReduxContext } from './Context';\nimport Subscription from '../utils/Subscription';\nimport { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';\n\nfunction Provider(_ref) {\n var store = _ref.store,\n context = _ref.context,\n children = _ref.children;\n var contextValue = useMemo(function () {\n var subscription = new Subscription(store);\n subscription.onStateChange = subscription.notifyNestedSubs;\n return {\n store: store,\n subscription: subscription\n };\n }, [store]);\n var previousState = useMemo(function () {\n return store.getState();\n }, [store]);\n useIsomorphicLayoutEffect(function () {\n var subscription = contextValue.subscription;\n subscription.trySubscribe();\n\n if (previousState !== store.getState()) {\n subscription.notifyNestedSubs();\n }\n\n return function () {\n subscription.tryUnsubscribe();\n subscription.onStateChange = null;\n };\n }, [contextValue, previousState]);\n var Context = context || ReactReduxContext;\n return /*#__PURE__*/React.createElement(Context.Provider, {\n value: contextValue\n }, children);\n}\n\nif (process.env.NODE_ENV !== 'production') {\n Provider.propTypes = {\n store: PropTypes.shape({\n subscribe: PropTypes.func.isRequired,\n dispatch: PropTypes.func.isRequired,\n getState: PropTypes.func.isRequired\n }),\n context: PropTypes.object,\n children: PropTypes.any\n };\n}\n\nexport default Provider;","import { useContext } from 'react';\nimport { ReactReduxContext } from '../components/Context';\n/**\r\n * A hook to access the value of the `ReactReduxContext`. This is a low-level\r\n * hook that you should usually not need to call directly.\r\n *\r\n * @returns {any} the value of the `ReactReduxContext`\r\n *\r\n * @example\r\n *\r\n * import React from 'react'\r\n * import { useReduxContext } from 'react-redux'\r\n *\r\n * export const CounterComponent = ({ value }) => {\r\n * const { store } = useReduxContext()\r\n * return
{store.getState()}
\r\n * }\r\n */\n\nexport function useReduxContext() {\n var contextValue = useContext(ReactReduxContext);\n\n if (process.env.NODE_ENV !== 'production' && !contextValue) {\n throw new Error('could not find react-redux context value; please ensure the component is wrapped in a ');\n }\n\n return contextValue;\n}","import { useContext } from 'react';\nimport { ReactReduxContext } from '../components/Context';\nimport { useReduxContext as useDefaultReduxContext } from './useReduxContext';\n/**\r\n * Hook factory, which creates a `useStore` hook bound to a given context.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useStore` hook bound to the specified context.\r\n */\n\nexport function createStoreHook(context) {\n if (context === void 0) {\n context = ReactReduxContext;\n }\n\n var useReduxContext = context === ReactReduxContext ? useDefaultReduxContext : function () {\n return useContext(context);\n };\n return function useStore() {\n var _useReduxContext = useReduxContext(),\n store = _useReduxContext.store;\n\n return store;\n };\n}\n/**\r\n * A hook to access the redux store.\r\n *\r\n * @returns {any} the redux store\r\n *\r\n * @example\r\n *\r\n * import React from 'react'\r\n * import { useStore } from 'react-redux'\r\n *\r\n * export const ExampleComponent = () => {\r\n * const store = useStore()\r\n * return
{store.getState()}
\r\n * }\r\n */\n\nexport var useStore = /*#__PURE__*/createStoreHook();","import { ReactReduxContext } from '../components/Context';\nimport { useStore as useDefaultStore, createStoreHook } from './useStore';\n/**\r\n * Hook factory, which creates a `useDispatch` hook bound to a given context.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useDispatch` hook bound to the specified context.\r\n */\n\nexport function createDispatchHook(context) {\n if (context === void 0) {\n context = ReactReduxContext;\n }\n\n var useStore = context === ReactReduxContext ? useDefaultStore : createStoreHook(context);\n return function useDispatch() {\n var store = useStore();\n return store.dispatch;\n };\n}\n/**\r\n * A hook to access the redux `dispatch` function.\r\n *\r\n * @returns {any|function} redux store's `dispatch` function\r\n *\r\n * @example\r\n *\r\n * import React, { useCallback } from 'react'\r\n * import { useDispatch } from 'react-redux'\r\n *\r\n * export const CounterComponent = ({ value }) => {\r\n * const dispatch = useDispatch()\r\n * const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])\r\n * return (\r\n *
\r\n * {value}\r\n * \r\n *
\r\n * )\r\n * }\r\n */\n\nexport var useDispatch = /*#__PURE__*/createDispatchHook();","import { useReducer, useRef, useMemo, useContext, useDebugValue } from 'react';\nimport { useReduxContext as useDefaultReduxContext } from './useReduxContext';\nimport Subscription from '../utils/Subscription';\nimport { useIsomorphicLayoutEffect } from '../utils/useIsomorphicLayoutEffect';\nimport { ReactReduxContext } from '../components/Context';\n\nvar refEquality = function refEquality(a, b) {\n return a === b;\n};\n\nfunction useSelectorWithStoreAndSubscription(selector, equalityFn, store, contextSub) {\n var _useReducer = useReducer(function (s) {\n return s + 1;\n }, 0),\n forceRender = _useReducer[1];\n\n var subscription = useMemo(function () {\n return new Subscription(store, contextSub);\n }, [store, contextSub]);\n var latestSubscriptionCallbackError = useRef();\n var latestSelector = useRef();\n var latestStoreState = useRef();\n var latestSelectedState = useRef();\n var storeState = store.getState();\n var selectedState;\n\n try {\n if (selector !== latestSelector.current || storeState !== latestStoreState.current || latestSubscriptionCallbackError.current) {\n var newSelectedState = selector(storeState); // ensure latest selected state is reused so that a custom equality function can result in identical references\n\n if (latestSelectedState.current === undefined || !equalityFn(newSelectedState, latestSelectedState.current)) {\n selectedState = newSelectedState;\n } else {\n selectedState = latestSelectedState.current;\n }\n } else {\n selectedState = latestSelectedState.current;\n }\n } catch (err) {\n if (latestSubscriptionCallbackError.current) {\n err.message += \"\\nThe error may be correlated with this previous error:\\n\" + latestSubscriptionCallbackError.current.stack + \"\\n\\n\";\n }\n\n throw err;\n }\n\n useIsomorphicLayoutEffect(function () {\n latestSelector.current = selector;\n latestStoreState.current = storeState;\n latestSelectedState.current = selectedState;\n latestSubscriptionCallbackError.current = undefined;\n });\n useIsomorphicLayoutEffect(function () {\n function checkForUpdates() {\n try {\n var newStoreState = store.getState();\n\n var _newSelectedState = latestSelector.current(newStoreState);\n\n if (equalityFn(_newSelectedState, latestSelectedState.current)) {\n return;\n }\n\n latestSelectedState.current = _newSelectedState;\n latestStoreState.current = newStoreState;\n } catch (err) {\n // we ignore all errors here, since when the component\n // is re-rendered, the selectors are called again, and\n // will throw again, if neither props nor store state\n // changed\n latestSubscriptionCallbackError.current = err;\n }\n\n forceRender();\n }\n\n subscription.onStateChange = checkForUpdates;\n subscription.trySubscribe();\n checkForUpdates();\n return function () {\n return subscription.tryUnsubscribe();\n };\n }, [store, subscription]);\n return selectedState;\n}\n/**\r\n * Hook factory, which creates a `useSelector` hook bound to a given context.\r\n *\r\n * @param {React.Context} [context=ReactReduxContext] Context passed to your ``.\r\n * @returns {Function} A `useSelector` hook bound to the specified context.\r\n */\n\n\nexport function createSelectorHook(context) {\n if (context === void 0) {\n context = ReactReduxContext;\n }\n\n var useReduxContext = context === ReactReduxContext ? useDefaultReduxContext : function () {\n return useContext(context);\n };\n return function useSelector(selector, equalityFn) {\n if (equalityFn === void 0) {\n equalityFn = refEquality;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!selector) {\n throw new Error(\"You must pass a selector to useSelector\");\n }\n\n if (typeof selector !== 'function') {\n throw new Error(\"You must pass a function as a selector to useSelector\");\n }\n\n if (typeof equalityFn !== 'function') {\n throw new Error(\"You must pass a function as an equality function to useSelector\");\n }\n }\n\n var _useReduxContext = useReduxContext(),\n store = _useReduxContext.store,\n contextSub = _useReduxContext.subscription;\n\n var selectedState = useSelectorWithStoreAndSubscription(selector, equalityFn, store, contextSub);\n useDebugValue(selectedState);\n return selectedState;\n };\n}\n/**\r\n * A hook to access the redux store's state. This hook takes a selector function\r\n * as an argument. The selector is called with the store state.\r\n *\r\n * This hook takes an optional equality comparison function as the second parameter\r\n * that allows you to customize the way the selected state is compared to determine\r\n * whether the component needs to be re-rendered.\r\n *\r\n * @param {Function} selector the selector function\r\n * @param {Function=} equalityFn the function that will be used to determine equality\r\n *\r\n * @returns {any} the selected state\r\n *\r\n * @example\r\n *\r\n * import React from 'react'\r\n * import { useSelector } from 'react-redux'\r\n *\r\n * export const CounterComponent = () => {\r\n * const counter = useSelector(state => state.counter)\r\n * return
{counter}
\r\n * }\r\n */\n\nexport var useSelector = /*#__PURE__*/createSelectorHook();","import Provider from './components/Provider';\nimport connectAdvanced from './components/connectAdvanced';\nimport { ReactReduxContext } from './components/Context';\nimport connect from './connect/connect';\nimport { useDispatch, createDispatchHook } from './hooks/useDispatch';\nimport { useSelector, createSelectorHook } from './hooks/useSelector';\nimport { useStore, createStoreHook } from './hooks/useStore';\nimport { setBatch } from './utils/batch';\nimport { unstable_batchedUpdates as batch } from './utils/reactBatchedUpdates';\nimport shallowEqual from './utils/shallowEqual';\nsetBatch(batch);\nexport { Provider, connectAdvanced, ReactReduxContext, connect, batch, useDispatch, createDispatchHook, useSelector, createSelectorHook, useStore, createStoreHook, shallowEqual };","import React, { ReactNode, useContext } from 'react';\nimport { Tooltip } from 'antd';\nimport { MenuItemProps, isSubMenu } from './types';\nimport './index.less';\nimport { useMenuSelect, useMenuActive, Context } from './index';\nimport classNames from 'classnames';\ninterface Props {\n item: MenuItemProps;\n subMenuKey?: string;\n collapsed?: boolean;\n}\n\nexport default function FcMenuItem(props: Props) {\n const { item, subMenuKey, collapsed } = props;\n const { activeMode } = useContext(Context);\n const [menuSelect, setMenuSelect] = useMenuSelect();\n const [menuActive, setMenuActive] = useMenuActive();\n const handleClick = () => {\n const keys = [item.key];\n subMenuKey && keys.unshift(subMenuKey);\n setMenuSelect(keys);\n };\n\n const handleHover = () => {\n if (activeMode === 'hover') {\n const keys = [item.key];\n subMenuKey && keys.unshift(subMenuKey);\n setMenuActive(keys);\n }\n };\n\n return (\n \n {!subMenuKey && (menuActive.length > 0 ? menuActive.includes(item.key) : menuSelect.includes(item.key)) && (\n <>\n
\n
\n
\n
\n
\n \n )}\n {collapsed ? (\n \n {item.icon}\n \n ) : (\n {item.icon}\n )}\n\n {!collapsed && {item.label}}\n \n );\n}\n","import React, { ReactNode, useState, useContext, useEffect } from 'react';\nimport { Tooltip, Menu } from 'antd';\nimport { SubMenuProps } from './types';\nimport './index.less';\nimport Item from './menuItem';\nimport classNames from 'classnames';\nimport { useMenuSelect, useMenuActive, Context } from './index';\ninterface Props {\n item: SubMenuProps;\n collapsed: boolean;\n}\n\nexport default function FcSubMenu(props: Props) {\n const { item, collapsed } = props;\n const { activeMode } = useContext(Context);\n const [menuSelect, setMenuSelect] = useMenuSelect();\n const [menuActive, setMenuActive] = useMenuActive();\n const [collapse, setCollapse] = useState(false);\n const selected = menuSelect.includes(item.key) && menuSelect.length > 1;\n const showHoverModeSelected = menuActive.length > 0 ? menuActive.includes(item.key) : selected;\n useEffect(() => {\n if (collapsed) {\n setCollapse(selected);\n }\n }, [menuSelect, collapsed]);\n\n const menu = (\n setMenuSelect([item.key, key])}>\n {item.children\n .filter((i) => !!i)\n .map((item) => (\n {item.label}\n ))}\n \n );\n return (\n {\n if (activeMode === 'hover') {\n setCollapse(true);\n setMenuActive([item.key]);\n }\n }}\n onMouseLeave={() => {\n if (activeMode === 'hover') {\n setCollapse(false);\n }\n }}\n >\n {(collapse || (activeMode === 'hover' ? showHoverModeSelected : selected)) && (\n <>\n
\n
\n
\n
\n
\n \n )}\n {\n if (activeMode === 'click') {\n if (!collapsed) {\n setCollapse(!collapse);\n }\n }\n }}\n onMouseEnter={() => {\n if (activeMode === 'hover') {\n setMenuActive([item.key]);\n }\n }}\n >\n {collapsed ? (\n \n {item.icon}\n \n ) : (\n {item.icon}\n )}\n {!collapsed && {item.label}}\n \n\n {activeMode === 'click' && !collapsed && collapse && item.children.filter((i) => !!i).map((i) => )}\n\n {activeMode === 'hover' &&\n !collapsed &&\n (collapse || showHoverModeSelected) &&\n item.children.filter((i) => !!i).map((i) => )}\n \n );\n}\n","import { useEffect } from 'react';\nvar useEffectOnce = function (effect) {\n useEffect(effect, []);\n};\nexport default useEffectOnce;\n","import { useEffect, useLayoutEffect } from 'react';\nimport { isBrowser } from './misc/util';\nvar useIsomorphicLayoutEffect = isBrowser ? useLayoutEffect : useEffect;\nexport default useIsomorphicLayoutEffect;\n","export var noop = function () { };\nexport function on(obj) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (obj && obj.addEventListener) {\n obj.addEventListener.apply(obj, args);\n }\n}\nexport function off(obj) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (obj && obj.removeEventListener) {\n obj.removeEventListener.apply(obj, args);\n }\n}\nexport var isBrowser = typeof window !== 'undefined';\nexport var isNavigator = typeof navigator !== 'undefined';\n","import { useState } from 'react';\nimport { resolveHookState } from '../misc/hookState';\nimport useEffectOnce from '../useEffectOnce';\nimport useIsomorphicLayoutEffect from '../useIsomorphicLayoutEffect';\nexport function createGlobalState(initialState) {\n var store = {\n state: initialState instanceof Function ? initialState() : initialState,\n setState: function (nextState) {\n store.state = resolveHookState(nextState, store.state);\n store.setters.forEach(function (setter) { return setter(store.state); });\n },\n setters: [],\n };\n return function () {\n var _a = useState(store.state), globalState = _a[0], stateSetter = _a[1];\n useEffectOnce(function () { return function () {\n store.setters = store.setters.filter(function (setter) { return setter !== stateSetter; });\n }; });\n useIsomorphicLayoutEffect(function () {\n if (!store.setters.includes(stateSetter)) {\n store.setters.push(stateSetter);\n }\n });\n return [globalState, store.setState];\n };\n}\nexport default createGlobalState;\n","export function resolveHookState(nextState, currentState) {\n if (typeof nextState === 'function') {\n return nextState.length ? nextState(currentState) : nextState();\n }\n return nextState;\n}\n","import React, { ReactNode, useState } from 'react';\nimport { IMenuProps, MenuItemProps, SubMenuProps } from './types';\nimport './index.less';\nimport { useMenuSelect } from './index';\n\ninterface Props {\n items: IMenuProps[];\n}\n\nexport default function FcMenuItem(props: Props) {\n const { items } = props;\n const [menuSelect, setMenuSelect] = useMenuSelect();\n\n const [hoverSecondMenus, setHoverSecondMenus] = useState();\n\n return (\n
\n
\n {items\n .filter((item) => !!item)\n .map((item: SubMenuProps) => (\n
setHoverSecondMenus(item)} onClick={() => !item.children && setMenuSelect([item.key])}>\n {item.label}\n
\n ))}\n
\n
\n
\n {hoverSecondMenus &&\n hoverSecondMenus.children &&\n hoverSecondMenus.children\n .filter((item) => !!item)\n .map((item: MenuItemProps) => (\n
setMenuSelect([hoverSecondMenus.key, item.key])}>\n {item.label}\n
\n ))}\n
\n
\n
\n );\n}\n","import React, { useState, useEffect, createContext } from 'react';\nimport { Tooltip } from 'antd';\nimport { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';\nimport { IMenuProps, isSubMenu, SubMenuProps } from './types';\nimport './index.less';\nimport Item from './menuItem';\nimport SubMenu from './subMenu';\nimport createGlobalState from 'react-use/esm/factory/createGlobalState';\nimport className from 'classnames';\nimport SkimMenu from './skimMenu';\ninterface Props {\n items: IMenuProps[];\n onClick: (key: string) => void;\n collapsed: string | null;\n switchCollapsed: () => void;\n defaultSelectedKeys?: string[];\n activeMode?: 'click' | 'hover';\n}\n\nexport type { IMenuProps };\n\nexport const useMenuSelect = createGlobalState([]);\nexport const useMenuActive = createGlobalState([]);\n\nexport const Context = createContext<{ activeMode: 'click' | 'hover' }>({\n activeMode: 'hover',\n});\n\nexport default function FcMenu(props: Props) {\n const { items, onClick, collapsed, switchCollapsed, defaultSelectedKeys, activeMode = 'hover' } = props;\n const [menuActive, setMenuActive] = useMenuActive();\n const [menuSelect, setMenuSelect] = useMenuSelect();\n const [inited, setInited] = useState(false);\n\n useEffect(() => {\n if (inited) {\n if (menuSelect.length > 0) {\n onClick(menuSelect[menuSelect.length - 1]);\n }\n } else {\n defaultSelectedKeys && setMenuActive(defaultSelectedKeys);\n defaultSelectedKeys && setMenuSelect(defaultSelectedKeys);\n setTimeout(() => {\n setInited(true);\n }, 0);\n }\n }, [menuSelect]);\n\n return (\n \n {\n if (activeMode === 'hover') {\n setMenuActive([]);\n }\n }}\n >\n
\n {collapsed === '2' ? (\n } placement='rightTop' overlayClassName='fc-skim-menu-tooltip'>\n switchCollapsed()} />\n \n ) : collapsed === '0' ? (\n switchCollapsed()} />\n ) : (\n switchCollapsed()} />\n )}\n
\n {collapsed !== '2' &&\n items\n .filter((item) => !!item)\n .map((item) => (isSubMenu(item) ? : item && ))}\n \n
\n );\n}\n","export interface MenuItemProps {\n key: string;\n label: string;\n icon?: React.ReactNode;\n}\n\nexport interface SubMenuProps extends MenuItemProps {\n children: MenuItemProps[];\n}\n\nexport type IMenuProps = MenuItemProps | SubMenuProps | undefined;\n\nexport const isSubMenu = (menu: IMenuProps): boolean => {\n if (menu && menu['children']) {\n return true;\n } else {\n return false;\n }\n};\n","'use strict';\nmodule.exports = str => encodeURIComponent(str).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`);\n","'use strict';\nvar token = '%[a-f0-9]{2}';\nvar singleMatcher = new RegExp(token, 'gi');\nvar multiMatcher = new RegExp('(' + token + ')+', 'gi');\n\nfunction decodeComponents(components, split) {\n\ttry {\n\t\t// Try to decode the entire string first\n\t\treturn decodeURIComponent(components.join(''));\n\t} catch (err) {\n\t\t// Do nothing\n\t}\n\n\tif (components.length === 1) {\n\t\treturn components;\n\t}\n\n\tsplit = split || 1;\n\n\t// Split the array in 2 parts\n\tvar left = components.slice(0, split);\n\tvar right = components.slice(split);\n\n\treturn Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));\n}\n\nfunction decode(input) {\n\ttry {\n\t\treturn decodeURIComponent(input);\n\t} catch (err) {\n\t\tvar tokens = input.match(singleMatcher);\n\n\t\tfor (var i = 1; i < tokens.length; i++) {\n\t\t\tinput = decodeComponents(tokens, i).join('');\n\n\t\t\ttokens = input.match(singleMatcher);\n\t\t}\n\n\t\treturn input;\n\t}\n}\n\nfunction customDecodeURIComponent(input) {\n\t// Keep track of all the replacements and prefill the map with the `BOM`\n\tvar replaceMap = {\n\t\t'%FE%FF': '\\uFFFD\\uFFFD',\n\t\t'%FF%FE': '\\uFFFD\\uFFFD'\n\t};\n\n\tvar match = multiMatcher.exec(input);\n\twhile (match) {\n\t\ttry {\n\t\t\t// Decode as big chunks as possible\n\t\t\treplaceMap[match[0]] = decodeURIComponent(match[0]);\n\t\t} catch (err) {\n\t\t\tvar result = decode(match[0]);\n\n\t\t\tif (result !== match[0]) {\n\t\t\t\treplaceMap[match[0]] = result;\n\t\t\t}\n\t\t}\n\n\t\tmatch = multiMatcher.exec(input);\n\t}\n\n\t// Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else\n\treplaceMap['%C2'] = '\\uFFFD';\n\n\tvar entries = Object.keys(replaceMap);\n\n\tfor (var i = 0; i < entries.length; i++) {\n\t\t// Replace all decoded components\n\t\tvar key = entries[i];\n\t\tinput = input.replace(new RegExp(key, 'g'), replaceMap[key]);\n\t}\n\n\treturn input;\n}\n\nmodule.exports = function (encodedURI) {\n\tif (typeof encodedURI !== 'string') {\n\t\tthrow new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');\n\t}\n\n\ttry {\n\t\tencodedURI = encodedURI.replace(/\\+/g, ' ');\n\n\t\t// Try the built in decoder first\n\t\treturn decodeURIComponent(encodedURI);\n\t} catch (err) {\n\t\t// Fallback to a more advanced decoder\n\t\treturn customDecodeURIComponent(encodedURI);\n\t}\n};\n","'use strict';\n\nmodule.exports = (string, separator) => {\n\tif (!(typeof string === 'string' && typeof separator === 'string')) {\n\t\tthrow new TypeError('Expected the arguments to be of type `string`');\n\t}\n\n\tif (separator === '') {\n\t\treturn [string];\n\t}\n\n\tconst separatorIndex = string.indexOf(separator);\n\n\tif (separatorIndex === -1) {\n\t\treturn [string];\n\t}\n\n\treturn [\n\t\tstring.slice(0, separatorIndex),\n\t\tstring.slice(separatorIndex + separator.length)\n\t];\n};\n","'use strict';\nmodule.exports = function (obj, predicate) {\n\tvar ret = {};\n\tvar keys = Object.keys(obj);\n\tvar isArr = Array.isArray(predicate);\n\n\tfor (var i = 0; i < keys.length; i++) {\n\t\tvar key = keys[i];\n\t\tvar val = obj[key];\n\n\t\tif (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) {\n\t\t\tret[key] = val;\n\t\t}\n\t}\n\n\treturn ret;\n};\n","'use strict';\nconst strictUriEncode = require('strict-uri-encode');\nconst decodeComponent = require('decode-uri-component');\nconst splitOnFirst = require('split-on-first');\nconst filterObject = require('filter-obj');\n\nconst isNullOrUndefined = value => value === null || value === undefined;\n\nconst encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier');\n\nfunction encoderForArrayFormat(options) {\n\tswitch (options.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn key => (result, value) => {\n\t\t\t\tconst index = result.length;\n\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, [encode(key, options), '[', index, ']'].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [\n\t\t\t\t\t...result,\n\t\t\t\t\t[encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join('')\n\t\t\t\t];\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, [encode(key, options), '[]'].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [...result, [encode(key, options), '[]=', encode(value, options)].join('')];\n\t\t\t};\n\n\t\tcase 'comma':\n\t\tcase 'separator':\n\t\tcase 'bracket-separator': {\n\t\t\tconst keyValueSep = options.arrayFormat === 'bracket-separator' ?\n\t\t\t\t'[]=' :\n\t\t\t\t'=';\n\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\t// Translate null to an empty string so that it doesn't serialize as 'null'\n\t\t\t\tvalue = value === null ? '' : value;\n\n\t\t\t\tif (result.length === 0) {\n\t\t\t\t\treturn [[encode(key, options), keyValueSep, encode(value, options)].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [[result, encode(value, options)].join(options.arrayFormatSeparator)];\n\t\t\t};\n\t\t}\n\n\t\tdefault:\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, encode(key, options)];\n\t\t\t\t}\n\n\t\t\t\treturn [...result, [encode(key, options), '=', encode(value, options)].join('')];\n\t\t\t};\n\t}\n}\n\nfunction parserForArrayFormat(options) {\n\tlet result;\n\n\tswitch (options.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tresult = /\\[(\\d*)\\]$/.exec(key);\n\n\t\t\t\tkey = key.replace(/\\[\\d*\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = {};\n\t\t\t\t}\n\n\t\t\t\taccumulator[key][result[1]] = value;\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tresult = /(\\[\\])$/.exec(key);\n\t\t\t\tkey = key.replace(/\\[\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = [value];\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\n\t\tcase 'comma':\n\t\tcase 'separator':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tconst isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);\n\t\t\t\tconst isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator));\n\t\t\t\tvalue = isEncodedArray ? decode(value, options) : value;\n\t\t\t\tconst newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : value === null ? value : decode(value, options);\n\t\t\t\taccumulator[key] = newValue;\n\t\t\t};\n\n\t\tcase 'bracket-separator':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tconst isArray = /(\\[\\])$/.test(key);\n\t\t\t\tkey = key.replace(/\\[\\]$/, '');\n\n\t\t\t\tif (!isArray) {\n\t\t\t\t\taccumulator[key] = value ? decode(value, options) : value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst arrayValue = value === null ?\n\t\t\t\t\t[] :\n\t\t\t\t\tvalue.split(options.arrayFormatSeparator).map(item => decode(item, options));\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = arrayValue;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], arrayValue);\n\t\t\t};\n\n\t\tdefault:\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\t}\n}\n\nfunction validateArrayFormatSeparator(value) {\n\tif (typeof value !== 'string' || value.length !== 1) {\n\t\tthrow new TypeError('arrayFormatSeparator must be single character string');\n\t}\n}\n\nfunction encode(value, options) {\n\tif (options.encode) {\n\t\treturn options.strict ? strictUriEncode(value) : encodeURIComponent(value);\n\t}\n\n\treturn value;\n}\n\nfunction decode(value, options) {\n\tif (options.decode) {\n\t\treturn decodeComponent(value);\n\t}\n\n\treturn value;\n}\n\nfunction keysSorter(input) {\n\tif (Array.isArray(input)) {\n\t\treturn input.sort();\n\t}\n\n\tif (typeof input === 'object') {\n\t\treturn keysSorter(Object.keys(input))\n\t\t\t.sort((a, b) => Number(a) - Number(b))\n\t\t\t.map(key => input[key]);\n\t}\n\n\treturn input;\n}\n\nfunction removeHash(input) {\n\tconst hashStart = input.indexOf('#');\n\tif (hashStart !== -1) {\n\t\tinput = input.slice(0, hashStart);\n\t}\n\n\treturn input;\n}\n\nfunction getHash(url) {\n\tlet hash = '';\n\tconst hashStart = url.indexOf('#');\n\tif (hashStart !== -1) {\n\t\thash = url.slice(hashStart);\n\t}\n\n\treturn hash;\n}\n\nfunction extract(input) {\n\tinput = removeHash(input);\n\tconst queryStart = input.indexOf('?');\n\tif (queryStart === -1) {\n\t\treturn '';\n\t}\n\n\treturn input.slice(queryStart + 1);\n}\n\nfunction parseValue(value, options) {\n\tif (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) {\n\t\tvalue = Number(value);\n\t} else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {\n\t\tvalue = value.toLowerCase() === 'true';\n\t}\n\n\treturn value;\n}\n\nfunction parse(query, options) {\n\toptions = Object.assign({\n\t\tdecode: true,\n\t\tsort: true,\n\t\tarrayFormat: 'none',\n\t\tarrayFormatSeparator: ',',\n\t\tparseNumbers: false,\n\t\tparseBooleans: false\n\t}, options);\n\n\tvalidateArrayFormatSeparator(options.arrayFormatSeparator);\n\n\tconst formatter = parserForArrayFormat(options);\n\n\t// Create an object with no prototype\n\tconst ret = Object.create(null);\n\n\tif (typeof query !== 'string') {\n\t\treturn ret;\n\t}\n\n\tquery = query.trim().replace(/^[?#&]/, '');\n\n\tif (!query) {\n\t\treturn ret;\n\t}\n\n\tfor (const param of query.split('&')) {\n\t\tif (param === '') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet [key, value] = splitOnFirst(options.decode ? param.replace(/\\+/g, ' ') : param, '=');\n\n\t\t// Missing `=` should be `null`:\n\t\t// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters\n\t\tvalue = value === undefined ? null : ['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options);\n\t\tformatter(decode(key, options), value, ret);\n\t}\n\n\tfor (const key of Object.keys(ret)) {\n\t\tconst value = ret[key];\n\t\tif (typeof value === 'object' && value !== null) {\n\t\t\tfor (const k of Object.keys(value)) {\n\t\t\t\tvalue[k] = parseValue(value[k], options);\n\t\t\t}\n\t\t} else {\n\t\t\tret[key] = parseValue(value, options);\n\t\t}\n\t}\n\n\tif (options.sort === false) {\n\t\treturn ret;\n\t}\n\n\treturn (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => {\n\t\tconst value = ret[key];\n\t\tif (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) {\n\t\t\t// Sort object keys, not values\n\t\t\tresult[key] = keysSorter(value);\n\t\t} else {\n\t\t\tresult[key] = value;\n\t\t}\n\n\t\treturn result;\n\t}, Object.create(null));\n}\n\nexports.extract = extract;\nexports.parse = parse;\n\nexports.stringify = (object, options) => {\n\tif (!object) {\n\t\treturn '';\n\t}\n\n\toptions = Object.assign({\n\t\tencode: true,\n\t\tstrict: true,\n\t\tarrayFormat: 'none',\n\t\tarrayFormatSeparator: ','\n\t}, options);\n\n\tvalidateArrayFormatSeparator(options.arrayFormatSeparator);\n\n\tconst shouldFilter = key => (\n\t\t(options.skipNull && isNullOrUndefined(object[key])) ||\n\t\t(options.skipEmptyString && object[key] === '')\n\t);\n\n\tconst formatter = encoderForArrayFormat(options);\n\n\tconst objectCopy = {};\n\n\tfor (const key of Object.keys(object)) {\n\t\tif (!shouldFilter(key)) {\n\t\t\tobjectCopy[key] = object[key];\n\t\t}\n\t}\n\n\tconst keys = Object.keys(objectCopy);\n\n\tif (options.sort !== false) {\n\t\tkeys.sort(options.sort);\n\t}\n\n\treturn keys.map(key => {\n\t\tconst value = object[key];\n\n\t\tif (value === undefined) {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (value === null) {\n\t\t\treturn encode(key, options);\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length === 0 && options.arrayFormat === 'bracket-separator') {\n\t\t\t\treturn encode(key, options) + '[]';\n\t\t\t}\n\n\t\t\treturn value\n\t\t\t\t.reduce(formatter(key), [])\n\t\t\t\t.join('&');\n\t\t}\n\n\t\treturn encode(key, options) + '=' + encode(value, options);\n\t}).filter(x => x.length > 0).join('&');\n};\n\nexports.parseUrl = (url, options) => {\n\toptions = Object.assign({\n\t\tdecode: true\n\t}, options);\n\n\tconst [url_, hash] = splitOnFirst(url, '#');\n\n\treturn Object.assign(\n\t\t{\n\t\t\turl: url_.split('?')[0] || '',\n\t\t\tquery: parse(extract(url), options)\n\t\t},\n\t\toptions && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {}\n\t);\n};\n\nexports.stringifyUrl = (object, options) => {\n\toptions = Object.assign({\n\t\tencode: true,\n\t\tstrict: true,\n\t\t[encodeFragmentIdentifier]: true\n\t}, options);\n\n\tconst url = removeHash(object.url).split('?')[0] || '';\n\tconst queryFromUrl = exports.extract(object.url);\n\tconst parsedQueryFromUrl = exports.parse(queryFromUrl, {sort: false});\n\n\tconst query = Object.assign(parsedQueryFromUrl, object.query);\n\tlet queryString = exports.stringify(query, options);\n\tif (queryString) {\n\t\tqueryString = `?${queryString}`;\n\t}\n\n\tlet hash = getHash(object.url);\n\tif (object.fragmentIdentifier) {\n\t\thash = `#${options[encodeFragmentIdentifier] ? encode(object.fragmentIdentifier, options) : object.fragmentIdentifier}`;\n\t}\n\n\treturn `${url}${queryString}${hash}`;\n};\n\nexports.pick = (input, filter, options) => {\n\toptions = Object.assign({\n\t\tparseFragmentIdentifier: true,\n\t\t[encodeFragmentIdentifier]: false\n\t}, options);\n\n\tconst {url, query, fragmentIdentifier} = exports.parseUrl(input, options);\n\treturn exports.stringifyUrl({\n\t\turl,\n\t\tquery: filterObject(query, filter),\n\t\tfragmentIdentifier\n\t}, options);\n};\n\nexports.exclude = (input, filter, options) => {\n\tconst exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value);\n\n\treturn exports.pick(input, exclusionFilter, options);\n};\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport { message } from 'antd';\nimport React, { ReactNode, Component } from 'react';\nimport { IStore } from '@/store/common';\nimport { useLocation } from 'react-router-dom';\n\nexport const isPromise = (obj) => {\n return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';\n};\n\nexport const download = function (stringList: Array | string, name: string = 'download.txt') {\n const element = document.createElement('a');\n const file = new Blob([Array.isArray(stringList) ? stringList.join('\\r\\n') : stringList], { type: 'text/plain' });\n element.href = URL.createObjectURL(file);\n element.download = name;\n document.body.appendChild(element);\n element.click();\n};\n\n/**\n * 将文本添加到剪贴板\n */\nexport const copyToClipBoard = (text: string, t, spliter?: string): boolean => {\n const fakeElem = document.createElement('textarea');\n fakeElem.style.border = '0';\n fakeElem.style.padding = '0';\n fakeElem.style.margin = '0';\n fakeElem.style.position = 'absolute';\n fakeElem.style.left = '-9999px';\n const yPosition = window.pageYOffset || document.documentElement.scrollTop;\n fakeElem.style.top = `${yPosition}px`;\n fakeElem.setAttribute('readonly', '');\n fakeElem.value = text;\n\n document.body.appendChild(fakeElem);\n fakeElem.select();\n let succeeded;\n try {\n succeeded = document.execCommand('copy');\n if (spliter && text.includes(spliter)) {\n message.success(`${t('复制')}${text.split('\\n').length}${t('条数据到剪贴板')}`);\n } else {\n message.success(t('复制到剪贴板'));\n }\n } catch (err) {\n message.error(t('复制失败'));\n succeeded = false;\n }\n if (succeeded) {\n document.body.removeChild(fakeElem);\n }\n return succeeded;\n};\n\nexport const copy2ClipBoard = (text: string, silent = false): boolean => {\n const fakeElem = document.createElement('textarea');\n fakeElem.style.border = '0';\n fakeElem.style.padding = '0';\n fakeElem.style.margin = '0';\n fakeElem.style.position = 'absolute';\n fakeElem.style.left = '-9999px';\n const yPosition = window.pageYOffset || document.documentElement.scrollTop;\n fakeElem.style.top = `${yPosition}px`;\n fakeElem.setAttribute('readonly', '');\n fakeElem.value = text;\n\n document.body.appendChild(fakeElem);\n fakeElem.select();\n let succeeded;\n try {\n succeeded = document.execCommand('copy');\n !silent && message.success('复制到剪贴板');\n } catch (err) {\n message.error('复制失败');\n succeeded = false;\n }\n if (succeeded) {\n document.body.removeChild(fakeElem);\n }\n return succeeded;\n};\n\nexport function formatTrim(s: string) {\n out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {\n switch (s[i]) {\n case '.':\n i0 = i1 = i;\n break;\n\n case '0':\n if (i0 === 0) i0 = i;\n i1 = i;\n break;\n\n default:\n if (i0 > 0) {\n if (!+s[i]) break out;\n i0 = 0;\n }\n break;\n }\n }\n return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;\n}\ninterface Route {\n path: string;\n component: JSX.Element | Component;\n}\nexport interface Entry {\n menu?: {\n weight?: number;\n content: ReactNode;\n };\n routes: Route[];\n module?: IStore;\n}\n\nexport const dynamicPackages = (): Entry[] => {\n const Packages = import.meta.globEager('../Packages/*/entry.tsx');\n return Object.values(Packages).map((obj) => obj.default);\n};\n\nexport const generateID = (): string => {\n return `_${Math.random().toString(36).substr(2, 9)}`;\n};\n\n// https://github.com/n9e/fe-v5/issues/72 修改 withByte 默认为 false\nexport const sizeFormatter = (\n val,\n fixedCount = 2,\n { withUnit = true, withByte = false, trimZero = false, convertNum = 1024 } = {\n withUnit: true,\n withByte: false,\n trimZero: false,\n convertNum: 1024 | 1000,\n },\n) => {\n const size = val ? Number(val) : 0;\n let result;\n let unit = '';\n\n if (size < 0) {\n result = 0;\n } else if (size < convertNum) {\n result = size.toFixed(fixedCount);\n } else if (size < convertNum * convertNum) {\n result = (size / convertNum).toFixed(fixedCount);\n unit = 'K';\n } else if (size < convertNum * convertNum * convertNum) {\n result = (size / convertNum / convertNum).toFixed(fixedCount);\n unit = 'M';\n } else if (size < convertNum * convertNum * convertNum * convertNum) {\n result = (size / convertNum / convertNum / convertNum).toFixed(fixedCount);\n unit = 'G';\n } else if (size < convertNum * convertNum * convertNum * convertNum * convertNum) {\n result = (size / convertNum / convertNum / convertNum / convertNum).toFixed(fixedCount);\n unit = 'T';\n }\n\n trimZero && (result = parseFloat(result));\n withUnit && (result = `${result}${unit}`);\n withByte && (result = `${result}B`);\n return result;\n};\n\nexport function useQuery() {\n const { search } = useLocation();\n return React.useMemo(() => new URLSearchParams(search), [search]);\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport { CommonStoreState } from './commonInterface';\nimport { resourceStoreState } from './businessInterface';\nimport { eventStoreState } from './eventInterface';\nimport { warningStoreState } from './warningInterface';\nimport { IshieldState } from '@/store/warningInterface/shield';\n\nexport type RootState = {\n common: CommonStoreState;\n resource: resourceStoreState;\n strategy: warningStoreState;\n event: eventStoreState;\n shield: IshieldState;\n};\n\nexport interface IContextPayload {\n dispatch: any;\n data: T;\n}\n\nexport interface IContext {\n payload: IContextPayload;\n ref?: React.MutableRefObject;\n open: () => void;\n close: () => void;\n innerContext?: C;\n setInnerContext?: React.Dispatch>;\n}\n\ntype disposer = (() => unknown) | null;\nexport interface IContextWrapperComponent {\n renderContent: (context: IContext) => React.ReactNode;\n renderTrigger: (context: IContext) => React.ReactNode;\n onConfirm: (context: IContext) => Promise;\n onMounted?: (context: IContext) => disposer;\n beforeClose?: (context: IContext) => Promise;\n renderFooter?: (context: IContext) => React.ReactNode;\n payload: IContextPayload;\n}\n\nexport interface IStore {\n namespace: string;\n state: S;\n reducers: R;\n effects: E;\n}\n\nexport enum RequestMethod {\n Get = 'Get',\n Post = 'Post',\n Put = 'Put',\n Delete = 'Delete',\n}\n\nexport type basePagingData = {\n list: [T];\n total: number;\n};\n\nexport type baseFePagingData = [T];\n\nexport type basePagingReq = {\n success: boolean;\n dat: baseFePagingData;\n err: string;\n};\n\nexport type baseFePagingReq = {\n success: boolean;\n dat: baseFePagingData;\n err: string;\n};\n\nexport interface IBasePagingParams {\n limit: number;\n p: number;\n}\n\nexport enum favoriteType {\n Add,\n Delete,\n}\n\nexport enum favoriteFrom {\n Favorite,\n Common,\n}\n\nexport type favoriteGroup = {\n favorite: Array;\n common: Array;\n commonTotal: number;\n currentPage: number;\n};\n\nexport type baseFavoriteItem = {\n id: number;\n isFavorite: boolean;\n create_at: number;\n create_by: number;\n update_at: number;\n update_by: number;\n isBelongIn: favoriteFrom;\n};\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport request from '@/utils/request';\nimport { RequestMethod } from '@/store/common';\n\n// 登录\nexport const Login = function (username: string, password: string) {\n return request(`/api/n9e/auth/login`, {\n method: RequestMethod.Post,\n data: { username, password },\n });\n};\n\n// 刷新accessToken\nexport const UpdateAccessToken = function () {\n return request(`/api/n9e/auth/refresh`, {\n method: RequestMethod.Post,\n data: {\n refresh_token: localStorage.getItem('refresh_token'),\n },\n });\n};\n\n// 更改密码\nexport const UpdatePwd = function (oldpass: string, newpass: string) {\n return request(`/api/n9e/self/password`, {\n method: RequestMethod.Put,\n data: { oldpass, newpass },\n });\n};\n\n// 获取csrf token\nexport const GenCsrfToken = function () {\n return request(`/api/n9e/csrf`, {\n method: RequestMethod.Get,\n });\n};\n\n// 退出\nexport const Logout = function () {\n return request(`/api/n9e/auth/logout`, {\n method: RequestMethod.Post,\n });\n};\n\nexport const getRedirectURL = function () {\n return request('/api/n9e/auth/redirect', {\n method: RequestMethod.Get,\n });\n};\n\nexport const authCallback = function (params) {\n return request('/api/n9e/auth/callback', {\n method: RequestMethod.Get,\n params,\n });\n};\n\nexport const getRedirectURLCAS = function () {\n return request('/api/n9e/auth/redirect/cas', {\n method: RequestMethod.Get,\n });\n};\n\nexport const authCallbackCAS = function (params) {\n return request('/api/n9e/auth/callback/cas', {\n method: RequestMethod.Get,\n params,\n });\n};\n\nexport const getRedirectURLOAuth = function () {\n return request('/api/n9e/auth/redirect/oauth', {\n method: RequestMethod.Get,\n });\n};\n\nexport const authCallbackOAuth = function (params) {\n return request('/api/n9e/auth/callback/oauth', {\n method: RequestMethod.Get,\n params,\n });\n};\n\nexport const getSsoConfig = function () {\n return request('/api/n9e/auth/sso-config', {\n method: RequestMethod.Get,\n });\n};\n","/** Request 网络请求工具 更详细的 api 文档\b: https://github.com/umijs/umi-request */\nimport { extend } from 'umi-request';\nimport { notification } from 'antd';\nimport { UpdateAccessToken } from '@/services/login';\n\n/** 异常处理程序,所有的error都被这里处理,页面无法感知具体error */\nconst errorHandler = (error: Error): Response => {\n // 忽略 AbortError 类型的报错\n // @ts-ignore\n if (!(error.name === 'AbortError') && !error.silence) {\n notification.error({\n message: error.message,\n });\n }\n // @ts-ignore\n if (error.silence) {\n // TODO: 兼容 n9e,暂时认定只有开启 silence 的场景才需要传递 error 详情\n throw error;\n } else {\n throw new Error(error.message);\n }\n};\n\n/** 配置request请求时的默认参数 */\nconst request = extend({\n errorHandler, // 默认错误处理\n credentials: 'include', // 默认请求是否带上cookie\n});\n\nrequest.interceptors.request.use((url, options) => {\n let headers = {\n ...options.headers,\n };\n headers['Authorization'] = `Bearer ${localStorage.getItem('access_token') || ''}`;\n if (!headers['X-Cluster']) {\n headers['X-Cluster'] = localStorage.getItem('curCluster') || '';\n }\n headers['X-Language'] = 'zh';\n return {\n url,\n options: { ...options, headers },\n };\n});\n\n/**\n * 响应拦截\n */\nrequest.interceptors.response.use(\n async (response, options) => {\n const { status } = response;\n\n if (status === 200) {\n return response\n .clone()\n .json()\n .then((data) => {\n if (response.url.includes('/api/v1/') || response.url.includes('/api/v2') || response.url.includes('/api/n9e-plus/datasource')) {\n if (status === 200 && !data.error) {\n return { ...data, success: true };\n } else if (data.error) {\n if (response.url.indexOf('/api/n9e/prometheus/api/v1') > -1 || response.url.indexOf('/api/v1/datasource/prometheus') > -1) {\n return data;\n } else {\n // @ts-ignore\n throw new Error(data.error.message, { cause: options.silence });\n }\n }\n } else {\n if (data.err === '' || data.status === 'success' || data.error === '') {\n if (data.data || data.dat) {\n if (data.dat && Object.prototype.toString.call(data.dat.list) === '[object Null]') {\n data.dat.list = [];\n }\n }\n return { ...data, success: true };\n } else {\n if (options.silence) {\n throw {\n name: data.err,\n message: data.err,\n silence: true,\n data,\n response,\n };\n } else {\n throw new Error(data.err);\n }\n }\n }\n });\n }\n // 屏蔽日志侧拉板接口报错\n if (status === 500 && response.url.indexOf('/api/v1/dimensions/log/aggregation') > -1) {\n return;\n }\n // 兼容异常处理\n if (status === 500 && (response.url.includes('/api/v1') || response.url.includes('/api/v2'))) {\n return response\n .clone()\n .json()\n .then((data) => {\n if (!data.error) {\n return { ...data, success: true };\n // if (data.data || data.dat) {\n // return { ...data, success: true };\n // } else {\n // return { success: true };\n // }\n } else if (data.error) {\n throw {\n name: data.error.name,\n message: data.error.message,\n silence: options.silence,\n data,\n response,\n };\n }\n });\n }\n if (status === 401) {\n if (response.url.indexOf('/api/n9e/prometheus/api/v1') > -1 || response.url.indexOf('/api/v1/datasource/prometheus') > -1) {\n return response\n .clone()\n .json()\n .then((data) => {\n throw new Error(data.err ? data.err : data);\n });\n } else if (response.url.indexOf('/api/n9e/auth/refresh') > 0) {\n location.href = `/login${location.pathname != '/' ? '?redirect=' + location.pathname + location.search : ''}`;\n } else {\n localStorage.getItem('refresh_token')\n ? UpdateAccessToken().then((res) => {\n console.log('401 err', res);\n if (res.err) {\n location.href = `/login${location.pathname != '/' ? '?redirect=' + location.pathname + location.search : ''}`;\n } else {\n const { access_token, refresh_token } = res.dat;\n localStorage.setItem('access_token', access_token);\n localStorage.setItem('refresh_token', refresh_token);\n location.href = `${location.pathname}${location.search}`;\n }\n })\n : (location.href = `/login${location.pathname != '/' ? '?redirect=' + location.pathname + location.search : ''}`);\n }\n // } else if (status === 404) {\n // location.href = '/404';\n } else if (status === 403 && (response.url.includes('/api/v1') || response.url.includes('/api/v2'))) {\n return response\n .clone()\n .json()\n .then((data) => {\n location.href = '/403';\n if (data.error && data.error.message) throw new Error(data.error.message);\n });\n } else {\n const contentType = response.headers.get('content-type');\n const isPlainText = contentType?.indexOf('text/plain; charset=utf-8') !== -1;\n if (isPlainText) {\n return response\n .clone()\n .text()\n .then((data) => {\n throw new Error(data);\n });\n } else {\n return response\n .clone()\n .json()\n .then((data) => {\n // 兼容 n9e 中的 prometheus api\n if (options.silence === undefined) {\n if (response.url.indexOf('/api/n9e/prometheus/api/v1') > -1 || response.url.indexOf('/api/v1/datasource/prometheus') > -1) {\n return data;\n }\n }\n if (response.url.includes('/api/v1') || response.url.includes('/api/v2')) {\n throw {\n // TODO: 后端服务异常后可能返回的错误数据也不是一个正常的结构,后面得考虑下怎么处理\n name: data.error ? data.error.name : JSON.stringify(data),\n message: data.error ? data.error.message : JSON.stringify(data),\n silence: options.silence,\n data,\n response,\n };\n } else {\n throw new Error(data.err ? data.err : data);\n }\n });\n }\n }\n },\n {\n global: false,\n },\n);\n\nexport default request;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport _ from 'lodash';\nimport request from '@/utils/request';\nimport { RequestMethod } from '@/store/common';\n\n// 获取集群信息\nexport function getCommonClusters() {\n if (import.meta.env.VITE_IS_COMMON_DS === 'true') {\n let url = '/api/v1/datasource/list';\n if (import.meta.env.VITE_IS_DS_SETTING === 'true') {\n url = '/api/n9e-plus/datasource/list';\n }\n return request(url, {\n method: RequestMethod.Post,\n data: {\n category: 'timeseries',\n plugin_type: 'prometheus',\n p: 1,\n limit: 100,\n },\n }).then((res) => {\n return {\n dat: _.map(\n _.filter(res.data.items, (item) => {\n return item.plugin_type === 'prometheus';\n }),\n 'name',\n ),\n };\n });\n }\n return request(`/api/n9e/clusters`, {\n method: RequestMethod.Get,\n });\n}\n\n// 获取es集群信息\nexport function getCommonESClusters() {\n if (import.meta.env.VITE_IS_COMMON_DS === 'true') {\n let url = '/api/v1/datasource/timeseries/elasticsearch/list';\n if (import.meta.env.VITE_IS_DS_SETTING === 'true') {\n url = '/api/n9e-plus/datasource/list';\n }\n return request(url, {\n method: RequestMethod.Post,\n data: {\n p: 1,\n limit: 100,\n category: 'logging',\n },\n }).then((res) => {\n return {\n dat: _.map(res.data.items, 'name'),\n };\n });\n }\n // TODO: n9e 暂时没有 es 集群接口\n return request(`/api/n9e/clusters`, {\n method: RequestMethod.Get,\n });\n}\n\n// 获取 sls 集群信息\nexport function getCommonSLSClusters() {\n if (import.meta.env.VITE_IS_COMMON_DS === 'true') {\n let url = '/api/v1/datasource/list';\n if (import.meta.env.VITE_IS_DS_SETTING === 'true') {\n url = '/api/n9e-plus/datasource/list';\n }\n return request(url, {\n method: RequestMethod.Post,\n data: {\n p: 1,\n limit: 100,\n category: 'logging',\n plugin_type: 'aliyun-sls.logging',\n },\n }).then((res) => {\n return {\n dat: _.map(res.data.items, 'name'),\n };\n });\n }\n return Promise.resolve({\n dat: [],\n });\n}\n\nexport function getBusiGroups(query: string, limit: number = 200) {\n return request(`/api/n9e/busi-groups`, {\n method: RequestMethod.Get,\n params: Object.assign(\n {\n limit,\n },\n query ? { query } : {},\n ),\n });\n}\n\nexport function getPerm(busiGroup: string, perm: 'ro' | 'rw') {\n return request(`/api/n9e/busi-group/${busiGroup}/perm/${perm}`, {\n method: RequestMethod.Get,\n });\n}\n\nexport function getMenuPerm() {\n return request(`/api/n9e/self/perms`, {\n method: RequestMethod.Get,\n });\n}\n\nexport function getDatasourceNames(ids: number[]) {\n if (import.meta.env.VITE_IS_COMMON_DS === 'true') {\n let url = '/api/v1/datasource/name/list';\n if (import.meta.env.VITE_IS_DS_SETTING === 'true') {\n // n9e暂时不用该接口\n // url = '/api/n9e-plus/datasource/name/list';\n return Promise.resolve({\n data: [],\n });\n }\n return request(url, {\n method: RequestMethod.Post,\n data: { ids },\n }).then((res) => res.data);\n }\n\n return Promise.resolve({\n data: [],\n });\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport { createFromIconfontCN } from '@ant-design/icons';\nimport { useTranslation } from 'react-i18next';\nconst IconFont = createFromIconfontCN({\n scriptUrl: '/font/iconfont.js',\n}); // console.log('{process.env.PUBLIC_URL}=', process.env.PUBLIC_URL)\n\nexport default IconFont;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport FcMenu, { IMenuProps } from '@fc-components/menu';\nimport React, { FC, useState, useEffect } from 'react';\nimport { useHistory, useLocation } from 'react-router-dom';\nimport { useSelector } from 'react-redux';\nimport { Menu, Button } from 'antd';\nimport Icon, { AimOutlined, AlertOutlined, LineChartOutlined, CodeOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport { useTranslation } from 'react-i18next';\nimport querystring from 'query-string';\nimport { dynamicPackages, Entry } from '@/utils';\nimport { getMenuPerm } from '@/services/common';\nimport { RootState as AccountRootState, accountStoreState } from '@/store/accountInterface';\nimport IconFont from '../IconFont';\nimport './menu.less';\n\nconst { SubMenu } = Menu;\nconst Packages = dynamicPackages();\nlet lazyMenu = Packages.reduce((result: any, module: Entry) => {\n const menu = module.menu;\n return menu ? (result = result.concat(menu)) : result;\n}, []);\nconst getDefaultOpenKey = (menus: any, pathname) => {\n const currentSubMenu = _.find(menus, (subMenus: any) => {\n return _.some(\n subMenus.children.filter((i) => !!i),\n (menu) => {\n return pathname.indexOf(menu.key) !== -1;\n },\n );\n });\n if (currentSubMenu) {\n return currentSubMenu.key;\n }\n};\nconst defaultSelectedKey = (menus: any, pathname) => {\n let key;\n _.forEach(menus, (subMenus: any) => {\n _.forEach(subMenus.children, (menu: any) => {\n if (menu && pathname.indexOf(menu.key) !== -1) {\n key = menu.key;\n }\n });\n });\n return key;\n};\n\nconst SideMenu: FC = () => {\n const { t, i18n } = useTranslation();\n const [defaultSelectedKeys, setDefaultSelectedKeys] = useState();\n const menuList = [\n {\n key: 'targets',\n icon: ,\n label: t('监控对象'),\n children: [\n {\n key: '/targets',\n label: t('对象列表'),\n },\n ],\n },\n {\n key: 'monitor',\n icon: ,\n label: t('监控看图'),\n children: [\n {\n key: '/metric/explorer',\n label: t('即时查询'),\n },\n {\n key: '/object/explorer',\n label: t('快捷视图'),\n },\n {\n key: '/dashboards',\n label: t('监控大盘'),\n },\n ],\n },\n {\n key: 'alarm',\n icon: ,\n label: t('告警管理'),\n children: [\n {\n key: '/alert-rules',\n label: t('告警规则'),\n },\n {\n key: '/recording-rules',\n label: t('记录规则'),\n },\n {\n key: '/alert-mutes',\n label: t('屏蔽规则'),\n },\n {\n key: '/alert-subscribes',\n label: t('订阅规则'),\n },\n {\n key: '/alert-cur-events',\n label: t('活跃告警'),\n },\n {\n key: '/alert-his-events',\n label: t('历史告警'),\n },\n ],\n },\n {\n key: 'job',\n icon: ,\n label: t('告警自愈'),\n children: [\n {\n key: '/job-tpls',\n label: t('自愈脚本'),\n },\n {\n key: '/job-tasks',\n label: t('执行历史'),\n },\n ],\n },\n {\n key: 'manage',\n // icon: ,\n icon: ,\n label: t('人员组织'),\n children: [\n {\n key: '/users',\n label: t('用户管理'),\n },\n {\n key: '/user-groups',\n label: t('团队管理'),\n },\n {\n key: '/busi-groups',\n label: t('业务组管理'),\n },\n ],\n },\n {\n key: 'help',\n // icon: ,\n icon: ,\n label: t('系统信息'),\n children: [\n {\n key: '/help/version',\n label: t('系统版本'),\n },\n // {\n // key: '/help/contact',\n // label:t('联系我们'),\n // },\n {\n key: '/help/migrate',\n label: t('管理员迁移'),\n },\n {\n key: '/help/servers',\n label: t('告警引擎'),\n },\n ...[\n import.meta.env.VITE_IS_DS_SETTING\n ? {\n key: '/help/source',\n label: t('数据源管理'),\n }\n : undefined,\n ],\n ],\n },\n ];\n\n const [menus, setMenus] = useState(menuList);\n\n useEffect(() => {\n setDefaultSelectedKeys([]);\n for (const item of menuList) {\n if (item && item.key.startsWith('/') && window.location.pathname.includes(item.key)) {\n setDefaultSelectedKeys([item?.key]);\n break;\n } else if (item?.children && item.children.length > 0) {\n for (const i of item.children) {\n if (i && window.location.pathname.includes(i.key!)) {\n setDefaultSelectedKeys([item?.key, i.key!]);\n break;\n }\n }\n }\n }\n }, []);\n\n const history = useHistory();\n const location = useLocation();\n const { pathname } = location;\n let { profile } = useSelector((state) => state.account);\n const [collapsed, setCollapsed] = useState<'0' | '1' | '2' | string | null>(localStorage.getItem('menuCollapsed'));\n // full => '0'\n // semi => '1'\n // skim => '2'\n const [selectedKeys, setSelectedKeys] = useState([defaultSelectedKey(menus, pathname)]);\n const [openKeys, setOpenKeys] = useState(collapsed ? [] : [getDefaultOpenKey(menus, pathname)]);\n\n const switchCollapsed = () => {\n if (!isNaN(Number(collapsed))) {\n const newColl = (Number(collapsed) === 2 ? -1 : Number(collapsed)) + 1 + '';\n setCollapsed(newColl);\n localStorage.setItem('menuCollapsed', newColl);\n } else {\n setCollapsed('1');\n localStorage.setItem('menuCollapsed', '1');\n }\n setTimeout(() => {\n window.dispatchEvent(new Event('resize'));\n }, 500);\n };\n const handleClick = (key) => {\n if (location.pathname === key) return;\n setSelectedKeys([key as string]);\n // 写两个key as string 感觉有点傻\n if (key === 'changeLanguage') {\n let language = i18n.language == 'en' ? 'zh' : 'en';\n i18n.changeLanguage(language);\n localStorage.setItem('language', language);\n }\n\n if ((key as string).startsWith('/')) {\n history.push(key as string);\n }\n };\n const hideSideMenu = () => {\n if (\n location.pathname === '/login' ||\n location.pathname.startsWith('/chart/') ||\n location.pathname.startsWith('/dashboards/share/') ||\n location.pathname === '/callback' ||\n location.pathname.indexOf('/polaris/screen') === 0\n ) {\n return true;\n }\n // 大盘全屏模式下也需要隐藏左侧菜单\n if (location.pathname.indexOf('/dashboard') === 0) {\n const query = querystring.parse(location.search);\n if (query?.viewMode === 'fullscreen') {\n return true;\n }\n return false;\n }\n return false;\n };\n\n useEffect(() => {\n setSelectedKeys([defaultSelectedKey(menus, pathname)]);\n if (!collapsed) {\n setOpenKeys(_.union([...openKeys, getDefaultOpenKey(menus, pathname)]));\n }\n }, [pathname, collapsed]);\n\n useEffect(() => {\n if (profile.roles.length > 0) {\n if (profile.roles.indexOf('Admin') === -1) {\n getMenuPerm().then((res) => {\n const { dat } = res;\n const newMenus = [...menuList];\n newMenus.forEach((menu) => {\n menu.children = menu.children.filter((item) => item && dat.includes(item.key));\n });\n setMenus(newMenus);\n });\n } else {\n setMenus(menuList);\n }\n }\n }, [profile.roles]);\n\n return hideSideMenu() ? null : (\n \n {collapsed !== '2' && (\n
\n
history.push('/metric/explorer')} key='overview'>\n \n
\n
\n )}\n {defaultSelectedKeys && (\n \n )}\n \n );\n};\n\nexport default SideMenu;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport { Button, Result } from 'antd';\nimport React from 'react';\nimport { useHistory } from 'react-router';\n\nconst NotFound: React.FC = () => {\n const history = useHistory();\n return (\n
\n history.replace('/')}>\n 回到首页\n \n }\n />\n
\n );\n};\n\nexport default NotFound;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport { Button, Result } from 'antd';\nimport React from 'react';\nimport { useHistory } from 'react-router';\n\nconst NotFound: React.FC = () => {\n const history = useHistory();\n return (\n
\n history.go(-2)}>\n 返回上一页\n \n }\n />\n
\n );\n};\n\nexport default NotFound;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useState, useEffect } from 'react';\nimport { Form, Input, Button, Radio, message } from 'antd';\nimport { useHistory, useLocation } from 'react-router-dom';\nimport { useDispatch } from 'react-redux';\nimport { UserOutlined, LockOutlined } from '@ant-design/icons';\nimport { getSsoConfig, getRedirectURL, getRedirectURLCAS, getRedirectURLOAuth } from '@/services/login';\nimport './login.less';\n\nimport { useTranslation } from 'react-i18next';\nexport interface DisplayName {\n oidc: string;\n cas: string;\n oauth: string;\n}\nexport default function Login() {\n const { t } = useTranslation();\n const [form] = Form.useForm();\n const history = useHistory();\n const location = useLocation();\n const redirect = location.search && new URLSearchParams(location.search).get('redirect');\n const dispatch = useDispatch();\n const [displayName, setDis] = useState({\n oidc: 'OIDC',\n cas: 'CAS',\n oauth: 'OAuth',\n });\n\n useEffect(() => {\n getSsoConfig().then((res) => {\n if (res.dat) {\n setDis({\n oidc: res.dat.oidcDisplayName,\n cas: res.dat.casDisplayName,\n oauth: res.dat.oauthDisplayName,\n });\n }\n });\n }, []);\n\n const handleSubmit = async () => {\n try {\n await form.validateFields();\n login();\n } catch {\n console.log(t('输入有误'));\n }\n };\n\n const login = async () => {\n let { username, password } = form.getFieldsValue();\n const err = await dispatch({\n type: 'account/login',\n username,\n password,\n });\n\n if (!err) {\n history.push(redirect || '/metric/explorer');\n }\n };\n\n return (\n
\n \n \n
\n \n
\n
\n
\n
\n \n
\n
\n \n } />\n \n \n } />\n \n\n \n \n \n
\n 其他登录方式:\n {\n getRedirectURL().then((res) => {\n if (res.dat) {\n window.location.href = res.dat;\n } else {\n message.warning('没有配置 OIDC 登录地址!');\n }\n });\n }}\n >\n {displayName.oidc}\n \n   \n {\n getRedirectURLCAS().then((res) => {\n if (res.dat) {\n window.location.href = res.dat.redirect;\n localStorage.setItem('CAS_state', res.dat.state);\n } else {\n message.warning('没有配置 CAS 登录地址!');\n }\n });\n }}\n >\n {displayName.cas}\n \n   \n {\n getRedirectURLOAuth().then((res) => {\n if (res.dat) {\n window.location.href = res.dat;\n } else {\n message.warning('没有配置 OAuth 登录地址!');\n }\n });\n }}\n >\n {displayName.oauth}\n \n
\n \n
\n
\n
\n );\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useState, useEffect, useRef } from 'react';\n\nexport default function Overview() {\n return
;\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useEffect, useState } from 'react';\nimport { useLocation } from 'react-router';\nimport queryString from 'query-string';\nimport { authCallback } from '@/services/login';\n\nexport default function index() {\n const location = useLocation();\n const query = queryString.parse(location.search);\n const [err, setErr] = useState();\n\n useEffect(() => {\n authCallback({\n code: query.code,\n state: query.state,\n redirect: query.redirect || '/',\n })\n .then((res) => {\n if (res.err === '') {\n if (res.dat && res.dat.access_token && res.dat.refresh_token) {\n localStorage.setItem('access_token', res.dat.access_token);\n localStorage.setItem('refresh_token', res.dat.refresh_token);\n window.location.href = res.dat.redirect;\n } else {\n console.log(res.dat);\n }\n } else {\n setErr(res.err);\n }\n })\n .catch((res) => {\n setErr(res.message);\n });\n }, []);\n if (err === undefined) return null;\n return (\n \n
\n

第三方登录验证失败

\n
{err}
\n \n
\n \n );\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useEffect, useState } from 'react';\nimport { useLocation } from 'react-router';\nimport queryString from 'query-string';\nimport { authCallbackCAS } from '@/services/login';\n\nexport default function index() {\n const location = useLocation();\n const query = queryString.parse(location.search);\n const [err, setErr] = useState();\n\n useEffect(() => {\n authCallbackCAS({\n ticket: query.ticket,\n state: localStorage.getItem(\"CAS_state\"),\n redirect: query.redirect || '/',\n })\n .then((res) => {\n if (res.err === '') {\n if (res.dat && res.dat.access_token && res.dat.refresh_token) {\n localStorage.setItem('access_token', res.dat.access_token);\n localStorage.setItem('refresh_token', res.dat.refresh_token);\n window.location.href = res.dat.redirect;\n localStorage.removeItem(\"CAS_state\");\n } else {\n console.log(res.dat);\n }\n } else {\n setErr(res.err);\n }\n })\n .catch((res) => {\n setErr(res.message);\n });\n }, []);\n if (err === undefined) return null;\n return (\n \n
\n

第三方登录验证失败

\n
{err}
\n \n
\n \n );\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useEffect, useState } from 'react';\nimport { useLocation } from 'react-router';\nimport queryString from 'query-string';\nimport { authCallbackOAuth } from '@/services/login';\n\nexport default function index() {\n const location = useLocation();\n const query = queryString.parse(location.search);\n const [err, setErr] = useState();\n\n useEffect(() => {\n authCallbackOAuth({\n code: query.code,\n state: query.state,\n redirect: query.redirect || '/',\n })\n .then((res) => {\n if (res.err === '') {\n if (res.dat && res.dat.access_token && res.dat.refresh_token) {\n localStorage.setItem('access_token', res.dat.access_token);\n localStorage.setItem('refresh_token', res.dat.refresh_token);\n window.location.href = res.dat.redirect;\n } else {\n console.log(res.dat);\n }\n } else {\n setErr(res.err);\n }\n })\n .catch((res) => {\n setErr(res.message);\n });\n }, []);\n if (err === undefined) return null;\n return (\n \n
\n

第三方登录验证失败

\n
{err}
\n \n
\n \n );\n}\n","import React from 'react';\nimport _ from 'lodash';\n\ninterface IProps {\n var?: string;\n children: React.ReactNode | Function;\n}\n\nexport default function index(props: IProps) {\n let vars: string[] = [];\n if (props.var) {\n if (props.var.indexOf(',') > -1) {\n vars = props.var.split(',');\n } else {\n vars = [props.var];\n }\n const result = _.some(vars, (item) => {\n return import.meta.env[item] === 'true';\n });\n if (result) {\n if (typeof props.children === 'function') {\n return
{props.children(true)}
;\n }\n return
{props.children}
;\n }\n }\n if (typeof props.children === 'function') {\n return
{props.children(false)}
;\n }\n return null;\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nexport const PAGE_SIZE = 15;\nexport const PAGE_SIZE_MAX = 100000;\nexport const PAGE_SIZE_OPTION = 20;\nexport const PAGE_SIZE_OPTION_LARGE = 150;\n\nexport const randomColor = ['pink', 'red', 'yellow', 'orange', 'cyan', 'green', 'blue', 'purple', 'geekblue', 'magenta', 'volcano', 'gold', 'lime'];\n\nexport const priorityColor = ['red', 'orange', 'blue'];\n// 主题色\nexport const chartColor = ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'];\nexport const METRICS = {\n TOTAL: 'total',\n ERROR: 'error',\n LATENCY: 'latency',\n};\n\nexport const chartDefaultOptions = {\n color: chartColor,\n xAxis: { data: [] },\n yAxis: {},\n series: [],\n tooltip: {\n show: true,\n trigger: 'axis',\n textStyle: {\n fontSize: 12,\n lineHeight: 12,\n },\n },\n grid: {\n left: '2%',\n right: '1%',\n top: '20',\n bottom: '20',\n },\n legend: {\n lineStyle: {\n width: 1,\n },\n },\n animation: false,\n};\n\nexport const normalDatasourceCates = [\n {\n value: 'prometheus',\n label: 'Prometheus',\n },\n];\n\nexport const datasourceCates = [\n ...normalDatasourceCates,\n {\n value: 'elasticsearch',\n label: 'Elasticsearch',\n },\n {\n value: 'aliyun-sls',\n label: '阿里云SLS',\n },\n];\n\nexport const datasourceCatesMap = {\n normal: normalDatasourceCates,\n all: datasourceCates,\n};\n\nexport enum DatasourceCateEnum {\n prometheus = 'prometheus',\n elasticsearch = 'elasticsearch',\n aliyunSLS = 'aliyun-sls',\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport request from '@/utils/request';\nimport { RequestMethod, IBasePagingParams } from '@/store/common';\nimport type { MetricListRes, strategyGroup, strategyStatus, TagKeysRes, TagValuesRes } from '@/store/warningInterface';\nimport { PAGE_SIZE } from '@/utils/constant';\nimport React from 'react';\nimport queryString from 'query-string';\n\n// 获得策略分组列表\nexport const getStrategyGroupList = function (query?: string, p = 1) {\n return request(`/api/n9e/alert-rule-groups`, {\n method: RequestMethod.Get,\n params: {\n query,\n p,\n limit: PAGE_SIZE,\n },\n });\n};\n\n// 添加策略分组\nexport const addStrategyGroup = function (data: strategyGroup) {\n return request(`/api/n9e/alert-rule-groups`, {\n method: RequestMethod.Post,\n data,\n });\n};\n\n// 获取策略分组\nexport const getStrategyGroup = function (id: number) {\n return request(`/api/n9e/alert-rule-group/${id}`, {\n method: RequestMethod.Get,\n });\n};\n\n// 删除策略分组\nexport const deleteStrategyGroup = function (id: number) {\n return request(`/api/n9e/alert-rule-group/${id}`, {\n method: RequestMethod.Delete,\n });\n};\n\n// 更新策略分组\nexport const updateStrategyGroup = function (data: Partial & { id: number }) {\n return request(`/api/n9e/alert-rule-group/${data.id}`, {\n method: RequestMethod.Put,\n data,\n });\n};\n\n//// 获取策略列表\nexport const getStrategyGroupSubList = function (params: { id: number }) {\n return request(`/api/n9e/busi-group/${params.id}/alert-rules`, {\n method: RequestMethod.Get,\n });\n};\n\n// 获取收藏分组\nexport const getFavoritesStrategyGroups = function () {\n return request(`/api/n9e/alert-rule-groups/favorites`, {\n method: RequestMethod.Get,\n });\n};\n\n// 添加收藏分组\nexport const addFavoriteGroup = function (id: number) {\n return request(`/api/n9e/alert-rule-group/${id}/favorites`, {\n method: RequestMethod.Post,\n data: {\n id,\n },\n });\n};\n\n// 删除收藏分组\nexport const deleteFavoriteGroup = function (id: number) {\n return request(`/api/n9e/alert-rule-group/${id}/favorites`, {\n method: RequestMethod.Delete,\n data: {\n id,\n },\n });\n};\n\nexport const getMetrics = function (params = {}) {\n return request(`/api/n9e/prometheus/api/v1/label/__name__/values`, {\n method: RequestMethod.Get,\n params,\n paramsSerializer: function (params) {\n return queryString.stringify(params, { arrayFormat: 'bracket' });\n },\n });\n};\n\nexport const getMetricsDesc = function (data = []) {\n return request(`/api/n9e/metrics/desc`, {\n method: RequestMethod.Post,\n data,\n });\n};\n\nexport const getTagKeys = function (params): Promise {\n return request(`/api/n9e/tag-keys`, {\n method: RequestMethod.Post,\n data: params,\n });\n};\n\nexport const getTagValuesByKey = function (params): Promise {\n return request(`/api/n9e/tag-values`, {\n method: RequestMethod.Post,\n data: params,\n });\n};\n\nexport const getWarningStrategy = function (id): Promise {\n return request(`/api/n9e/alert-rule/${id}`, {\n method: RequestMethod.Get,\n });\n};\n\n// export const addOrEditStrategy = function (data: object, strategyId?: string) {\n// let url = `/api/n9e/alert-rules`;\n// if (strategyId) url = `/api/n9e/alert-rule/${strategyId}`;\n// return request(url, {\n// method: strategyId ? RequestMethod.Put : RequestMethod.Post,\n// data: strategyId ? data[0] : data,\n// });\n// };\n\nexport const addOrEditStrategy = function (data: any[], busiId: number, method: string) {\n return request(`/api/n9e/busi-group/${busiId}/alert-rules`, {\n method: method,\n data: data,\n });\n};\nexport const EditStrategy = function (data: any[], busiId: number, strategyId: number) {\n return request(`/api/n9e/busi-group/${busiId}/alert-rule/${strategyId}`, {\n method: RequestMethod.Put,\n data: data,\n });\n};\n\nexport const deleteStrategy = function (ids: number[], strategyId: number) {\n return request(`/api/n9e/busi-group/${strategyId}/alert-rules`, {\n method: RequestMethod.Delete,\n data: { ids },\n });\n};\n\nexport const batchDeleteStrategy = function (ruleId, ids: Array) {\n return request(`/api/n9e/alert-rule-group/${ruleId}/alert-rules`, {\n method: RequestMethod.Delete,\n data: { ids },\n });\n};\n\nexport const prometheusQuery = function (data, cluster): Promise {\n return request(`/api/n9e/prometheus/api/v1/query`, {\n method: RequestMethod.Get,\n params: data,\n headers: {\n 'X-Cluster': cluster,\n },\n });\n};\n\n/**\n * 批量更新规则\n */\nexport const updateAlertRules = function (\n data: {\n ids: React.Key[];\n fields: any;\n action?: string;\n },\n busiId: number,\n) {\n return request(`/api/n9e/busi-group/${busiId}/alert-rules/fields`, {\n method: RequestMethod.Put,\n data: data,\n });\n};\n\n/**\n * 获取未恢复告警列表\n */\nexport function getBusiGroupsCurAlerts(ids: number[]) {\n return request(`/api/n9e/busi-groups/alertings`, {\n method: RequestMethod.Get,\n params: { ids: ids.join(',') },\n });\n}\n\nexport const getAlertEvents = function (data) {\n return request(`/api/n9e/alert-events`, {\n method: RequestMethod.Get,\n params: data,\n });\n};\n/**\n * 获取全量告警历史页面\n */\nexport const getHistoryEvents = function (data) {\n console.log(data);\n\n return request(`/api/n9e/history-alert-events`, {\n method: RequestMethod.Get,\n params: data,\n });\n};\n// 获取告警详情\nexport function getAlertEventsById(busiId, eventId) {\n return request(`/api/n9e/alert-cur-event/${eventId}`, {\n method: RequestMethod.Get,\n });\n}\n\nexport function getHistoryEventsById(busiId, eventId) {\n return request(`/api/n9e/alert-his-event/${eventId}`, {\n method: RequestMethod.Get,\n });\n}\n/**\n * 批量删除(忽略)告警历史\n */\nexport const deleteAlertEvents = function (busiId, ids: Array) {\n return request(`/api/n9e/alert-cur-events`, {\n method: RequestMethod.Delete,\n data: {\n ids,\n },\n });\n};\n\n/**\n * 批量更新告警策略状态\n */\nexport const updateAlertEventsStatus = function (ids: Array, status: strategyStatus) {\n return request(`/api/n9e/alert-rules/status`, {\n method: RequestMethod.Put,\n data: {\n ids,\n status,\n },\n });\n};\n/**\n * 批量更新告警通知接收组+接收人\n */\nexport const updateAlertEventsNotifyGroups = function (ids: Array, notify_groups: string, notify_users: string) {\n return request(`/api/n9e/alert-rules/notify-groups`, {\n method: RequestMethod.Put,\n data: {\n ids,\n notify_groups,\n notify_users,\n },\n });\n};\n/**\n * 批量更新告警通知接收人\n */\nexport const updateAlertEventsNotifyUsers = function (ids: Array, notify_users: string) {\n return request(`/api/n9e/alert-rules/notify-users`, {\n method: RequestMethod.Put,\n data: {\n ids,\n notify_users,\n },\n });\n};\n/**\n * 批量更新告警通知媒介\n */\nexport const updateAlertEventsNotifyChannels = function (ids: Array, notify_channels: string) {\n return request(`/api/n9e/alert-rules/notify-channels`, {\n method: RequestMethod.Put,\n data: {\n ids,\n notify_channels,\n },\n });\n};\n/**\n * 批量更新告警附加标签\n */\nexport const updateAlertEventsAppendTags = function (ids: Array, append_tags: string) {\n return request(`/api/n9e/alert-rules/append-tags`, {\n method: RequestMethod.Put,\n data: {\n ids,\n append_tags,\n },\n });\n};\n\nexport const getBuiltinAlerts = function () {\n return request('/api/n9e/alert-rules/builtin/list', {\n method: RequestMethod.Get,\n });\n};\n\nexport const createBuiltinAlerts = function (name: string, cluster: string, id: number) {\n return request(`/api/n9e/busi-group/${id}/alert-rules/builtin`, {\n method: RequestMethod.Post,\n data: { name, cluster },\n });\n};\n\nexport const getAggrAlerts = function () {\n return request('/api/n9e/alert-aggr-views', {\n method: RequestMethod.Get,\n });\n};\n\nexport const AddAggrAlerts = function (data) {\n return request('/api/n9e/alert-aggr-views', {\n method: RequestMethod.Post,\n data,\n });\n};\n\nexport const updateAggrAlerts = function (data) {\n return request('/api/n9e/alert-aggr-views', {\n method: RequestMethod.Put,\n data,\n });\n};\n\nexport const deleteAggrAlerts = function (ids: number[]) {\n return request('/api/n9e/alert-aggr-views', {\n method: RequestMethod.Delete,\n data: { ids },\n });\n};\n\nexport const getAlertCards = function (params) {\n return request('/api/n9e/alert-cur-events/card', {\n method: RequestMethod.Get,\n params,\n });\n};\n\nexport const getCardDetail = function (ids) {\n return request('/api/n9e/alert-cur-events/card/details', {\n method: RequestMethod.Post,\n data: { ids },\n });\n};\n\nexport const getBrainData = function (params) {\n return request('/api/fc-brain/data', {\n method: RequestMethod.Get,\n params,\n });\n};\n\nexport const getBrainParams = function () {\n return request('/api/fc-brain/params', {\n method: RequestMethod.Get,\n }).then((res) => {\n return res.data;\n });\n};\n\nexport const checkBrainPromql = function (data) {\n return request('/api/fc-brain/promql-check', {\n method: RequestMethod.Post,\n data,\n silence: true,\n }).then((res) => {\n return res.data;\n });\n};\n\nexport const getBrainJobs = function (id) {\n return request('/api/fc-brain/jobs', {\n method: RequestMethod.Get,\n params: {\n id,\n },\n }).then((res) => {\n return res.data;\n });\n};\n\nexport function getBrainLicense() {\n return request('/api/fc-brain/license', {\n method: RequestMethod.Get,\n silence: true,\n });\n}\n\nexport function getDsQuery(params) {\n return request('/api/n9e-plus/ds-query', {\n method: RequestMethod.Post,\n data: params,\n headers: {\n 'X-Cluster': 'Default',\n },\n silence: true,\n });\n}\n\nexport function getLogQuery(params) {\n return request('/api/n9e-plus/log-query', {\n method: RequestMethod.Post,\n data: params,\n headers: {\n 'X-Cluster': 'Default',\n },\n silence: true,\n });\n}\n\nexport function getIndices(params) {\n return request('/api/n9e-plus/indices', {\n method: RequestMethod.Post,\n data: params,\n headers: {\n 'X-Cluster': 'Default',\n },\n });\n}\n\nexport function getFields(params) {\n return request('/api/n9e-plus/fields', {\n method: RequestMethod.Post,\n data: params,\n headers: {\n 'X-Cluster': 'Default',\n },\n silence: true,\n });\n}\n\nexport function getEventTSQuery(params) {\n return request('/api/n9e-plus/event-ts-query', {\n method: RequestMethod.Post,\n data: params,\n });\n}\n\nexport function getEventLogQuery(params) {\n return request('/api/n9e-plus/event-log-query', {\n method: RequestMethod.Post,\n data: params,\n });\n}\n\nexport function getLogsQuery(params) {\n return request('/api/n9e-plus/logs-query', {\n method: RequestMethod.Post,\n data: params,\n });\n}\n\nexport const getAlertEventList = function (params) {\n return request('/api/n9e/alert-his-events/list', {\n method: RequestMethod.Get,\n params,\n }).then((res) => res?.dat?.list || []);\n};\n","import React, { useEffect, useState } from 'react';\nimport { Tooltip, Modal } from 'antd';\nimport _ from 'lodash';\nimport moment from 'moment';\nimport { getBrainLicense } from '@/services/warning';\n\nexport default function License() {\n const [days, setDays] = useState();\n const [rules, setRules] = useState();\n useEffect(() => {\n const now = moment().unix();\n getBrainLicense()\n .then((res) => {\n setDays(_.round((res?.data?.expire - now) / 86400));\n setRules(res?.data?.rules_remaining);\n window.localStorage.setItem('license_rules_remaining', _.toString(res?.data?.rules_remaining));\n })\n .catch((e) => {\n const modal = Modal.error({ closable: false, maskClosable: false, title: 'License证书不存在或已过期,请联系Flashcat技术支持', className: 'license-off' });\n setTimeout(() => {\n modal.destroy();\n }, 10000);\n });\n }, []);\n if (!days || days > 30) return null;\n return (\n
\n \n
还剩 {days} 天到期
\n {rules > 0 ?
还可添加 {rules} 条规则
:
请尽快联系管理员续费
}\n
\n }\n >\n \n 还剩 {days} 天到期\n \n \n \n );\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useState, ReactNode } from 'react';\nimport './index.less';\nimport { useHistory } from 'react-router-dom';\nimport { useSelector, useDispatch } from 'react-redux';\nimport Icon, { RollbackOutlined } from '@ant-design/icons';\nimport { useTranslation } from 'react-i18next';\nimport { RootState as AccountRootState, accountStoreState } from '@/store/accountInterface';\nimport { RootState as CommonRootState } from '@/store/common';\nimport { CommonStoreState } from '@/store/commonInterface';\nimport { Menu, Dropdown, Button } from 'antd';\nimport { DownOutlined } from '@ant-design/icons';\nimport { Logout } from '@/services/login';\nimport AdvancedWrap from '@/components/AdvancedWrap';\nimport License from '@/pages/warning/strategy/license';\ninterface IPageLayoutProps {\n icon?: ReactNode;\n title?: String | JSX.Element;\n children?: ReactNode;\n introIcon?: ReactNode;\n rightArea?: ReactNode;\n customArea?: ReactNode;\n showBack?: Boolean;\n backPath?: string;\n hideCluster?: Boolean;\n onChangeCluster?: (string) => void;\n docFn?: Function;\n}\n\nconst PageLayout: React.FC = ({ icon, title, rightArea, introIcon, children, customArea, showBack, backPath, onChangeCluster, hideCluster = true, docFn }) => {\n const { t, i18n } = useTranslation();\n const history = useHistory();\n const dispatch = useDispatch();\n let { profile } = useSelector((state) => state.account);\n const { clusters } = useSelector((state) => state.common);\n const localCluster = localStorage.getItem('curCluster');\n const [curCluster, setCurCluster] = useState(localCluster || clusters[0]);\n if (!localCluster && clusters.length > 0) {\n setCurCluster(clusters[0]);\n localStorage.setItem('curCluster', clusters[0]);\n dispatch({\n type: 'common/saveData',\n prop: 'curCluster',\n data: clusters[0],\n });\n }\n\n const menu = (\n \n {\n history.push('/account/profile/info');\n }}\n >\n {t('个人信息')}\n \n {\n Logout().then((res) => {\n localStorage.removeItem('access_token');\n localStorage.removeItem('refresh_token');\n dispatch({\n type: 'common/saveData',\n prop: 'clusters',\n data: [],\n });\n dispatch({\n type: 'common/saveData',\n prop: 'busiGroups',\n data: [],\n });\n history.push('/login');\n });\n }}\n >\n {t('退出')}\n \n \n );\n\n const clusterMenu = (\n \n {clusters.map((cluster) => (\n {\n setCurCluster(cluster);\n onChangeCluster && onChangeCluster(cluster);\n localStorage.setItem('curCluster', cluster);\n dispatch({\n type: 'common/saveData',\n prop: 'curCluster',\n data: cluster,\n });\n }}\n >\n {cluster}\n \n ))}\n \n );\n\n return (\n
\n {customArea ? (\n
{customArea}
\n ) : (\n
\n
\n
\n {showBack && (\n {\n if (backPath) {\n history.push({\n pathname: backPath,\n });\n } else {\n history.goBack();\n }\n }}\n style={{\n marginRight: '5px',\n }}\n />\n )}\n {icon}\n {title}\n
\n\n {/*
{rightArea}
*/}\n
\n {introIcon}\n {docFn && (\n docFn()} style={{ marginRight: 20 }}>\n 文档\n \n )}\n {/* 整合版本关闭文档链接 */}\n {import.meta.env.VITE_IS_COMMON_DS !== 'true' && (\n
\n \n 文档\n \n {\n return (\n \n \n \n );\n }}\n />\n
\n )}\n\n {!hideCluster && (\n
\n 集群:\n \n \n \n
\n )}\n \n \n \n\n {/* 文案完善了再打开 */}\n {/* {\n let language = i18n.language == 'en' ? 'zh' : 'en';\n i18n.changeLanguage(language);\n localStorage.setItem('language', language);\n }}\n >\n {i18n.language == 'zh' ? 'En' : '中'}\n */}\n \n \n \n {profile.nickname || profile.username}\n \n \n \n
\n
\n
\n )}\n {children && children}\n
\n );\n};\n\nexport default PageLayout;\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport * as React from 'react';\nvar rowSizeBase = {\n width: '100%',\n height: '10px',\n top: '0px',\n left: '0px',\n cursor: 'row-resize',\n};\nvar colSizeBase = {\n width: '10px',\n height: '100%',\n top: '0px',\n left: '0px',\n cursor: 'col-resize',\n};\nvar edgeBase = {\n width: '20px',\n height: '20px',\n position: 'absolute',\n};\nvar styles = {\n top: __assign(__assign({}, rowSizeBase), { top: '-5px' }),\n right: __assign(__assign({}, colSizeBase), { left: undefined, right: '-5px' }),\n bottom: __assign(__assign({}, rowSizeBase), { top: undefined, bottom: '-5px' }),\n left: __assign(__assign({}, colSizeBase), { left: '-5px' }),\n topRight: __assign(__assign({}, edgeBase), { right: '-10px', top: '-10px', cursor: 'ne-resize' }),\n bottomRight: __assign(__assign({}, edgeBase), { right: '-10px', bottom: '-10px', cursor: 'se-resize' }),\n bottomLeft: __assign(__assign({}, edgeBase), { left: '-10px', bottom: '-10px', cursor: 'sw-resize' }),\n topLeft: __assign(__assign({}, edgeBase), { left: '-10px', top: '-10px', cursor: 'nw-resize' }),\n};\nvar Resizer = /** @class */ (function (_super) {\n __extends(Resizer, _super);\n function Resizer() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.onMouseDown = function (e) {\n _this.props.onResizeStart(e, _this.props.direction);\n };\n _this.onTouchStart = function (e) {\n _this.props.onResizeStart(e, _this.props.direction);\n };\n return _this;\n }\n Resizer.prototype.render = function () {\n return (React.createElement(\"div\", { className: this.props.className || '', style: __assign(__assign({ position: 'absolute', userSelect: 'none' }, styles[this.props.direction]), (this.props.replaceStyles || {})), onMouseDown: this.onMouseDown, onTouchStart: this.onTouchStart }, this.props.children));\n };\n return Resizer;\n}(React.PureComponent));\nexport { Resizer };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport * as React from 'react';\nimport { flushSync } from 'react-dom';\nimport { Resizer } from './resizer';\nvar DEFAULT_SIZE = {\n width: 'auto',\n height: 'auto',\n};\nvar clamp = function (n, min, max) { return Math.max(Math.min(n, max), min); };\nvar snap = function (n, size) { return Math.round(n / size) * size; };\nvar hasDirection = function (dir, target) {\n return new RegExp(dir, 'i').test(target);\n};\n// INFO: In case of window is a Proxy and does not porxy Events correctly, use isTouchEvent & isMouseEvent to distinguish event type instead of `instanceof`.\nvar isTouchEvent = function (event) {\n return Boolean(event.touches && event.touches.length);\n};\nvar isMouseEvent = function (event) {\n return Boolean((event.clientX || event.clientX === 0) &&\n (event.clientY || event.clientY === 0));\n};\nvar findClosestSnap = function (n, snapArray, snapGap) {\n if (snapGap === void 0) { snapGap = 0; }\n var closestGapIndex = snapArray.reduce(function (prev, curr, index) { return (Math.abs(curr - n) < Math.abs(snapArray[prev] - n) ? index : prev); }, 0);\n var gap = Math.abs(snapArray[closestGapIndex] - n);\n return snapGap === 0 || gap < snapGap ? snapArray[closestGapIndex] : n;\n};\nvar getStringSize = function (n) {\n n = n.toString();\n if (n === 'auto') {\n return n;\n }\n if (n.endsWith('px')) {\n return n;\n }\n if (n.endsWith('%')) {\n return n;\n }\n if (n.endsWith('vh')) {\n return n;\n }\n if (n.endsWith('vw')) {\n return n;\n }\n if (n.endsWith('vmax')) {\n return n;\n }\n if (n.endsWith('vmin')) {\n return n;\n }\n return n + \"px\";\n};\nvar getPixelSize = function (size, parentSize, innerWidth, innerHeight) {\n if (size && typeof size === 'string') {\n if (size.endsWith('px')) {\n return Number(size.replace('px', ''));\n }\n if (size.endsWith('%')) {\n var ratio = Number(size.replace('%', '')) / 100;\n return parentSize * ratio;\n }\n if (size.endsWith('vw')) {\n var ratio = Number(size.replace('vw', '')) / 100;\n return innerWidth * ratio;\n }\n if (size.endsWith('vh')) {\n var ratio = Number(size.replace('vh', '')) / 100;\n return innerHeight * ratio;\n }\n }\n return size;\n};\nvar calculateNewMax = function (parentSize, innerWidth, innerHeight, maxWidth, maxHeight, minWidth, minHeight) {\n maxWidth = getPixelSize(maxWidth, parentSize.width, innerWidth, innerHeight);\n maxHeight = getPixelSize(maxHeight, parentSize.height, innerWidth, innerHeight);\n minWidth = getPixelSize(minWidth, parentSize.width, innerWidth, innerHeight);\n minHeight = getPixelSize(minHeight, parentSize.height, innerWidth, innerHeight);\n return {\n maxWidth: typeof maxWidth === 'undefined' ? undefined : Number(maxWidth),\n maxHeight: typeof maxHeight === 'undefined' ? undefined : Number(maxHeight),\n minWidth: typeof minWidth === 'undefined' ? undefined : Number(minWidth),\n minHeight: typeof minHeight === 'undefined' ? undefined : Number(minHeight),\n };\n};\nvar definedProps = [\n 'as',\n 'style',\n 'className',\n 'grid',\n 'snap',\n 'bounds',\n 'boundsByDirection',\n 'size',\n 'defaultSize',\n 'minWidth',\n 'minHeight',\n 'maxWidth',\n 'maxHeight',\n 'lockAspectRatio',\n 'lockAspectRatioExtraWidth',\n 'lockAspectRatioExtraHeight',\n 'enable',\n 'handleStyles',\n 'handleClasses',\n 'handleWrapperStyle',\n 'handleWrapperClass',\n 'children',\n 'onResizeStart',\n 'onResize',\n 'onResizeStop',\n 'handleComponent',\n 'scale',\n 'resizeRatio',\n 'snapGap',\n];\n// HACK: This class is used to calculate % size.\nvar baseClassName = '__resizable_base__';\nvar Resizable = /** @class */ (function (_super) {\n __extends(Resizable, _super);\n function Resizable(props) {\n var _this = _super.call(this, props) || this;\n _this.ratio = 1;\n _this.resizable = null;\n // For parent boundary\n _this.parentLeft = 0;\n _this.parentTop = 0;\n // For boundary\n _this.resizableLeft = 0;\n _this.resizableRight = 0;\n _this.resizableTop = 0;\n _this.resizableBottom = 0;\n // For target boundary\n _this.targetLeft = 0;\n _this.targetTop = 0;\n _this.appendBase = function () {\n if (!_this.resizable || !_this.window) {\n return null;\n }\n var parent = _this.parentNode;\n if (!parent) {\n return null;\n }\n var element = _this.window.document.createElement('div');\n element.style.width = '100%';\n element.style.height = '100%';\n element.style.position = 'absolute';\n element.style.transform = 'scale(0, 0)';\n element.style.left = '0';\n element.style.flex = '0 0 100%';\n if (element.classList) {\n element.classList.add(baseClassName);\n }\n else {\n element.className += baseClassName;\n }\n parent.appendChild(element);\n return element;\n };\n _this.removeBase = function (base) {\n var parent = _this.parentNode;\n if (!parent) {\n return;\n }\n parent.removeChild(base);\n };\n _this.ref = function (c) {\n if (c) {\n _this.resizable = c;\n }\n };\n _this.state = {\n isResizing: false,\n width: typeof (_this.propsSize && _this.propsSize.width) === 'undefined'\n ? 'auto'\n : _this.propsSize && _this.propsSize.width,\n height: typeof (_this.propsSize && _this.propsSize.height) === 'undefined'\n ? 'auto'\n : _this.propsSize && _this.propsSize.height,\n direction: 'right',\n original: {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n },\n backgroundStyle: {\n height: '100%',\n width: '100%',\n backgroundColor: 'rgba(0,0,0,0)',\n cursor: 'auto',\n opacity: 0,\n position: 'fixed',\n zIndex: 9999,\n top: '0',\n left: '0',\n bottom: '0',\n right: '0',\n },\n flexBasis: undefined,\n };\n _this.onResizeStart = _this.onResizeStart.bind(_this);\n _this.onMouseMove = _this.onMouseMove.bind(_this);\n _this.onMouseUp = _this.onMouseUp.bind(_this);\n return _this;\n }\n Object.defineProperty(Resizable.prototype, \"parentNode\", {\n get: function () {\n if (!this.resizable) {\n return null;\n }\n return this.resizable.parentNode;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Resizable.prototype, \"window\", {\n get: function () {\n if (!this.resizable) {\n return null;\n }\n if (!this.resizable.ownerDocument) {\n return null;\n }\n return this.resizable.ownerDocument.defaultView;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Resizable.prototype, \"propsSize\", {\n get: function () {\n return this.props.size || this.props.defaultSize || DEFAULT_SIZE;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Resizable.prototype, \"size\", {\n get: function () {\n var width = 0;\n var height = 0;\n if (this.resizable && this.window) {\n var orgWidth = this.resizable.offsetWidth;\n var orgHeight = this.resizable.offsetHeight;\n // HACK: Set position `relative` to get parent size.\n // This is because when re-resizable set `absolute`, I can not get base width correctly.\n var orgPosition = this.resizable.style.position;\n if (orgPosition !== 'relative') {\n this.resizable.style.position = 'relative';\n }\n // INFO: Use original width or height if set auto.\n width = this.resizable.style.width !== 'auto' ? this.resizable.offsetWidth : orgWidth;\n height = this.resizable.style.height !== 'auto' ? this.resizable.offsetHeight : orgHeight;\n // Restore original position\n this.resizable.style.position = orgPosition;\n }\n return { width: width, height: height };\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Resizable.prototype, \"sizeStyle\", {\n get: function () {\n var _this = this;\n var size = this.props.size;\n var getSize = function (key) {\n if (typeof _this.state[key] === 'undefined' || _this.state[key] === 'auto') {\n return 'auto';\n }\n if (_this.propsSize && _this.propsSize[key] && _this.propsSize[key].toString().endsWith('%')) {\n if (_this.state[key].toString().endsWith('%')) {\n return _this.state[key].toString();\n }\n var parentSize = _this.getParentSize();\n var value = Number(_this.state[key].toString().replace('px', ''));\n var percent = (value / parentSize[key]) * 100;\n return percent + \"%\";\n }\n return getStringSize(_this.state[key]);\n };\n var width = size && typeof size.width !== 'undefined' && !this.state.isResizing\n ? getStringSize(size.width)\n : getSize('width');\n var height = size && typeof size.height !== 'undefined' && !this.state.isResizing\n ? getStringSize(size.height)\n : getSize('height');\n return { width: width, height: height };\n },\n enumerable: false,\n configurable: true\n });\n Resizable.prototype.getParentSize = function () {\n if (!this.parentNode) {\n if (!this.window) {\n return { width: 0, height: 0 };\n }\n return { width: this.window.innerWidth, height: this.window.innerHeight };\n }\n var base = this.appendBase();\n if (!base) {\n return { width: 0, height: 0 };\n }\n // INFO: To calculate parent width with flex layout\n var wrapChanged = false;\n var wrap = this.parentNode.style.flexWrap;\n if (wrap !== 'wrap') {\n wrapChanged = true;\n this.parentNode.style.flexWrap = 'wrap';\n // HACK: Use relative to get parent padding size\n }\n base.style.position = 'relative';\n base.style.minWidth = '100%';\n base.style.minHeight = '100%';\n var size = {\n width: base.offsetWidth,\n height: base.offsetHeight,\n };\n if (wrapChanged) {\n this.parentNode.style.flexWrap = wrap;\n }\n this.removeBase(base);\n return size;\n };\n Resizable.prototype.bindEvents = function () {\n if (this.window) {\n this.window.addEventListener('mouseup', this.onMouseUp);\n this.window.addEventListener('mousemove', this.onMouseMove);\n this.window.addEventListener('mouseleave', this.onMouseUp);\n this.window.addEventListener('touchmove', this.onMouseMove, {\n capture: true,\n passive: false,\n });\n this.window.addEventListener('touchend', this.onMouseUp);\n }\n };\n Resizable.prototype.unbindEvents = function () {\n if (this.window) {\n this.window.removeEventListener('mouseup', this.onMouseUp);\n this.window.removeEventListener('mousemove', this.onMouseMove);\n this.window.removeEventListener('mouseleave', this.onMouseUp);\n this.window.removeEventListener('touchmove', this.onMouseMove, true);\n this.window.removeEventListener('touchend', this.onMouseUp);\n }\n };\n Resizable.prototype.componentDidMount = function () {\n if (!this.resizable || !this.window) {\n return;\n }\n var computedStyle = this.window.getComputedStyle(this.resizable);\n this.setState({\n width: this.state.width || this.size.width,\n height: this.state.height || this.size.height,\n flexBasis: computedStyle.flexBasis !== 'auto' ? computedStyle.flexBasis : undefined,\n });\n };\n Resizable.prototype.componentWillUnmount = function () {\n if (this.window) {\n this.unbindEvents();\n }\n };\n Resizable.prototype.createSizeForCssProperty = function (newSize, kind) {\n var propsSize = this.propsSize && this.propsSize[kind];\n return this.state[kind] === 'auto' &&\n this.state.original[kind] === newSize &&\n (typeof propsSize === 'undefined' || propsSize === 'auto')\n ? 'auto'\n : newSize;\n };\n Resizable.prototype.calculateNewMaxFromBoundary = function (maxWidth, maxHeight) {\n var boundsByDirection = this.props.boundsByDirection;\n var direction = this.state.direction;\n var widthByDirection = boundsByDirection && hasDirection('left', direction);\n var heightByDirection = boundsByDirection && hasDirection('top', direction);\n var boundWidth;\n var boundHeight;\n if (this.props.bounds === 'parent') {\n var parent_1 = this.parentNode;\n if (parent_1) {\n boundWidth = widthByDirection\n ? this.resizableRight - this.parentLeft\n : parent_1.offsetWidth + (this.parentLeft - this.resizableLeft);\n boundHeight = heightByDirection\n ? this.resizableBottom - this.parentTop\n : parent_1.offsetHeight + (this.parentTop - this.resizableTop);\n }\n }\n else if (this.props.bounds === 'window') {\n if (this.window) {\n boundWidth = widthByDirection ? this.resizableRight : this.window.innerWidth - this.resizableLeft;\n boundHeight = heightByDirection ? this.resizableBottom : this.window.innerHeight - this.resizableTop;\n }\n }\n else if (this.props.bounds) {\n boundWidth = widthByDirection\n ? this.resizableRight - this.targetLeft\n : this.props.bounds.offsetWidth + (this.targetLeft - this.resizableLeft);\n boundHeight = heightByDirection\n ? this.resizableBottom - this.targetTop\n : this.props.bounds.offsetHeight + (this.targetTop - this.resizableTop);\n }\n if (boundWidth && Number.isFinite(boundWidth)) {\n maxWidth = maxWidth && maxWidth < boundWidth ? maxWidth : boundWidth;\n }\n if (boundHeight && Number.isFinite(boundHeight)) {\n maxHeight = maxHeight && maxHeight < boundHeight ? maxHeight : boundHeight;\n }\n return { maxWidth: maxWidth, maxHeight: maxHeight };\n };\n Resizable.prototype.calculateNewSizeFromDirection = function (clientX, clientY) {\n var scale = this.props.scale || 1;\n var resizeRatio = this.props.resizeRatio || 1;\n var _a = this.state, direction = _a.direction, original = _a.original;\n var _b = this.props, lockAspectRatio = _b.lockAspectRatio, lockAspectRatioExtraHeight = _b.lockAspectRatioExtraHeight, lockAspectRatioExtraWidth = _b.lockAspectRatioExtraWidth;\n var newWidth = original.width;\n var newHeight = original.height;\n var extraHeight = lockAspectRatioExtraHeight || 0;\n var extraWidth = lockAspectRatioExtraWidth || 0;\n if (hasDirection('right', direction)) {\n newWidth = original.width + ((clientX - original.x) * resizeRatio) / scale;\n if (lockAspectRatio) {\n newHeight = (newWidth - extraWidth) / this.ratio + extraHeight;\n }\n }\n if (hasDirection('left', direction)) {\n newWidth = original.width - ((clientX - original.x) * resizeRatio) / scale;\n if (lockAspectRatio) {\n newHeight = (newWidth - extraWidth) / this.ratio + extraHeight;\n }\n }\n if (hasDirection('bottom', direction)) {\n newHeight = original.height + ((clientY - original.y) * resizeRatio) / scale;\n if (lockAspectRatio) {\n newWidth = (newHeight - extraHeight) * this.ratio + extraWidth;\n }\n }\n if (hasDirection('top', direction)) {\n newHeight = original.height - ((clientY - original.y) * resizeRatio) / scale;\n if (lockAspectRatio) {\n newWidth = (newHeight - extraHeight) * this.ratio + extraWidth;\n }\n }\n return { newWidth: newWidth, newHeight: newHeight };\n };\n Resizable.prototype.calculateNewSizeFromAspectRatio = function (newWidth, newHeight, max, min) {\n var _a = this.props, lockAspectRatio = _a.lockAspectRatio, lockAspectRatioExtraHeight = _a.lockAspectRatioExtraHeight, lockAspectRatioExtraWidth = _a.lockAspectRatioExtraWidth;\n var computedMinWidth = typeof min.width === 'undefined' ? 10 : min.width;\n var computedMaxWidth = typeof max.width === 'undefined' || max.width < 0 ? newWidth : max.width;\n var computedMinHeight = typeof min.height === 'undefined' ? 10 : min.height;\n var computedMaxHeight = typeof max.height === 'undefined' || max.height < 0 ? newHeight : max.height;\n var extraHeight = lockAspectRatioExtraHeight || 0;\n var extraWidth = lockAspectRatioExtraWidth || 0;\n if (lockAspectRatio) {\n var extraMinWidth = (computedMinHeight - extraHeight) * this.ratio + extraWidth;\n var extraMaxWidth = (computedMaxHeight - extraHeight) * this.ratio + extraWidth;\n var extraMinHeight = (computedMinWidth - extraWidth) / this.ratio + extraHeight;\n var extraMaxHeight = (computedMaxWidth - extraWidth) / this.ratio + extraHeight;\n var lockedMinWidth = Math.max(computedMinWidth, extraMinWidth);\n var lockedMaxWidth = Math.min(computedMaxWidth, extraMaxWidth);\n var lockedMinHeight = Math.max(computedMinHeight, extraMinHeight);\n var lockedMaxHeight = Math.min(computedMaxHeight, extraMaxHeight);\n newWidth = clamp(newWidth, lockedMinWidth, lockedMaxWidth);\n newHeight = clamp(newHeight, lockedMinHeight, lockedMaxHeight);\n }\n else {\n newWidth = clamp(newWidth, computedMinWidth, computedMaxWidth);\n newHeight = clamp(newHeight, computedMinHeight, computedMaxHeight);\n }\n return { newWidth: newWidth, newHeight: newHeight };\n };\n Resizable.prototype.setBoundingClientRect = function () {\n // For parent boundary\n if (this.props.bounds === 'parent') {\n var parent_2 = this.parentNode;\n if (parent_2) {\n var parentRect = parent_2.getBoundingClientRect();\n this.parentLeft = parentRect.left;\n this.parentTop = parentRect.top;\n }\n }\n // For target(html element) boundary\n if (this.props.bounds && typeof this.props.bounds !== 'string') {\n var targetRect = this.props.bounds.getBoundingClientRect();\n this.targetLeft = targetRect.left;\n this.targetTop = targetRect.top;\n }\n // For boundary\n if (this.resizable) {\n var _a = this.resizable.getBoundingClientRect(), left = _a.left, top_1 = _a.top, right = _a.right, bottom = _a.bottom;\n this.resizableLeft = left;\n this.resizableRight = right;\n this.resizableTop = top_1;\n this.resizableBottom = bottom;\n }\n };\n Resizable.prototype.onResizeStart = function (event, direction) {\n if (!this.resizable || !this.window) {\n return;\n }\n var clientX = 0;\n var clientY = 0;\n if (event.nativeEvent && isMouseEvent(event.nativeEvent)) {\n clientX = event.nativeEvent.clientX;\n clientY = event.nativeEvent.clientY;\n }\n else if (event.nativeEvent && isTouchEvent(event.nativeEvent)) {\n clientX = event.nativeEvent.touches[0].clientX;\n clientY = event.nativeEvent.touches[0].clientY;\n }\n if (this.props.onResizeStart) {\n if (this.resizable) {\n var startResize = this.props.onResizeStart(event, direction, this.resizable);\n if (startResize === false) {\n return;\n }\n }\n }\n // Fix #168\n if (this.props.size) {\n if (typeof this.props.size.height !== 'undefined' && this.props.size.height !== this.state.height) {\n this.setState({ height: this.props.size.height });\n }\n if (typeof this.props.size.width !== 'undefined' && this.props.size.width !== this.state.width) {\n this.setState({ width: this.props.size.width });\n }\n }\n // For lockAspectRatio case\n this.ratio =\n typeof this.props.lockAspectRatio === 'number' ? this.props.lockAspectRatio : this.size.width / this.size.height;\n var flexBasis;\n var computedStyle = this.window.getComputedStyle(this.resizable);\n if (computedStyle.flexBasis !== 'auto') {\n var parent_3 = this.parentNode;\n if (parent_3) {\n var dir = this.window.getComputedStyle(parent_3).flexDirection;\n this.flexDir = dir.startsWith('row') ? 'row' : 'column';\n flexBasis = computedStyle.flexBasis;\n }\n }\n // For boundary\n this.setBoundingClientRect();\n this.bindEvents();\n var state = {\n original: {\n x: clientX,\n y: clientY,\n width: this.size.width,\n height: this.size.height,\n },\n isResizing: true,\n backgroundStyle: __assign(__assign({}, this.state.backgroundStyle), { cursor: this.window.getComputedStyle(event.target).cursor || 'auto' }),\n direction: direction,\n flexBasis: flexBasis,\n };\n this.setState(state);\n };\n Resizable.prototype.onMouseMove = function (event) {\n var _this = this;\n if (!this.state.isResizing || !this.resizable || !this.window) {\n return;\n }\n if (this.window.TouchEvent && isTouchEvent(event)) {\n try {\n event.preventDefault();\n event.stopPropagation();\n }\n catch (e) {\n // Ignore on fail\n }\n }\n var _a = this.props, maxWidth = _a.maxWidth, maxHeight = _a.maxHeight, minWidth = _a.minWidth, minHeight = _a.minHeight;\n var clientX = isTouchEvent(event) ? event.touches[0].clientX : event.clientX;\n var clientY = isTouchEvent(event) ? event.touches[0].clientY : event.clientY;\n var _b = this.state, direction = _b.direction, original = _b.original, width = _b.width, height = _b.height;\n var parentSize = this.getParentSize();\n var max = calculateNewMax(parentSize, this.window.innerWidth, this.window.innerHeight, maxWidth, maxHeight, minWidth, minHeight);\n maxWidth = max.maxWidth;\n maxHeight = max.maxHeight;\n minWidth = max.minWidth;\n minHeight = max.minHeight;\n // Calculate new size\n var _c = this.calculateNewSizeFromDirection(clientX, clientY), newHeight = _c.newHeight, newWidth = _c.newWidth;\n // Calculate max size from boundary settings\n var boundaryMax = this.calculateNewMaxFromBoundary(maxWidth, maxHeight);\n if (this.props.snap && this.props.snap.x) {\n newWidth = findClosestSnap(newWidth, this.props.snap.x, this.props.snapGap);\n }\n if (this.props.snap && this.props.snap.y) {\n newHeight = findClosestSnap(newHeight, this.props.snap.y, this.props.snapGap);\n }\n // Calculate new size from aspect ratio\n var newSize = this.calculateNewSizeFromAspectRatio(newWidth, newHeight, { width: boundaryMax.maxWidth, height: boundaryMax.maxHeight }, { width: minWidth, height: minHeight });\n newWidth = newSize.newWidth;\n newHeight = newSize.newHeight;\n if (this.props.grid) {\n var newGridWidth = snap(newWidth, this.props.grid[0]);\n var newGridHeight = snap(newHeight, this.props.grid[1]);\n var gap = this.props.snapGap || 0;\n newWidth = gap === 0 || Math.abs(newGridWidth - newWidth) <= gap ? newGridWidth : newWidth;\n newHeight = gap === 0 || Math.abs(newGridHeight - newHeight) <= gap ? newGridHeight : newHeight;\n }\n var delta = {\n width: newWidth - original.width,\n height: newHeight - original.height,\n };\n if (width && typeof width === 'string') {\n if (width.endsWith('%')) {\n var percent = (newWidth / parentSize.width) * 100;\n newWidth = percent + \"%\";\n }\n else if (width.endsWith('vw')) {\n var vw = (newWidth / this.window.innerWidth) * 100;\n newWidth = vw + \"vw\";\n }\n else if (width.endsWith('vh')) {\n var vh = (newWidth / this.window.innerHeight) * 100;\n newWidth = vh + \"vh\";\n }\n }\n if (height && typeof height === 'string') {\n if (height.endsWith('%')) {\n var percent = (newHeight / parentSize.height) * 100;\n newHeight = percent + \"%\";\n }\n else if (height.endsWith('vw')) {\n var vw = (newHeight / this.window.innerWidth) * 100;\n newHeight = vw + \"vw\";\n }\n else if (height.endsWith('vh')) {\n var vh = (newHeight / this.window.innerHeight) * 100;\n newHeight = vh + \"vh\";\n }\n }\n var newState = {\n width: this.createSizeForCssProperty(newWidth, 'width'),\n height: this.createSizeForCssProperty(newHeight, 'height'),\n };\n if (this.flexDir === 'row') {\n newState.flexBasis = newState.width;\n }\n else if (this.flexDir === 'column') {\n newState.flexBasis = newState.height;\n }\n // For v18, update state sync\n flushSync(function () {\n _this.setState(newState);\n });\n if (this.props.onResize) {\n this.props.onResize(event, direction, this.resizable, delta);\n }\n };\n Resizable.prototype.onMouseUp = function (event) {\n var _a = this.state, isResizing = _a.isResizing, direction = _a.direction, original = _a.original;\n if (!isResizing || !this.resizable) {\n return;\n }\n var delta = {\n width: this.size.width - original.width,\n height: this.size.height - original.height,\n };\n if (this.props.onResizeStop) {\n this.props.onResizeStop(event, direction, this.resizable, delta);\n }\n if (this.props.size) {\n this.setState(this.props.size);\n }\n this.unbindEvents();\n this.setState({\n isResizing: false,\n backgroundStyle: __assign(__assign({}, this.state.backgroundStyle), { cursor: 'auto' }),\n });\n };\n Resizable.prototype.updateSize = function (size) {\n this.setState({ width: size.width, height: size.height });\n };\n Resizable.prototype.renderResizer = function () {\n var _this = this;\n var _a = this.props, enable = _a.enable, handleStyles = _a.handleStyles, handleClasses = _a.handleClasses, handleWrapperStyle = _a.handleWrapperStyle, handleWrapperClass = _a.handleWrapperClass, handleComponent = _a.handleComponent;\n if (!enable) {\n return null;\n }\n var resizers = Object.keys(enable).map(function (dir) {\n if (enable[dir] !== false) {\n return (React.createElement(Resizer, { key: dir, direction: dir, onResizeStart: _this.onResizeStart, replaceStyles: handleStyles && handleStyles[dir], className: handleClasses && handleClasses[dir] }, handleComponent && handleComponent[dir] ? handleComponent[dir] : null));\n }\n return null;\n });\n // #93 Wrap the resize box in span (will not break 100% width/height)\n return (React.createElement(\"div\", { className: handleWrapperClass, style: handleWrapperStyle }, resizers));\n };\n Resizable.prototype.render = function () {\n var _this = this;\n var extendsProps = Object.keys(this.props).reduce(function (acc, key) {\n if (definedProps.indexOf(key) !== -1) {\n return acc;\n }\n acc[key] = _this.props[key];\n return acc;\n }, {});\n var style = __assign(__assign(__assign({ position: 'relative', userSelect: this.state.isResizing ? 'none' : 'auto' }, this.props.style), this.sizeStyle), { maxWidth: this.props.maxWidth, maxHeight: this.props.maxHeight, minWidth: this.props.minWidth, minHeight: this.props.minHeight, boxSizing: 'border-box', flexShrink: 0 });\n if (this.state.flexBasis) {\n style.flexBasis = this.state.flexBasis;\n }\n var Wrapper = this.props.as || 'div';\n return (React.createElement(Wrapper, __assign({ ref: this.ref, style: style, className: this.props.className }, extendsProps),\n this.state.isResizing && React.createElement(\"div\", { style: this.state.backgroundStyle }),\n this.props.children,\n this.renderResizer()));\n };\n Resizable.defaultProps = {\n as: 'div',\n onResizeStart: function () { },\n onResize: function () { },\n onResizeStop: function () { },\n enable: {\n top: true,\n right: true,\n bottom: true,\n left: true,\n topRight: true,\n bottomRight: true,\n bottomLeft: true,\n topLeft: true,\n },\n style: {},\n grid: [1, 1],\n lockAspectRatio: false,\n lockAspectRatioExtraWidth: 0,\n lockAspectRatioExtraHeight: 0,\n scale: 1,\n resizeRatio: 1,\n snapGap: 0,\n };\n return Resizable;\n}(React.PureComponent));\nexport { Resizable };\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useEffect, useMemo, useState, useRef } from 'react';\nimport { Badge, Checkbox, Col, Input, Radio, Row, Space } from 'antd';\nimport { Resizable } from 're-resizable';\nimport { useDispatch, useSelector } from 'react-redux';\nimport { RootState } from '@/store/common';\nimport { getBusiGroups } from '@/services/common';\nimport { CommonStoreState } from '@/store/commonInterface';\nimport _ from 'lodash';\nimport './index.less';\nimport { SearchOutlined, SettingOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons';\nimport { useHistory } from 'react-router-dom';\nimport { eventStoreState } from '@/store/eventInterface';\nimport classNames from 'classnames';\n\nconst CheckboxGroup = Checkbox.Group;\ntype ChangeFunction = (value: any, item?: any) => void;\n\ninterface groupProps {\n isShow?: boolean;\n onChange?: ChangeFunction;\n}\n\ninterface BusiGroupProps {\n defaultSelect?: number | undefined;\n showNotGroupItem?: boolean;\n showAlertings?: boolean;\n onChange?: ChangeFunction;\n}\n\ninterface LeftTreeProps {\n clusterGroup?: groupProps;\n eventLevelGroup?: groupProps & { defaultSelect?: number | undefined };\n eventTypeGroup?: groupProps & { defaultSelect?: number | undefined };\n busiGroup?: BusiGroupProps;\n}\ninterface IGroupItemProps {\n title: string | React.ReactNode;\n isShow?: boolean;\n shrink?:\n | boolean\n | {\n style: object;\n };\n render: Function;\n}\n\ninterface SelectListProps {\n dataSource: object[];\n fieldNames?: {\n key: string;\n label: string;\n value: string;\n };\n defaultSelect?: object | string | number;\n allowNotSelect?: boolean;\n showBadge?: boolean;\n badgeInfo?: { ['index']?: number };\n onChange?: ChangeFunction;\n}\n\n// 内容可选列表\nexport const SelectList: React.FC = ({ dataSource, fieldNames = {}, allowNotSelect = false, defaultSelect, showBadge = false, badgeInfo = {}, onChange }) => {\n const [active, setActive] = useState(defaultSelect && typeof defaultSelect === 'object' ? defaultSelect[fieldNames.key || 'value'] : defaultSelect);\n\n return (\n
\n {dataSource.map((item: any) => {\n return (\n \n \n {\n if (item.id !== active) {\n setActive(item.id);\n onChange && onChange(item.id, item);\n }\n }}\n >\n {item.name}\n
\n \n {showBadge && (\n \n
\n \n
\n \n )}\n \n );\n })}\n \n );\n};\n\n// 集群渲染内容\nconst clustersGroupContent = (clusterGroup: groupProps): IGroupItemProps => {\n const dispatch = useDispatch();\n const { clusters, curClusterItems } = useSelector((state) => state.common);\n const [indeterminate, setIndeterminate] = useState(false);\n const [checkAll, setCheckAll] = useState(false);\n\n const setClusterItems = (curClusterItems) => {\n dispatch({\n type: 'common/saveData',\n prop: 'curClusterItems',\n data: curClusterItems,\n });\n localStorage.setItem('curClusterItems', JSON.stringify(curClusterItems));\n clusterGroup.onChange && clusterGroup.onChange(curClusterItems);\n };\n const onCheckAllChange = (e) => {\n const curCheckedList = e.target.checked ? clusters : [];\n setClusterItems(curCheckedList);\n setIndeterminate(false);\n setCheckAll(e.target.checked);\n };\n\n // 获取到集群列表数据后抛出默认选择项并同步全选状态\n useEffect(() => {\n setCheckAll(clusters.length === curClusterItems.length);\n setIndeterminate(!!curClusterItems.length && curClusterItems.length < clusters.length);\n\n if (clusters.length && clusterGroup.onChange) {\n clusterGroup.onChange(curClusterItems);\n }\n }, [clusters]);\n\n return {\n title: (\n
\n 集群\n {/* \n 全选\n */}\n
\n ),\n isShow: clusterGroup.isShow,\n shrink: {\n style: {\n flex: 'none',\n maxHeight: '200px',\n },\n },\n render() {\n return (\n {\n setClusterItems(list);\n setIndeterminate(!!list.length && list.length < clusters.length);\n setCheckAll(list.length === clusters.length);\n }}\n >\n );\n },\n };\n};\n\n// 业务组渲染内容\nconst busiGroupContent = (busiGroupProps: BusiGroupProps): IGroupItemProps => {\n const dispatch = useDispatch();\n const { busiGroups, curBusiItem } = useSelector((state) => state.common);\n const { alertings } = useSelector((state) => state.event);\n const [filteredBusiGroups, setFilteredBusiGroups] = useState(busiGroups);\n const showNotGroupItem = busiGroupProps.showNotGroupItem;\n // 初始化,当不展示 [未归组对象] 时,选中第一条业务组\n if (!localStorage.getItem('curBusiItem') && !showNotGroupItem && busiGroups.length > 0) {\n localStorage.setItem('curBusiItem', JSON.stringify(busiGroups[0]));\n dispatch({\n type: 'common/saveData',\n prop: 'curBusiItem',\n data: busiGroups[0],\n });\n }\n if (busiGroupProps.defaultSelect && busiGroups.length > 0 && curBusiItem.id !== busiGroupProps.defaultSelect) {\n const curBusiness = busiGroups.find((item) => item.id === busiGroupProps.defaultSelect);\n if (curBusiness) {\n localStorage.setItem('curBusiItem', JSON.stringify(curBusiness));\n dispatch({\n type: 'common/saveData',\n prop: 'curBusiItem',\n data: curBusiness,\n });\n }\n }\n // 初始化选中项\n const initCurBusiItem = useMemo(() => (busiGroupProps.defaultSelect ? { id: busiGroupProps.defaultSelect } : curBusiItem.id ? curBusiItem : { id: undefined }), [curBusiItem]);\n\n // 初始化展示所有业务组\n useEffect(() => {\n if (!filteredBusiGroups.length) {\n setFilteredBusiGroups(busiGroups);\n }\n }, [busiGroups]);\n\n // 初始化抛出默认选择项\n useEffect(() => {\n if (busiGroups.length && busiGroupProps.onChange && (showNotGroupItem || (!showNotGroupItem && initCurBusiItem.id))) {\n busiGroupProps.onChange(initCurBusiItem.id, initCurBusiItem);\n }\n }, [busiGroups, initCurBusiItem]);\n\n return {\n title: '业务组',\n isShow: true,\n shrink: true,\n render() {\n return (\n <>\n }\n onPressEnter={(e) => {\n e.preventDefault();\n const value = e.currentTarget.value;\n if (value) {\n getBusiGroups(value).then((res) => {\n setFilteredBusiGroups(res.dat || []);\n });\n } else {\n getBusiGroups('').then((res) => {\n const data = res.dat || [];\n setFilteredBusiGroups(data);\n dispatch({\n type: 'common/saveData',\n prop: 'busiGroups',\n data,\n });\n });\n }\n }}\n placeholder={'请输入业务组名称进行筛选'}\n />\n {(!showNotGroupItem && curBusiItem.id && filteredBusiGroups.length !== 0) || showNotGroupItem ? (\n {\n if (value) {\n dispatch({\n type: 'common/saveData',\n prop: 'curBusiItem',\n data: item,\n });\n localStorage.setItem('curBusiItem', JSON.stringify(item));\n }\n busiGroupProps.onChange && busiGroupProps.onChange(value, item);\n }}\n />\n ) : (\n
\n \n
{'暂无数据'}
\n
\n )}\n \n );\n },\n };\n};\n\n// 左侧栏\nconst LeftTree: React.FC = ({ clusterGroup = {}, busiGroup = {}, eventLevelGroup = {}, eventTypeGroup = {} }) => {\n const history = useHistory();\n const [collapse, setCollapse] = useState(localStorage.getItem('leftlist') === '1');\n const groupItems: IGroupItemProps[] = [\n clustersGroupContent(clusterGroup),\n busiGroupContent(busiGroup),\n {\n title: '事件级别',\n isShow: eventLevelGroup.isShow,\n render() {\n return (\n \n );\n },\n },\n {\n title: '事件类别',\n isShow: eventTypeGroup.isShow,\n render() {\n return (\n \n );\n },\n },\n ];\n const [width, setWidth] = useState(_.toNumber(localStorage.getItem('leftwidth') || 200));\n\n return (\n {\n let curWidth = width + d.width;\n if (curWidth < 200) {\n curWidth = 200;\n }\n setWidth(curWidth);\n localStorage.setItem('leftwidth', curWidth.toString());\n }}\n >\n
\n {\n localStorage.setItem('leftlist', !collapse ? '1' : '0');\n setCollapse(!collapse);\n }}\n >\n {!collapse ? : }\n
\n {/* 遍历渲染左侧栏内容 */}\n {groupItems.map(\n ({ title, isShow, shrink = false, render }: IGroupItemProps, i) =>\n isShow && (\n
\n
\n {title}\n {title === '业务组' && history.push(`/busi-groups`)} />}\n
\n {render()}\n
\n ),\n )}\n \n \n );\n};\n\nexport default LeftTree;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useState } from 'react';\nimport { useParams, Link } from 'react-router-dom';\nimport { useTranslation } from 'react-i18next';\nimport { InfoCircleOutlined } from '@ant-design/icons';\ninterface Props {\n text: string;\n}\nexport default function BlankBusinessPlaceholder(props: Props) {\n const { t } = useTranslation();\n const { text } = props;\n\n return (\n
\n

\n {t('提示信息')}\n

\n

\n {text}需要归属某个业务组,请先  \n 创建业务组\n

\n
\n );\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useState } from 'react';\nimport { SearchOutlined } from '@ant-design/icons';\nimport { Input, InputProps } from 'antd';\nimport { useTranslation } from 'react-i18next';\ninterface IBaseSearchInputProps extends InputProps {\n onSearch?: (value: string) => unknown;\n}\n\nconst BaseSearchInput: React.FC = ({\n onSearch,\n ...props\n}) => {\n const { t } = useTranslation();\n const [value, setValue] = useState('');\n return (\n }\n value={value}\n onChange={(e) => {\n setValue(e.target.value);\n\n if (e.target.value === '') {\n onSearch && onSearch('');\n }\n }}\n onPressEnter={(e) => {\n onSearch && onSearch(value);\n }}\n {...props}\n />\n );\n};\n\nexport default BaseSearchInput;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport { baseFavoriteItem, favoriteGroup } from '../common';\nexport type TagKey = {\n key: string;\n};\n\nexport type TagValue = {\n value: string;\n};\n\nexport type TagKeysRes = {\n dat: {\n keys: Array;\n };\n};\n\nexport type TagValuesRes = {\n dat: {\n values: Array;\n };\n};\n\nexport type Expression = {\n optr: string;\n func: string;\n metric: string;\n params?: Array;\n threshold: number;\n};\n\nexport type ResourceFilterCondition = {\n params: number | Array;\n func: string;\n};\n\nexport type TagFilterCondition = {\n key: string;\n func: string;\n};\n\nexport type AppendTagFilterCondition = {\n tagk: Array;\n tagv: Array;\n};\n\nexport type Metric = {\n name: string;\n description: string;\n promql?: string;\n};\n\nexport type MetricListRes = {\n dat: {\n list: Array;\n };\n};\n\nexport enum strategyType {\n n9e = 0,\n prometheus = 1,\n}\n\nexport enum strategyStatus {\n Enable = 0,\n UnEnable = 1,\n}\n\nexport enum notifyType {\n Send = 0,\n UnSend = 1,\n}\n\nexport enum strategyPriority {\n First = 1,\n Second = 2,\n Third = 3,\n}\nexport interface strategyItem {\n id: number;\n group_id: number;\n name: string;\n type: strategyType;\n expression: {\n promql: string;\n };\n alert_duration: number;\n // status: strategyStatus;\n disabled: strategyStatus;\n append_tags: string;\n enable_stime: string;\n enable_etime: string;\n enable_days_of_week: string;\n recovery_duration: number;\n recovery_notify: notifyType;\n // priority: strategyPriority;\n severity: strategyPriority;\n notify_channels: string;\n notify_groups: string;\n notify_users: string;\n callbacks: string;\n runbook_url: string;\n note: string;\n create_at: number;\n create_by: string;\n update_at: number;\n update_by: string;\n // notify_groups_detail: Array;\n notify_groups_obj: Array;\n}\n\nexport enum strategyFrom {\n Favorite,\n Common,\n}\n\nexport type strategyGroup = {\n favorite: Array;\n common: Array;\n};\n\nexport type strategyGroupItemBase = {\n name: string;\n user_group_ids: string;\n user_groups: Array;\n};\n\n// export type strategyGroupItem = baseFavoriteItem & {\n// name: string;\n// };\n\nexport type strategyGroupItem = {\n id: number;\n};\n\nexport interface warningStoreState {\n group: favoriteGroup;\n currentGroup: strategyGroupItem;\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nexport const funcMap = (t) => {\n return {\n all: {\n label: t('周期内所有点'),\n meaning: t(\n '在统计周期 $n 秒内(初次上报的指标,统计周期内只有一个值,如要限制点数,可选择happen函数)每个值都 $v',\n ),\n meaningEn: 'duration $n s, every value $v',\n params: [],\n defaultValue: [],\n },\n happen: {\n label: t('发生次数'),\n meaning: t('统计周期 $n 秒内至少有 $m 次值 $v'),\n meaningEn: 'duration $n s, $m times value $v',\n params: ['m'],\n defaultValue: [1],\n },\n max: {\n label: t('最大值'),\n meaning: t('统计周期 $n 秒内的最大值 $v'),\n meaningEn: 'duration $n s, max $v',\n params: [],\n defaultValue: [],\n },\n min: {\n label: t('最小值'),\n meaning: t('统计周期 $n 秒内的最小值 $v'),\n meaningEn: 'duration $n s, min $v',\n params: [],\n defaultValue: [],\n },\n avg: {\n label: t('均值'),\n meaning: t('统计周期 $n 秒内的均值 $v'),\n meaningEn: 'duration $n s, avg $v',\n params: [],\n defaultValue: [],\n },\n sum: {\n label: t('求和'),\n meaning: t('统计周期 $n 秒内的所有值求和 $v'),\n meaningEn: 'duration $n s, sum $v',\n params: [],\n defaultValue: [],\n },\n diff: {\n label: t('突增突降值'),\n meaning: t('最新值与其之前 $n 秒内的任意值之差 (区分正负) $v'),\n params: [],\n defaultValue: [],\n },\n pdiff: {\n label: t('突增突降率'),\n meaning: t(\n '(最新值与其之前 $n 秒的任意值之差)除以对应历史值 (区分正负) $v %',\n ),\n params: [],\n defaultValue: [],\n },\n c_avg_rate_abs: {\n label: t('同比变化率'),\n meaning: t('最近 $n 秒平均值相对 $m 天前同周期平均值变化率 $v %'),\n params: ['m'],\n defaultValue: [86400],\n },\n c_avg_rate: {\n label: t('同比变化率(区分正负)'),\n meaning: t('最近 $n 秒平均值相对 $m 天前同周期平均值变化率 $v %'),\n params: ['m'],\n defaultValue: [86400],\n },\n c_avg_abs: {\n label: t('同比变化值'),\n meaning: t('最近 $n 秒平均值相对 $m 天前同周期平均值变化值 $v'),\n params: ['m'],\n defaultValue: [86400],\n },\n c_avg: {\n label: t('同比变化值(区分正负)'),\n meaning: t('最近 $n 秒平均值相对 $m 天前同周期平均值变化值 $v'),\n params: ['m'],\n defaultValue: [86400],\n },\n stddev: {\n label: t('3-sigma离群点检测'),\n meaning: t('统计周期 $n 秒内波动值过大,超过了 $m 个标准差范围'),\n meaningEn:\n 'within $n seconds, the fluctuation value exceeds the $m standard deviation range',\n params: ['m'],\n defaultValue: [3],\n },\n };\n};\nexport const resourceFilterConditions = [\n {\n value: 'InClasspath',\n multiple: true,\n },\n {\n value: 'NotInClasspath',\n multiple: true,\n },\n {\n value: 'InClasspathPrefix',\n multiple: false,\n },\n {\n value: 'NotInClasspathPrefix',\n multiple: false,\n },\n {\n value: 'InResourceList',\n multiple: true,\n },\n {\n value: 'NotInResourceList',\n multiple: true,\n },\n {\n value: 'HasPrefixString',\n multiple: false,\n },\n {\n value: 'NoPrefixString',\n multiple: false,\n },\n {\n value: 'HasSuffixString',\n multiple: false,\n },\n {\n value: 'NoSuffixString',\n multiple: false,\n },\n {\n value: 'ContainsString',\n multiple: false,\n },\n {\n value: 'NotContainsString',\n multiple: false,\n },\n {\n value: 'MatchRegexp',\n multiple: false,\n },\n {\n value: 'NotMatchRegexp',\n multiple: false,\n },\n];\nexport const tagFilterConditions = [\n {\n value: 'InList',\n multiple: true,\n },\n {\n value: 'NotInList',\n multiple: true,\n },\n {\n value: 'HasPrefixString',\n multiple: false,\n },\n {\n value: 'NoPrefixString',\n multiple: false,\n },\n {\n value: 'HasSuffixString',\n multiple: false,\n },\n {\n value: 'NoSuffixString',\n multiple: false,\n },\n {\n value: 'ContainsString',\n multiple: false,\n },\n {\n value: 'NotContainsString',\n multiple: false,\n },\n {\n value: 'MatchRegexp',\n multiple: false,\n },\n {\n value: 'NotMatchRegexp',\n multiple: false,\n },\n];\n\nexport const pageSizeOptionsDefault = ['30', '50', '100', '300'];\n\nexport const timeLensDefault = [\n {\n value: '1h'\n },\n {\n value: '2h'\n },\n {\n value: '3h'\n },\n {\n value: '6h'\n },\n {\n value: '12h'\n },\n {\n value: '1d'\n },\n {\n value: '2d'\n },\n {\n value: '3d'\n },\n {\n value: '5d'\n },\n {\n value: '7d'\n },\n {\n value: '14d'\n },\n {\n value: '30d'\n },\n {\n value: '60d'\n },\n {\n value: '90d'\n },\n {\n value: '99y'\n }\n]","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useState } from 'react';\nimport { Button } from 'antd';\nimport { ReloadOutlined } from '@ant-design/icons';\nimport { useTranslation } from 'react-i18next';\nimport './index.less';\ninterface Props {\n onClick: () => void;\n className?: string;\n}\nexport default function RefreshIcon(props: Props) {\n const { t } = useTranslation();\n const { onClick, className } = props;\n const [refreshing, setRefreshing] = useState(false);\n\n const handleRefresh = (e) => {\n if (refreshing) return;\n setRefreshing(true);\n onClick();\n setTimeout(() => {\n setRefreshing(false);\n }, 1000);\n };\n\n return (\n }\n >\n );\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React from 'react';\nimport { Tag, TagProps } from 'antd';\nimport { useTranslation } from 'react-i18next';\ninterface IColorTagProps {\n text: string;\n}\nconst tagColors = ['purple', 'lime', 'green', 'cyan'];\n\nconst ColorTag: React.FC = ({ text, ...props }) => {\n const { t } = useTranslation();\n const sumCharCode: number = Array.from(text).reduce((prev: number, item: string) => {\n return prev + item.charCodeAt(0);\n }, 0);\n return (\n \n {text}\n \n );\n};\n\nexport default ColorTag;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useRef, ReactNode, isValidElement, useEffect, useState } from 'react';\nimport { useSelector } from 'react-redux';\nimport { RootState } from '@/store/common';\nimport { CommonStoreState } from '@/store/commonInterface';\nimport { download, copyToClipBoard } from '@/utils';\nimport { Button, Modal, Form, Input, message, Table, Select, Divider, Row, Col } from 'antd';\n\nconst { Option } = Select;\nimport './index.less';\nimport { useTranslation } from 'react-i18next';\nimport { CopyOutlined, CheckCircleOutlined, CloseCircleOutlined, CaretDownOutlined, SearchOutlined } from '@ant-design/icons';\nimport { stringify } from 'querystring';\nconst { TextArea } = Input;\nexport const enum ModalStatus {\n Import = 'import',\n Export = 'export',\n BuiltIn = 'builtin',\n None = 'hide',\n}\ninterface Props {\n bgid?: number;\n title: string | ReactNode;\n fetchBuiltinFunc?: Function;\n submitBuiltinFunc?: (name: string, cluster: string, id: number) => Promise;\n label?: string;\n crossCluster?: boolean;\n description?: string;\n status: ModalStatus;\n exportData: string;\n onClose: () => void;\n onSuccess?: () => void;\n onSubmit: Function;\n}\n\nexport default function ImportAndDownloadModal(props: Props) {\n const { t } = useTranslation();\n const exportTextRef = useRef(null as any);\n const { status, title, exportData, description, onClose, onSubmit, crossCluster = true, onSuccess, label, fetchBuiltinFunc, submitBuiltinFunc, bgid } = props;\n const [form] = Form.useForm();\n const { clusters: clusterList } = useSelector((state) => state.common);\n const [allList, setAllList] = useState<{ name: string }[]>([]);\n const [buildinList, setBuildinList] = useState<{ name: string }[]>([]);\n const [importResult, setImportResult] = useState<{ name: string; isTrue: boolean; msg: string }[]>();\n const columns = [\n {\n title: label,\n dataIndex: 'name',\n },\n {\n title: '导入结果',\n dataIndex: 'isTrue',\n render: (data) => {\n return data ? : ;\n },\n },\n {\n title: '错误消息',\n dataIndex: 'msg',\n },\n ];\n const builtinColumn = [\n {\n title: `${label}名称`,\n dataIndex: 'name',\n },\n {\n title: '操作',\n dataIndex: 'id',\n render(id, record) {\n return (\n {\n submitBuiltinFunc &&\n submitBuiltinFunc(record.name, form.getFieldValue('cluster'), bgid!).then(({ dat }) => {\n setImportResult(\n Object.keys(dat).map((key) => {\n return {\n name: key,\n key: key,\n isTrue: !dat[key],\n msg: dat[key],\n };\n }),\n );\n });\n }}\n >\n 导入\n \n );\n },\n },\n ];\n const handleClose = () => {\n onClose();\n importResult && importResult.some((item) => item.isTrue) && onSuccess && onSuccess();\n };\n useEffect(() => {\n if (status === ModalStatus.BuiltIn || status == ModalStatus.Import) {\n fetchBuiltinFunc &&\n fetchBuiltinFunc().then((res) => {\n let arr = res.dat.map((name) => ({ name }));\n setBuildinList(arr);\n setAllList(arr);\n });\n }\n setImportResult(undefined);\n }, [status]);\n\n const handleExportTxt = () => {\n download([exportData], 'download.json');\n };\n const computeTitle = isValidElement(title) ? title : status === ModalStatus.Export ? t('导出') + title : t('导入') + title;\n\n return (\n \n \n {importResult ? (\n \n ) : (\n {\n await form.validateFields();\n const data = form.getFieldsValue();\n try {\n const importData = JSON.parse(data.import);\n if (!Array.isArray(importData)) {\n message.error(title + 'JSON需要时数组');\n return;\n }\n const requstBody = importData.map((item) => {\n return {\n ...item,\n cluster: crossCluster ? data.cluster : undefined,\n };\n });\n\n const dat = await onSubmit(requstBody);\n const dataSource = Object.keys(dat).map((key) => {\n return {\n name: key,\n key: key,\n isTrue: !dat[key],\n msg: dat[key],\n };\n });\n setImportResult(dataSource);\n // 每个业务各自处理onSubmit\n } catch (error) {\n message.error(t('数据有误:') + error);\n }\n }}\n >\n {t('确定')}\n \n )}\n \n )\n }\n onCancel={handleClose}\n afterClose={() => setImportResult(undefined)}\n visible={status !== 'hide'}\n width={600}\n >\n \n {description &&

{description}

}\n {status === ModalStatus.Export && (\n

\n Download.json\n copyToClipBoard(exportData, t)}>\n \n 复制JSON内容到剪贴板\n \n

\n )}\n \n {(() => {\n switch (status) {\n case ModalStatus.Export:\n return (\n
\n
{exportData}
\n
\n );\n\n case ModalStatus.BuiltIn:\n return (\n <>\n
\n {crossCluster && (\n \n \n \n )}\n \n }\n style={{ marginBottom: '8px' }}\n allowClear\n onChange={(e) => {\n let str = e.target.value;\n let filterArr: { name: string }[] = [];\n allList.forEach((el) => {\n if (el.name.toLowerCase().indexOf(str.toLowerCase()) != -1) filterArr.push(el);\n });\n setBuildinList(filterArr);\n }}\n />\n \n {importResult && (\n <>\n \n
\n \n )}\n \n );\n\n case ModalStatus.Import:\n return (\n <>\n \n {crossCluster ? (\n \n \n \n ) : null}\n \n \n \n \n {importResult && (\n <>\n \n
\n \n )}\n \n );\n }\n })()}\n \n );\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport request from '@/utils/request';\nimport { RequestMethod } from '@/store/common';\nimport { N9EAPI } from '../../config/constant';\n\n// 修改个人信息\nexport const getUserInfoList = function (params = {}) {\n return request(`/api/n9e/users`, {\n method: RequestMethod.Get,\n params,\n });\n};\nexport const getTeamInfoList = function (params?: { query: string; limit?: number }) {\n const data = params ? (params.limit ? params : { ...params, limit: 200 }) : { limit: 200 };\n return request(`/api/n9e/user-groups`, {\n method: RequestMethod.Get,\n params: data,\n });\n};\nexport const getBusinessTeamList = function (params = {}) {\n return request(`/api/n9e/busi-groups`, {\n method: RequestMethod.Get,\n params,\n });\n};\nexport const getBusinessTeamInfo = function (id: string) {\n return request(`/api/n9e/busi-group/${id}`, {\n method: RequestMethod.Get,\n }).then((res) => res && res.dat);\n};\nexport const createBusinessTeam = function (data: object) {\n return request(`/api/n9e/busi-groups`, {\n method: RequestMethod.Post,\n data,\n }).then((res) => res && res.dat);\n};\nexport const changeBusinessTeam = function (id: string, data: object) {\n return request(`/api/n9e/busi-group/${id}`, {\n method: RequestMethod.Put,\n data,\n }).then((res) => res && res.dat);\n};\n\nexport const deleteBusinessTeamMember = function (id: string, data: object) {\n return request(`/api/n9e/busi-group/${id}/members`, {\n method: RequestMethod.Delete,\n data,\n }).then((res) => res && res.dat);\n};\n\nexport const deleteBusinessTeam = function (id: string) {\n return request(`/api/n9e/busi-group/${id}`, {\n method: RequestMethod.Delete,\n }).then((res) => res && res.dat);\n};\n\nexport const addBusinessMember = function (id: string, data: object) {\n return request(`/api/n9e/busi-group/${id}/members`, {\n method: RequestMethod.Post,\n data,\n }).then((res) => res && res.dat);\n};\n\nexport const createUser = function (data: object) {\n return request(`/api/n9e/users`, {\n method: RequestMethod.Post,\n data,\n }).then((res) => res && res.dat);\n};\nexport const createTeam = function (data: object) {\n return request(`/api/n9e/user-groups`, {\n method: RequestMethod.Post,\n data,\n }).then((res) => res && res.dat);\n};\nexport const getUserInfo = function (id: string) {\n return request(`/api/n9e/user/${id}/profile`, {\n method: RequestMethod.Get,\n }).then((res) => res && res.dat);\n};\nexport const getTeamInfo = function (id: string) {\n return request(`/api/n9e/user-group/${id}`, {\n method: RequestMethod.Get,\n }).then((res) => res && res.dat);\n};\nexport const changeUserInfo = function (id: string, data: object) {\n return request(`/api/n9e/user/${id}/profile`, {\n method: RequestMethod.Put,\n data,\n }).then((res) => res && res.dat);\n};\nexport const changeStatus = function (id: string, data: object) {\n return request(`/api/n9e/user/${id}/status`, {\n method: RequestMethod.Put,\n data,\n }).then((res) => res && res.dat);\n};\nexport const changeTeamInfo = function (id: string, data: object) {\n return request(`/api/n9e/user-group/${id}`, {\n method: RequestMethod.Put,\n data,\n }).then((res) => res && res.dat);\n};\nexport const changeUserPassword = function (id: string, data: object) {\n return request(`/api/n9e/user/${id}/password`, {\n method: RequestMethod.Put,\n data,\n }).then((res) => res && res.dat);\n};\nexport const disabledUser = function (id: string, data: object) {\n return request(`/api/n9e/user/${id}/password`, {\n method: RequestMethod.Put,\n data,\n }).then((res) => res && res.dat);\n};\nexport const deleteUser = function (id: string) {\n return request(`/api/n9e/user/${id}`, {\n method: RequestMethod.Delete,\n }).then((res) => res && res.dat);\n};\nexport const deleteTeam = function (id: string) {\n return request(`/api/n9e/user-group/${id}`, {\n method: RequestMethod.Delete,\n }).then((res) => res && res.dat);\n};\nexport const deleteMember = function (id: string, data: object) {\n return request(`/api/n9e/user-group/${id}/members`, {\n method: RequestMethod.Delete,\n data,\n }).then((res) => res && res.dat);\n};\nexport const addTeamUser = function (id: string, data: object) {\n return request(`/api/n9e/user-group/${id}/members`, {\n method: RequestMethod.Post,\n data,\n }).then((res) => res && res.dat);\n};\nexport const getNotifiesList = function () {\n return request(`/api/n9e/notify-channels`, {\n method: RequestMethod.Get,\n }).then((res) => res && res.dat);\n};\n\nexport const getContactsList = function () {\n return request(`/api/n9e/contact-channels`, {\n method: RequestMethod.Get,\n }).then((res) => res && res.dat);\n};\n\nexport const getNotifyChannels = function () {\n return request(`/api/n9e/contact-keys`, {\n method: RequestMethod.Get,\n }).then((res) => res && res.dat);\n};\n\nexport const getRoles = function () {\n return request(`/api/n9e/roles`, {\n method: RequestMethod.Get,\n }).then((res) => res && res.dat);\n};\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React from 'react';\nimport { Switch } from 'antd';\n\ninterface Props {\n label: string;\n checked?: boolean;\n onChange?: (value: boolean) => void;\n}\n\nexport const SwitchWithLabel: React.FC = ({ checked, onChange, label }) => {\n return (\n <>\n \n {label}\n \n );\n};\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport { HighlightStyle, tags } from '@codemirror/highlight';\nimport { EditorView } from '@codemirror/view';\n\nexport const baseTheme = EditorView.theme({\n '.cm-content': {\n padding: 0,\n },\n '&.cm-editor.cm-focused': {\n outline: 'unset',\n },\n '.cm-scroller': {\n overflow: 'hidden',\n fontFamily: 'verdana, Microsoft YaHei, Consolas, Deja Vu Sans Mono, Bitstream Vera Sans Mono;',\n lineHeight: 'unset', // input group 里不能设置 lineHeight\n },\n '.cm-matchingBracket': {\n color: '#000',\n backgroundColor: '#dedede',\n fontWeight: 'bold',\n outline: '1px dashed transparent',\n },\n '.cm-nonmatchingBracket': { borderColor: 'red' },\n\n '.cm-tooltip.cm-tooltip-autocomplete': {\n '& > ul': {\n maxHeight: '350px',\n fontFamily: '\"DejaVu Sans Mono\", monospace',\n maxWidth: 'unset',\n },\n '& > ul > li': {\n padding: '2px 1em 2px 3px',\n overflowY: 'hidden',\n },\n '& > ul > li[aria-selected]': {\n backgroundColor: '#a7d0f2',\n color: 'unset',\n },\n minWidth: '30%',\n },\n\n '.cm-completionDetail': {\n float: 'right',\n color: '#999',\n },\n\n '.cm-tooltip.cm-completionInfo': {\n marginTop: '-11px',\n padding: '10px',\n fontFamily: \"'Open Sans', 'Lucida Sans Unicode', 'Lucida Grande', sans-serif;\",\n border: 'none',\n minWidth: '250px',\n maxWidth: 'min-content',\n },\n\n '.cm-completionInfo.cm-completionInfo-right': {\n '&:before': {\n content: \"' '\",\n height: '0',\n position: 'absolute',\n width: '0',\n left: '-20px',\n borderWidth: '10px',\n borderStyle: 'solid',\n borderColor: 'transparent',\n },\n marginLeft: '12px',\n },\n '.cm-completionInfo.cm-completionInfo-left': {\n '&:before': {\n content: \"' '\",\n height: '0',\n position: 'absolute',\n width: '0',\n right: '-20px',\n borderWidth: '10px',\n borderStyle: 'solid',\n borderColor: 'transparent',\n },\n marginRight: '12px',\n },\n\n '.cm-completionMatchedText': {\n textDecoration: 'none',\n fontWeight: 'bold',\n color: '#0066bf',\n },\n\n '.cm-selectionMatch': {\n backgroundColor: '#e6f3ff',\n },\n\n '.cm-diagnostic': {\n '&.cm-diagnostic-error': {\n borderLeft: '3px solid #e65013',\n },\n },\n\n '.cm-completionIcon': {\n boxSizing: 'content-box',\n fontSize: '16px',\n lineHeight: '1',\n marginRight: '10px',\n verticalAlign: 'top',\n '&:after': { content: \"'\\\\ea88'\" },\n fontFamily: 'codicon',\n paddingRight: '0',\n opacity: '1',\n color: '#007acc',\n },\n\n '.cm-completionIcon-function, .cm-completionIcon-method': {\n '&:after': { content: \"'\\\\ea8c'\" },\n color: '#652d90',\n },\n '.cm-completionIcon-class': {\n '&:after': { content: \"'○'\" },\n },\n '.cm-completionIcon-interface': {\n '&:after': { content: \"'◌'\" },\n },\n '.cm-completionIcon-variable': {\n '&:after': { content: \"'𝑥'\" },\n },\n '.cm-completionIcon-constant': {\n '&:after': { content: \"'\\\\eb5f'\" },\n color: '#007acc',\n },\n '.cm-completionIcon-type': {\n '&:after': { content: \"'𝑡'\" },\n },\n '.cm-completionIcon-enum': {\n '&:after': { content: \"'∪'\" },\n },\n '.cm-completionIcon-property': {\n '&:after': { content: \"'□'\" },\n },\n '.cm-completionIcon-keyword': {\n '&:after': { content: \"'\\\\eb62'\" },\n color: '#616161',\n },\n '.cm-completionIcon-namespace': {\n '&:after': { content: \"'▢'\" },\n },\n '.cm-completionIcon-text': {\n '&:after': { content: \"'\\\\ea95'\" },\n color: '#ee9d28',\n },\n});\n\nexport const lightTheme = EditorView.theme(\n {\n '.cm-tooltip': {\n backgroundColor: '#f8f8f8',\n borderColor: 'rgba(52, 79, 113, 0.2)',\n },\n\n '.cm-tooltip.cm-tooltip-autocomplete': {\n '& li:hover': {\n backgroundColor: '#ddd',\n },\n '& > ul > li[aria-selected]': {\n backgroundColor: '#d6ebff',\n color: 'unset',\n },\n },\n\n '.cm-tooltip.cm-completionInfo': {\n backgroundColor: '#d6ebff',\n },\n\n '.cm-tooltip > .cm-completionInfo.cm-completionInfo-right': {\n '&:before': {\n borderRightColor: '#d6ebff',\n },\n },\n '.cm-tooltip > .cm-completionInfo.cm-completionInfo-left': {\n '&:before': {\n borderLeftColor: '#d6ebff',\n },\n },\n\n '.cm-line': {\n '&::selection': {\n backgroundColor: '#add6ff',\n },\n '& > span::selection': {\n backgroundColor: '#add6ff',\n },\n },\n },\n { dark: false },\n);\n\nexport const darkTheme = EditorView.theme(\n {\n '.cm-content': {\n caretColor: '#fff',\n },\n\n '.cm-tooltip.cm-completionInfo': {\n backgroundColor: '#333338',\n },\n\n '.cm-tooltip > .cm-completionInfo.cm-completionInfo-right': {\n '&:before': {\n borderRightColor: '#333338',\n },\n },\n '.cm-tooltip > .cm-completionInfo.cm-completionInfo-left': {\n '&:before': {\n borderLeftColor: '#333338',\n },\n },\n\n '.cm-line': {\n '&::selection': {\n backgroundColor: '#767676',\n },\n '& > span::selection': {\n backgroundColor: '#767676',\n },\n },\n },\n { dark: true },\n);\n\nexport const promqlHighlighter = HighlightStyle.define([\n { tag: tags.name, color: '#000' },\n { tag: tags.number, color: '#09885a' },\n { tag: tags.string, color: '#a31515' },\n { tag: tags.keyword, color: '#008080' },\n { tag: tags.function(tags.variableName), color: '#008080' },\n { tag: tags.labelName, color: '#800000' },\n { tag: tags.operator },\n { tag: tags.modifier, color: '#008080' },\n { tag: tags.paren },\n { tag: tags.squareBracket },\n { tag: tags.brace },\n { tag: tags.invalid, color: 'red' },\n { tag: tags.comment, color: '#888', fontStyle: 'italic' },\n]);\n","function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n \"default\": obj\n };\n}\n\nmodule.exports = _interopRequireDefault;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = {\n // Options.jsx\n items_per_page: '条/页',\n jump_to: '跳至',\n jump_to_confirm: '确定',\n page: '页',\n // Pagination.jsx\n prev_page: '上一页',\n next_page: '下一页',\n prev_5: '向前 5 页',\n next_5: '向后 5 页',\n prev_3: '向前 3 页',\n next_3: '向后 3 页',\n page_size: '页码'\n};\nexports.default = _default;","function _extends() {\n module.exports = _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n module.exports[\"default\"] = module.exports, module.exports.__esModule = true;\n return _extends.apply(this, arguments);\n}\n\nmodule.exports = _extends;\nmodule.exports[\"default\"] = module.exports, module.exports.__esModule = true;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar locale = {\n locale: 'zh_CN',\n today: '今天',\n now: '此刻',\n backToToday: '返回今天',\n ok: '确定',\n timeSelect: '选择时间',\n dateSelect: '选择日期',\n weekSelect: '选择周',\n clear: '清除',\n month: '月',\n year: '年',\n previousMonth: '上个月 (翻页上键)',\n nextMonth: '下个月 (翻页下键)',\n monthSelect: '选择月份',\n yearSelect: '选择年份',\n decadeSelect: '选择年代',\n yearFormat: 'YYYY年',\n dayFormat: 'D日',\n dateFormat: 'YYYY年M月D日',\n dateTimeFormat: 'YYYY年M月D日 HH时mm分ss秒',\n previousYear: '上一年 (Control键加左方向键)',\n nextYear: '下一年 (Control键加右方向键)',\n previousDecade: '上一年代',\n nextDecade: '下一年代',\n previousCentury: '上一世纪',\n nextCentury: '下一世纪'\n};\nvar _default = locale;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar locale = {\n placeholder: '请选择时间',\n rangePlaceholder: ['开始时间', '结束时间']\n};\nvar _default = locale;\nexports[\"default\"] = _default;","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _zh_CN = _interopRequireDefault(require(\"rc-picker/lib/locale/zh_CN\"));\n\nvar _zh_CN2 = _interopRequireDefault(require(\"../../time-picker/locale/zh_CN\"));\n\n// 统一合并为完整的 Locale\nvar locale = {\n lang: (0, _extends2[\"default\"])({\n placeholder: '请选择日期',\n yearPlaceholder: '请选择年份',\n quarterPlaceholder: '请选择季度',\n monthPlaceholder: '请选择月份',\n weekPlaceholder: '请选择周',\n rangePlaceholder: ['开始日期', '结束日期'],\n rangeYearPlaceholder: ['开始年份', '结束年份'],\n rangeMonthPlaceholder: ['开始月份', '结束月份'],\n rangeWeekPlaceholder: ['开始周', '结束周']\n }, _zh_CN[\"default\"]),\n timePickerLocale: (0, _extends2[\"default\"])({}, _zh_CN2[\"default\"])\n}; // should add whitespace between char in Button\n\nlocale.lang.ok = '确定'; // All settings at:\n// https://github.com/ant-design/ant-design/blob/master/components/date-picker/locale/example.json\n\nvar _default = locale;\nexports[\"default\"] = _default;","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\n\nvar _zh_CN = _interopRequireDefault(require(\"../../date-picker/locale/zh_CN\"));\n\nvar _default = _zh_CN[\"default\"];\nexports[\"default\"] = _default;","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\n\nvar _zh_CN = _interopRequireDefault(require(\"rc-pagination/lib/locale/zh_CN\"));\n\nvar _zh_CN2 = _interopRequireDefault(require(\"../date-picker/locale/zh_CN\"));\n\nvar _zh_CN3 = _interopRequireDefault(require(\"../time-picker/locale/zh_CN\"));\n\nvar _zh_CN4 = _interopRequireDefault(require(\"../calendar/locale/zh_CN\"));\n\n/* eslint-disable no-template-curly-in-string */\nvar typeTemplate = '${label}不是一个有效的${type}';\nvar localeValues = {\n locale: 'zh-cn',\n Pagination: _zh_CN[\"default\"],\n DatePicker: _zh_CN2[\"default\"],\n TimePicker: _zh_CN3[\"default\"],\n Calendar: _zh_CN4[\"default\"],\n // locales for all components\n global: {\n placeholder: '请选择'\n },\n Table: {\n filterTitle: '筛选',\n filterConfirm: '确定',\n filterReset: '重置',\n filterEmptyText: '无筛选项',\n filterCheckall: '全选',\n filterSearchPlaceholder: '在筛选项中搜索',\n selectAll: '全选当页',\n selectInvert: '反选当页',\n selectNone: '清空所有',\n selectionAll: '全选所有',\n sortTitle: '排序',\n expand: '展开行',\n collapse: '关闭行',\n triggerDesc: '点击降序',\n triggerAsc: '点击升序',\n cancelSort: '取消排序'\n },\n Modal: {\n okText: '确定',\n cancelText: '取消',\n justOkText: '知道了'\n },\n Popconfirm: {\n cancelText: '取消',\n okText: '确定'\n },\n Transfer: {\n searchPlaceholder: '请输入搜索内容',\n itemUnit: '项',\n itemsUnit: '项',\n remove: '删除',\n selectCurrent: '全选当页',\n removeCurrent: '删除当页',\n selectAll: '全选所有',\n removeAll: '删除全部',\n selectInvert: '反选当页'\n },\n Upload: {\n uploading: '文件上传中',\n removeFile: '删除文件',\n uploadError: '上传错误',\n previewFile: '预览文件',\n downloadFile: '下载文件'\n },\n Empty: {\n description: '暂无数据'\n },\n Icon: {\n icon: '图标'\n },\n Text: {\n edit: '编辑',\n copy: '复制',\n copied: '复制成功',\n expand: '展开'\n },\n PageHeader: {\n back: '返回'\n },\n Form: {\n optional: '(可选)',\n defaultValidateMessages: {\n \"default\": '字段验证错误${label}',\n required: '请输入${label}',\n \"enum\": '${label}必须是其中一个[${enum}]',\n whitespace: '${label}不能为空字符',\n date: {\n format: '${label}日期格式无效',\n parse: '${label}不能转换为日期',\n invalid: '${label}是一个无效日期'\n },\n types: {\n string: typeTemplate,\n method: typeTemplate,\n array: typeTemplate,\n object: typeTemplate,\n number: typeTemplate,\n date: typeTemplate,\n \"boolean\": typeTemplate,\n integer: typeTemplate,\n \"float\": typeTemplate,\n regexp: typeTemplate,\n email: typeTemplate,\n url: typeTemplate,\n hex: typeTemplate\n },\n string: {\n len: '${label}须为${len}个字符',\n min: '${label}最少${min}个字符',\n max: '${label}最多${max}个字符',\n range: '${label}须在${min}-${max}字符之间'\n },\n number: {\n len: '${label}必须等于${len}',\n min: '${label}最小值为${min}',\n max: '${label}最大值为${max}',\n range: '${label}须在${min}-${max}之间'\n },\n array: {\n len: '须为${len}个${label}',\n min: '最少${min}个${label}',\n max: '最多${max}个${label}',\n range: '${label}数量须在${min}-${max}之间'\n },\n pattern: {\n mismatch: '${label}与模式不匹配${pattern}'\n }\n }\n },\n Image: {\n preview: '预览'\n }\n};\nvar _default = localeValues;\nexports[\"default\"] = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = {\n // Options.jsx\n items_per_page: '/ page',\n jump_to: 'Go to',\n jump_to_confirm: 'confirm',\n page: 'Page',\n // Pagination.jsx\n prev_page: 'Previous Page',\n next_page: 'Next Page',\n prev_5: 'Previous 5 Pages',\n next_5: 'Next 5 Pages',\n prev_3: 'Previous 3 Pages',\n next_3: 'Next 3 Pages',\n page_size: 'Page Size'\n};\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar locale = {\n locale: 'en_US',\n today: 'Today',\n now: 'Now',\n backToToday: 'Back to today',\n ok: 'Ok',\n clear: 'Clear',\n month: 'Month',\n year: 'Year',\n timeSelect: 'select time',\n dateSelect: 'select date',\n weekSelect: 'Choose a week',\n monthSelect: 'Choose a month',\n yearSelect: 'Choose a year',\n decadeSelect: 'Choose a decade',\n yearFormat: 'YYYY',\n dateFormat: 'M/D/YYYY',\n dayFormat: 'D',\n dateTimeFormat: 'M/D/YYYY HH:mm:ss',\n monthBeforeYear: true,\n previousMonth: 'Previous month (PageUp)',\n nextMonth: 'Next month (PageDown)',\n previousYear: 'Last year (Control + left)',\n nextYear: 'Next year (Control + right)',\n previousDecade: 'Last decade',\n nextDecade: 'Next decade',\n previousCentury: 'Last century',\n nextCentury: 'Next century'\n};\nvar _default = locale;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar locale = {\n placeholder: 'Select time',\n rangePlaceholder: ['Start time', 'End time']\n};\nvar _default = locale;\nexports[\"default\"] = _default;","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\n\nvar _extends2 = _interopRequireDefault(require(\"@babel/runtime/helpers/extends\"));\n\nvar _en_US = _interopRequireDefault(require(\"rc-picker/lib/locale/en_US\"));\n\nvar _en_US2 = _interopRequireDefault(require(\"../../time-picker/locale/en_US\"));\n\n// Merge into a locale object\nvar locale = {\n lang: (0, _extends2[\"default\"])({\n placeholder: 'Select date',\n yearPlaceholder: 'Select year',\n quarterPlaceholder: 'Select quarter',\n monthPlaceholder: 'Select month',\n weekPlaceholder: 'Select week',\n rangePlaceholder: ['Start date', 'End date'],\n rangeYearPlaceholder: ['Start year', 'End year'],\n rangeMonthPlaceholder: ['Start month', 'End month'],\n rangeWeekPlaceholder: ['Start week', 'End week']\n }, _en_US[\"default\"]),\n timePickerLocale: (0, _extends2[\"default\"])({}, _en_US2[\"default\"])\n}; // All settings at:\n// https://github.com/ant-design/ant-design/blob/master/components/date-picker/locale/example.json\n\nvar _default = locale;\nexports[\"default\"] = _default;","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\n\nvar _en_US = _interopRequireDefault(require(\"../../date-picker/locale/en_US\"));\n\nvar _default = _en_US[\"default\"];\nexports[\"default\"] = _default;","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\n\nvar _en_US = _interopRequireDefault(require(\"rc-pagination/lib/locale/en_US\"));\n\nvar _en_US2 = _interopRequireDefault(require(\"../date-picker/locale/en_US\"));\n\nvar _en_US3 = _interopRequireDefault(require(\"../time-picker/locale/en_US\"));\n\nvar _en_US4 = _interopRequireDefault(require(\"../calendar/locale/en_US\"));\n\n/* eslint-disable no-template-curly-in-string */\nvar typeTemplate = '${label} is not a valid ${type}';\nvar localeValues = {\n locale: 'en',\n Pagination: _en_US[\"default\"],\n DatePicker: _en_US2[\"default\"],\n TimePicker: _en_US3[\"default\"],\n Calendar: _en_US4[\"default\"],\n global: {\n placeholder: 'Please select'\n },\n Table: {\n filterTitle: 'Filter menu',\n filterConfirm: 'OK',\n filterReset: 'Reset',\n filterEmptyText: 'No filters',\n filterCheckall: 'Select all items',\n filterSearchPlaceholder: 'Search in filters',\n emptyText: 'No data',\n selectAll: 'Select current page',\n selectInvert: 'Invert current page',\n selectNone: 'Clear all data',\n selectionAll: 'Select all data',\n sortTitle: 'Sort',\n expand: 'Expand row',\n collapse: 'Collapse row',\n triggerDesc: 'Click to sort descending',\n triggerAsc: 'Click to sort ascending',\n cancelSort: 'Click to cancel sorting'\n },\n Modal: {\n okText: 'OK',\n cancelText: 'Cancel',\n justOkText: 'OK'\n },\n Popconfirm: {\n okText: 'OK',\n cancelText: 'Cancel'\n },\n Transfer: {\n titles: ['', ''],\n searchPlaceholder: 'Search here',\n itemUnit: 'item',\n itemsUnit: 'items',\n remove: 'Remove',\n selectCurrent: 'Select current page',\n removeCurrent: 'Remove current page',\n selectAll: 'Select all data',\n removeAll: 'Remove all data',\n selectInvert: 'Invert current page'\n },\n Upload: {\n uploading: 'Uploading...',\n removeFile: 'Remove file',\n uploadError: 'Upload error',\n previewFile: 'Preview file',\n downloadFile: 'Download file'\n },\n Empty: {\n description: 'No Data'\n },\n Icon: {\n icon: 'icon'\n },\n Text: {\n edit: 'Edit',\n copy: 'Copy',\n copied: 'Copied',\n expand: 'Expand'\n },\n PageHeader: {\n back: 'Back'\n },\n Form: {\n optional: '(optional)',\n defaultValidateMessages: {\n \"default\": 'Field validation error for ${label}',\n required: 'Please enter ${label}',\n \"enum\": '${label} must be one of [${enum}]',\n whitespace: '${label} cannot be a blank character',\n date: {\n format: '${label} date format is invalid',\n parse: '${label} cannot be converted to a date',\n invalid: '${label} is an invalid date'\n },\n types: {\n string: typeTemplate,\n method: typeTemplate,\n array: typeTemplate,\n object: typeTemplate,\n number: typeTemplate,\n date: typeTemplate,\n \"boolean\": typeTemplate,\n integer: typeTemplate,\n \"float\": typeTemplate,\n regexp: typeTemplate,\n email: typeTemplate,\n url: typeTemplate,\n hex: typeTemplate\n },\n string: {\n len: '${label} must be ${len} characters',\n min: '${label} must be at least ${min} characters',\n max: '${label} must be up to ${max} characters',\n range: '${label} must be between ${min}-${max} characters'\n },\n number: {\n len: '${label} must be equal to ${len}',\n min: '${label} must be minimum ${min}',\n max: '${label} must be maximum ${max}',\n range: '${label} must be between ${min}-${max}'\n },\n array: {\n len: 'Must be ${len} ${label}',\n min: 'At least ${min} ${label}',\n max: 'At most ${max} ${label}',\n range: 'The amount of ${label} must be between ${min}-${max}'\n },\n pattern: {\n mismatch: '${label} does not match the pattern ${pattern}'\n }\n }\n },\n Image: {\n preview: 'Preview'\n }\n};\nvar _default = localeValues;\nexports[\"default\"] = _default;","\"use strict\";\n\nvar _interopRequireDefault = require(\"@babel/runtime/helpers/interopRequireDefault\");\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\n\nvar _default2 = _interopRequireDefault(require(\"./default\"));\n\nvar _default = _default2[\"default\"];\nexports[\"default\"] = _default;","import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { BrowserRouter as Router } from 'react-router-dom';\nimport _ from 'lodash';\nimport { ConfigProvider } from 'antd';\nimport antdZhCN from 'antd/lib/locale/zh_CN';\nimport antdEnUS from 'antd/lib/locale/en_US';\n\nexport interface ModalWrapProps {\n visible: boolean;\n destroy: () => void;\n onOk: (...args: any[]) => void;\n onCancel: () => void;\n}\n\nexport default function ModalHOC(Component: React.FC) {\n return function ModalControl(\n config: T & {\n language?: string;\n },\n ) {\n const div = document.createElement('div');\n document.body.appendChild(div);\n\n function destroy() {\n const unmountResult = ReactDOM.unmountComponentAtNode(div);\n if (unmountResult && div.parentNode) {\n div.parentNode.removeChild(div);\n }\n }\n\n function render(props: any) {\n ReactDOM.render(\n \n \n \n \n ,\n div,\n );\n }\n\n render({ ...config, visible: true, destroy });\n\n return {\n destroy,\n };\n };\n}\n\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport { ITimeOption, TDurationUnit } from './types';\n\nexport const spans: { [key: string]: { display: string; section?: number; displayZh: string } } = {\n s: { display: 'second', displayZh: '秒' },\n m: { display: 'minute', displayZh: '分钟' },\n h: { display: 'hour', displayZh: '小时' },\n d: { display: 'day', displayZh: '天' },\n w: { display: 'week', displayZh: '周' },\n M: { display: 'month', displayZh: '月' },\n y: { display: 'year', displayZh: '年' },\n};\n\nexport const rangeOptions: ITimeOption[] = [\n { start: 'now-1m', end: 'now', display: 'Last 1 minutes', displayZh: '最近 1 分钟' },\n { start: 'now-2m', end: 'now', display: 'Last 2 minutes', displayZh: '最近 2 分钟' },\n { start: 'now-3m', end: 'now', display: 'Last 3 minutes', displayZh: '最近 3 分钟' },\n { start: 'now-5m', end: 'now', display: 'Last 5 minutes', displayZh: '最近 5 分钟' },\n { start: 'now-15m', end: 'now', display: 'Last 15 minutes', displayZh: '最近 15 分钟' },\n { start: 'now-30m', end: 'now', display: 'Last 30 minutes', displayZh: '最近 30 分钟' },\n { start: 'now-1h', end: 'now', display: 'Last 1 hour', displayZh: '最近 1 小时' },\n { start: 'now-3h', end: 'now', display: 'Last 3 hours', displayZh: '最近 3 小时' },\n { start: 'now-6h', end: 'now', display: 'Last 6 hours', displayZh: '最近 6 小时' },\n { start: 'now-12h', end: 'now', display: 'Last 12 hours', displayZh: '最近 12 小时' },\n { start: 'now-24h', end: 'now', display: 'Last 24 hours', displayZh: '最近 24 小时' },\n { start: 'now-2d', end: 'now', display: 'Last 2 days', displayZh: '最近 2 天' },\n { start: 'now-7d', end: 'now', display: 'Last 7 days', displayZh: '最近 7 天' },\n { start: 'now-30d', end: 'now', display: 'Last 30 days', displayZh: '最近 30 天' },\n { start: 'now-90d', end: 'now', display: 'Last 90 days', displayZh: '最近 90 天' },\n { start: 'now-1d/d', end: 'now-1d/d', display: 'Yesterday', displayZh: '昨天' },\n {\n start: 'now-2d/d',\n end: 'now-2d/d',\n display: 'Day before yesterday',\n displayZh: '前天',\n },\n {\n start: 'now-7d/d',\n end: 'now-7d/d',\n display: 'This day last week',\n displayZh: '上周今天',\n },\n { start: 'now-1w/w', end: 'now-1w/w', display: 'Previous week', displayZh: '上周' },\n { start: 'now-1M/M', end: 'now-1M/M', display: 'Previous month', displayZh: '上个月' },\n { start: 'now/d', end: 'now/d', display: 'Today', displayZh: '今天' },\n { start: 'now/d', end: 'now', display: 'Today so far', displayZh: '今天到现在' },\n { start: 'now/w', end: 'now/w', display: 'This week', displayZh: '本周' },\n { start: 'now/w', end: 'now', display: 'This week so far', displayZh: '本周到现在' },\n { start: 'now/M', end: 'now/M', display: 'This month', displayZh: '本月' },\n { start: 'now/M', end: 'now', display: 'This month so far', displayZh: '本月到现在' },\n];\n\nexport const momentLocaleZhCN = {\n months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),\n monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),\n weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),\n weekdaysShort: '周日_周一_周二_周三_周四_周五_周六'.split('_'),\n weekdaysMin: '日_一_二_三_四_五_六'.split('_'),\n};\n\nexport const units: TDurationUnit[] = ['y', 'M', 'w', 'd', 'h', 'm', 's', 'Q'];\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport _, { includes, isDate } from 'lodash';\nimport moment, { Moment } from 'moment';\nimport { IRawTimeRange } from './types';\nimport { spans, rangeOptions, units } from './config';\n\nexport function isMathString(text: string | Moment | Date): boolean {\n if (!text) {\n return false;\n }\n\n if (typeof text === 'string' && (text.substring(0, 3) === 'now' || text.includes('||'))) {\n return true;\n } else {\n return false;\n }\n}\n\nexport function parse(text?: string | Moment | Date | null, roundUp?: boolean): Moment | undefined {\n if (!text) {\n return undefined;\n }\n\n if (typeof text !== 'string') {\n if (moment.isMoment(text)) {\n return text;\n }\n if (isDate(text)) {\n return moment(text);\n }\n // We got some non string which is not a moment nor Date. TS should be able to check for that but not always.\n return undefined;\n } else {\n let time;\n let mathString = '';\n let index;\n let parseString;\n\n if (text.substring(0, 3) === 'now') {\n time = moment();\n mathString = text.substring('now'.length);\n } else {\n index = text.indexOf('||');\n if (index === -1) {\n parseString = text;\n mathString = ''; // nothing else\n } else {\n parseString = text.substring(0, index);\n mathString = text.substring(index + 2);\n }\n // We're going to just require ISO8601 timestamps, k?\n time = moment(parseString, moment.ISO_8601);\n }\n\n if (!mathString.length) {\n return time;\n }\n\n return parseDateMath(mathString, time, roundUp);\n }\n}\n\nexport function isValid(text: string | Moment): boolean {\n const date = parse(text);\n if (!date) {\n return false;\n }\n\n if (moment.isMoment(date)) {\n return date.isValid();\n }\n\n return false;\n}\n\nexport function parseDateMath(mathString: string, time: any, roundUp?: boolean): Moment | undefined {\n const strippedMathString = mathString.replace(/\\s/g, '');\n const dateTime = time;\n let i = 0;\n const len = strippedMathString.length;\n\n while (i < len) {\n const c = strippedMathString.charAt(i++);\n let type;\n let num;\n let unit;\n\n if (c === '/') {\n type = 0;\n } else if (c === '+') {\n type = 1;\n } else if (c === '-') {\n type = 2;\n } else {\n return undefined;\n }\n\n if (isNaN(parseInt(strippedMathString.charAt(i), 10))) {\n num = 1;\n } else if (strippedMathString.length === 2) {\n num = parseInt(strippedMathString.charAt(i), 10);\n } else {\n const numFrom = i;\n while (!isNaN(parseInt(strippedMathString.charAt(i), 10))) {\n i++;\n if (i > 10) {\n return undefined;\n }\n }\n num = parseInt(strippedMathString.substring(numFrom, i), 10);\n }\n\n if (type === 0) {\n // rounding is only allowed on whole, single, units (eg M or 1M, not 0.5M or 2M)\n if (num !== 1) {\n return undefined;\n }\n }\n unit = strippedMathString.charAt(i++);\n\n if (!includes(units, unit)) {\n return undefined;\n } else {\n if (type === 0) {\n if (roundUp) {\n dateTime.endOf(unit);\n } else {\n dateTime.startOf(unit);\n }\n } else if (type === 1) {\n dateTime.add(num, unit);\n } else if (type === 2) {\n dateTime.subtract(num, unit);\n }\n }\n }\n return dateTime;\n}\n\nconst rangeIndex: any = {};\n_.forEach(rangeOptions, (frame: any) => {\n rangeIndex[frame.start + ' ~ ' + frame.end] = frame;\n});\n\nexport function describeTextRange(expr: any) {\n const isLast = expr.indexOf('+') !== 0;\n if (expr.indexOf('now') === -1) {\n expr = (isLast ? 'now-' : 'now') + expr;\n }\n\n let opt = rangeIndex[expr + ' ~ now'];\n if (opt) {\n return opt;\n }\n\n if (isLast) {\n opt = { start: expr, end: 'now' };\n } else {\n opt = { start: 'now', end: expr };\n }\n\n const parts = /^now([-+])(\\d+)(\\w)/.exec(expr);\n if (parts) {\n const unit = parts[3];\n const amount = parseInt(parts[2], 10);\n const span = spans[unit];\n if (span) {\n opt.displayZh = isLast ? '最近 ' : '接下来 ';\n opt.displayZh += amount + ' ' + span.displayZh;\n opt.section = span.section;\n }\n } else {\n opt.displayZh = opt.start + ' ~ ' + opt.end;\n opt.invalid = true;\n }\n\n return opt;\n}\n\nexport function describeTimeRange(range: IRawTimeRange, dateFormat: string): string {\n const option = rangeIndex[range.start.toString() + ' ~ ' + range.end.toString()];\n\n if (option) {\n return option.displayZh;\n }\n\n if (moment.isMoment(range.start) && moment.isMoment(range.end)) {\n return moment(range.start).format(dateFormat) + ' ~ ' + moment(range.end).format(dateFormat);\n }\n\n if (moment.isMoment(range.start)) {\n const parsed = parse(range.end);\n return parsed ? moment(range.start).format(dateFormat) + ' ~ ' + range.end : '';\n }\n\n if (moment.isMoment(range.end)) {\n const parsed = parse(range.start);\n return parsed ? range.start + ' ~ ' + moment(range.end).format(dateFormat) : '';\n }\n\n if (range.end.toString() === 'now') {\n const res = describeTextRange(range.start);\n return res.displayZh;\n }\n\n return range.start.toString() + ' ~ ' + range.end.toString();\n}\n\nexport const valueAsString = (value: Moment | string, dateFormat: string) => {\n if (moment.isMoment(value)) {\n return value.format(dateFormat);\n }\n return value;\n};\n\nexport const parseRange = (range: IRawTimeRange) => {\n return {\n start: parse(range.start),\n end: parse(range.end, true),\n };\n};\n\nexport const timeRangeUnix = (range: IRawTimeRange) => {\n const parsedRange = parseRange(range);\n const start = moment(parsedRange.start).unix();\n const end = moment(parsedRange.end).unix();\n return {\n start,\n end,\n };\n};\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useState, useEffect } from 'react';\nimport { Button, Popover, Row, Col, Input } from 'antd';\nimport { DownOutlined, UpOutlined, CalendarOutlined, SearchOutlined, CloseCircleOutlined } from '@ant-design/icons';\nimport { PickerPanel } from 'rc-picker';\nimport momentGenerateConfig from 'rc-picker/es/generate/moment';\nimport zhCN from 'rc-picker/lib/locale/zh_CN';\nimport 'rc-picker/assets/index.css';\nimport classNames from 'classnames';\nimport moment, { Moment } from 'moment';\nimport _ from 'lodash';\nimport { isValid, describeTimeRange, valueAsString, isMathString } from './utils';\nimport { IRawTimeRange, ITimeRangePickerProps } from './types';\nimport { rangeOptions, momentLocaleZhCN } from './config';\nimport './style.less';\n\nmoment.locale('zh-cn', momentLocaleZhCN);\n\nconst absolutehistoryCacheKey = 'flashcat-timeRangePicker-absolute-history';\nconst getAbsoluteHistoryCache = () => {\n const cache = localStorage.getItem(absolutehistoryCacheKey);\n if (cache) {\n try {\n const list = _.unionWith(JSON.parse(cache), _.isEqual);\n return list;\n } catch (e) {\n console.log(e);\n return [];\n }\n }\n return [];\n};\nconst setAbsoluteHistoryCache = (range, dateFormat) => {\n const absoluteHistoryCache = getAbsoluteHistoryCache();\n const rangeClone = _.cloneDeep(range);\n rangeClone.start = valueAsString(rangeClone.start, dateFormat);\n rangeClone.end = valueAsString(rangeClone.end, dateFormat);\n const newAbsoluteHistoryCache = _.unionWith([rangeClone, ...absoluteHistoryCache], _.isEqual).slice(0, 4);\n try {\n const cacheStr = JSON.stringify(newAbsoluteHistoryCache);\n localStorage.setItem(absolutehistoryCacheKey, cacheStr);\n } catch (e) {\n console.log(e);\n }\n};\n\nexport default function index(props: ITimeRangePickerProps) {\n const absoluteHistoryCache = getAbsoluteHistoryCache();\n const { value, onChange = () => {}, dateFormat = 'YYYY-MM-DD HH:mm', placeholder = '请选择时间', allowClear = false, onClear = () => {}, extraFooter } = props;\n const [visible, setVisible] = useState(false);\n const [range, setRange] = useState();\n const [label, setLabel] = useState('');\n const [searchValue, setSearchValue] = useState('');\n const [rangeStatus, setRangeStatus] = useState<{\n start?: string;\n end?: string;\n }>({\n start: undefined,\n end: undefined,\n });\n const renderSinglePicker = (key: 'start' | 'end') => {\n const labelMap = {\n start: '开始时间',\n end: '结束时间',\n };\n const val = moment(range ? range[key] : undefined, true);\n return (\n
\n {labelMap[key]}\n \n document.body}\n content={\n {\n if (key === 'start') {\n return current && current.valueOf() > moment(range?.end, true).valueOf();\n }\n return current && current.valueOf() < moment(range?.start, true).valueOf();\n }}\n value={val.isValid() ? val : undefined}\n onChange={(value) => {\n const newRange = {\n ...(range || {}),\n [key]: value,\n };\n if (key === 'start' && !moment.isMoment(newRange.end)) {\n newRange.end = moment(newRange.start).endOf('day');\n }\n if (key === 'end' && !moment.isMoment(newRange.start)) {\n newRange.start = moment(newRange.end).startOf('day');\n }\n setRange(newRange as IRawTimeRange);\n setAbsoluteHistoryCache(newRange, dateFormat);\n }}\n />\n }\n >\n
\n );\n };\n\n useEffect(() => {\n if (value) {\n setRange(value);\n setLabel(describeTimeRange(value, dateFormat));\n }\n }, [JSON.stringify(value), visible]);\n\n return (\n <>\n \n
\n \n
\n
\n {renderSinglePicker('start')}\n {renderSinglePicker('end')}\n
\n 最近使用的时间范围\n
    \n {_.map(absoluteHistoryCache, (range, idx) => {\n return (\n {\n const newValue = {\n start: isMathString(range.start) ? range.start : moment(range.start),\n end: isMathString(range.end) ? range.end : moment(range.end),\n };\n setRange(newValue);\n onChange(newValue);\n setAbsoluteHistoryCache(newValue, dateFormat);\n setVisible(false);\n }}\n >\n {describeTimeRange(range, dateFormat)}\n \n );\n })}\n
\n
\n
\n \n \n
\n }\n value={searchValue}\n onChange={(e) => {\n setSearchValue(e.target.value);\n }}\n />\n
    \n {_.map(\n _.filter(rangeOptions, (item) => item.displayZh.indexOf(searchValue) > -1),\n (item) => {\n return (\n {\n const newValue = {\n start: item.start,\n end: item.end,\n };\n setRange(newValue);\n onChange(newValue);\n setVisible(false);\n setAbsoluteHistoryCache(newValue, dateFormat);\n }}\n >\n {item.displayZh}\n \n );\n },\n )}\n
\n
\n \n \n \n
\n {\n if (rangeStatus.start !== 'invalid' && rangeStatus.end !== 'invalid') {\n onChange(range as IRawTimeRange);\n setVisible(false);\n }\n }}\n >\n 确定\n \n {extraFooter && extraFooter(setVisible)}\n
\n \n }\n trigger='click'\n placement='bottomRight'\n visible={visible}\n onVisibleChange={(v) => {\n setVisible(v);\n }}\n >\n {\n setVisible(!visible);\n }}\n >\n {props.label || label || placeholder}\n {!props.label && (\n \n {visible ? : }\n {\n e.nativeEvent.stopImmediatePropagation();\n e.stopPropagation();\n setRange(undefined);\n setLabel('');\n onClear();\n }}\n />\n \n )}\n \n \n \n );\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useState, useEffect, useRef, useImperativeHandle } from 'react';\nimport { Dropdown, Button, Menu, Tooltip } from 'antd';\nimport { DownOutlined, UpOutlined, SyncOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport './style.less';\n\nconst refreshMap = {\n 0: 'off',\n 5: '5s',\n 10: '10s',\n 20: '20s',\n 30: '30s',\n 60: '1m',\n 120: '2m',\n 180: '3m',\n 300: '5m',\n 600: '10m',\n};\n\ninterface IProps {\n tooltip?: string;\n onRefresh: () => void;\n localKey?: string;\n intervalSeconds?: number;\n onIntervalSecondsChange?: (intervalSeconds: number) => void;\n}\n\nfunction Refresh(props: IProps, ref) {\n const intervalSecondsCache = props.localKey ? _.toNumber(window.localStorage.getItem(props.localKey)) : 0;\n const [intervalSeconds, setIntervalSeconds] = useState(props.intervalSeconds || intervalSecondsCache);\n const [visible, setVisible] = useState(false);\n const intervalRef = useRef();\n\n useEffect(() => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n }\n if (intervalSeconds) {\n intervalRef.current = setInterval(() => {\n props.onRefresh();\n }, intervalSeconds * 1000);\n }\n }, [intervalSeconds, props.onRefresh]);\n\n useEffect(() => {\n return () => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n }\n };\n }, []);\n\n useEffect(() => {\n setIntervalSeconds(props.intervalSeconds || intervalSecondsCache);\n }, [props.intervalSeconds]);\n\n useImperativeHandle(ref, () => ({\n closeRefresh() {\n setIntervalSeconds(0);\n props.localKey && window.localStorage.setItem(props.localKey, '0');\n },\n }));\n\n return (\n
\n \n \n \n
\n );\n}\n\nexport default React.forwardRef(Refresh);\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React from 'react';\nimport { Space } from 'antd';\nimport _ from 'lodash';\nimport AutoRefresh from './AutoRefresh';\nimport TimeRangePicker from './TimeRangePicker';\nimport { ITimeRangePickerWithRefreshProps } from './types';\nimport { valueAsString } from './utils';\n\nexport default function TimeRangePickerWithRefresh(props: ITimeRangePickerWithRefreshProps) {\n const { value, onChange, style, refreshTooltip, dateFormat = 'YYYY-MM-DD HH:mm', localKey } = props;\n\n return (\n \n {\n if (value && onChange) {\n onChange({\n ...value,\n refreshFlag: _.uniqueId('refreshFlag_ '),\n });\n }\n }}\n intervalSeconds={props.intervalSeconds}\n onIntervalSecondsChange={props.onIntervalSecondsChange}\n />\n {\n if (localKey) {\n localStorage.setItem(\n localKey,\n JSON.stringify({\n start: valueAsString(val.start, dateFormat),\n end: valueAsString(val.end, dateFormat),\n }),\n );\n }\n if (onChange) {\n onChange(val);\n }\n }}\n />\n \n );\n}\n","interface RelativeTimeRange {\n start: number;\n end: number;\n}\n\ninterface TimeOption {\n start: string;\n end: string;\n display?: string;\n}\n\nconst regex = /^now$|^now\\-(\\d{1,10})([wdhms])$/;\n\nexport const mapOptionToRelativeTimeRange = (option: TimeOption): RelativeTimeRange | undefined => {\n return {\n start: relativeToSeconds(option.start),\n end: relativeToSeconds(option.end),\n };\n};\n\nexport const mapRelativeTimeRangeToOption = (range: RelativeTimeRange): TimeOption => {\n const start = secondsToRelativeFormat(range.start);\n const end = secondsToRelativeFormat(range.end);\n\n return { start, end, display: `${start} to ${end}` };\n};\n\nexport type RangeValidation = {\n isValid: boolean;\n errorMessage?: string;\n};\n\nexport const isRangeValid = (relative: string, now = Date.now()): RangeValidation => {\n if (!isRelativeFormat(relative)) {\n return {\n isValid: false,\n errorMessage: 'Value not in relative time format.',\n };\n }\n\n const seconds = relativeToSeconds(relative);\n\n if (seconds > Math.ceil(now / 1000)) {\n return {\n isValid: false,\n errorMessage: 'Can not enter value prior to January 1, 1970.',\n };\n }\n\n return { isValid: true };\n};\n\nexport const isRelativeFormat = (format: string): boolean => {\n return regex.test(format);\n};\n\nconst relativeToSeconds = (relative: string): number => {\n const match = regex.exec(relative);\n\n if (!match || match.length !== 3) {\n return 0;\n }\n\n const [, value, unit] = match;\n const parsed = parseInt(value, 10);\n\n if (isNaN(parsed)) {\n return 0;\n }\n\n return parsed * units[unit];\n};\n\nconst units: Record = {\n w: 604800,\n d: 86400,\n h: 3600,\n m: 60,\n s: 1,\n};\n\nconst secondsToRelativeFormat = (seconds: number): string => {\n if (seconds <= 0) {\n return 'now';\n }\n\n if (seconds >= units.w && seconds % units.w === 0) {\n return `now-${seconds / units.w}w`;\n }\n\n if (seconds >= units.d && seconds % units.d === 0) {\n return `now-${seconds / units.d}d`;\n }\n\n if (seconds >= units.h && seconds % units.h === 0) {\n return `now-${seconds / units.h}h`;\n }\n\n if (seconds >= units.m && seconds % units.m === 0) {\n return `now-${seconds / units.m}m`;\n }\n\n return `now-${seconds}s`;\n};\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useState, useEffect } from 'react';\nimport { Button, Popover, Row, Col, Input } from 'antd';\nimport { DownOutlined, UpOutlined, SearchOutlined, CloseCircleOutlined } from '@ant-design/icons';\nimport classNames from 'classnames';\nimport moment from 'moment';\nimport _ from 'lodash';\nimport { isValid, describeTimeRange, valueAsString, isMathString } from '../utils';\nimport { IRawTimeRange, ITimeRangePickerProps } from '../types';\nimport { rangeOptions, momentLocaleZhCN } from '../config';\nimport { isRelativeFormat } from './utils';\nimport '../style.less';\n\nmoment.locale('zh-cn', momentLocaleZhCN);\n\nconst validOptions = rangeOptions.filter((o) => isRelativeFormat(o.start));\nconst historyCacheKey = 'flashcat-timeRangePicker-relative-history';\nconst getHistoryCache = () => {\n const cache = localStorage.getItem(historyCacheKey);\n if (cache) {\n try {\n const list = _.unionWith(JSON.parse(cache), _.isEqual);\n return list;\n } catch (e) {\n console.log(e);\n return [];\n }\n }\n return [];\n};\nconst setHistoryCache = (range, dateFormat) => {\n const historyCache = getHistoryCache();\n const rangeClone = _.cloneDeep(range);\n rangeClone.start = valueAsString(rangeClone.start, dateFormat);\n rangeClone.end = valueAsString(rangeClone.end, dateFormat);\n const newHistoryCache = _.unionWith([rangeClone, ...historyCache], _.isEqual).slice(0, 4);\n try {\n const cacheStr = JSON.stringify(newHistoryCache);\n localStorage.setItem(historyCacheKey, cacheStr);\n } catch (e) {\n console.log(e);\n }\n};\n\nexport default function index(props: ITimeRangePickerProps) {\n const historyCache = getHistoryCache();\n const { value, onChange = () => {}, dateFormat = 'YYYY-MM-DD HH:mm', placeholder = '请选择时间', allowClear = false, onClear = () => {}, extraFooter } = props;\n const [visible, setVisible] = useState(false);\n const [range, setRange] = useState();\n const [label, setLabel] = useState('');\n const [searchValue, setSearchValue] = useState('');\n const [rangeStatus, setRangeStatus] = useState<{\n start?: string;\n end?: string;\n }>({\n start: undefined,\n end: undefined,\n });\n const renderSinglePicker = (key: 'start' | 'end') => {\n const labelMap = {\n start: '开始时间',\n end: '结束时间',\n };\n const val = moment(range ? range[key] : undefined, true);\n return (\n
\n {labelMap[key]}\n \n {\n const val = e.target.value;\n setRangeStatus({\n ...rangeStatus,\n [key]: !isValid(val) ? 'invalid' : undefined,\n });\n if (isValid(val)) {\n const newRange = {\n ...(range || {}),\n [key]: isMathString(val) ? val : moment(val),\n };\n setRange(newRange as IRawTimeRange);\n } else {\n setRange({\n ...(range || {}),\n [key]: val,\n } as IRawTimeRange);\n }\n }}\n onBlur={(e) => {\n const val = e.target.value;\n const otherKey = key === 'start' ? 'end' : 'start';\n // 必须是绝对时间才缓存\n if (range && !isMathString(val) && moment.isMoment(range[otherKey])) {\n setHistoryCache(\n {\n ...range,\n [key]: val,\n },\n dateFormat,\n );\n }\n }}\n />\n \n
{rangeStatus[key] === 'invalid' ? '时间格式错误' : undefined}
\n
\n );\n };\n\n useEffect(() => {\n if (value) {\n setRange(value);\n setLabel(describeTimeRange(value, dateFormat));\n }\n }, [JSON.stringify(value), visible]);\n\n return (\n <>\n \n
\n \n
\n
\n {renderSinglePicker('start')}\n {renderSinglePicker('end')}\n
\n 最近使用的时间范围\n
    \n {_.map(historyCache, (range, idx) => {\n return (\n {\n const newValue = {\n start: isMathString(range.start) ? range.start : moment(range.start),\n end: isMathString(range.end) ? range.end : moment(range.end),\n };\n setRange(newValue);\n onChange(newValue);\n setHistoryCache(newValue, dateFormat);\n setVisible(false);\n }}\n >\n {describeTimeRange(range, dateFormat)}\n \n );\n })}\n
\n
\n
\n \n \n
\n }\n value={searchValue}\n onChange={(e) => {\n setSearchValue(e.target.value);\n }}\n />\n
    \n {_.map(\n _.filter(validOptions, (item) => item.displayZh.indexOf(searchValue) > -1),\n (item) => {\n return (\n {\n const newValue = {\n start: item.start,\n end: item.end,\n };\n setRange(newValue);\n onChange(newValue);\n setVisible(false);\n setHistoryCache(newValue, dateFormat);\n }}\n >\n {item.displayZh}\n \n );\n },\n )}\n
\n
\n \n \n \n
\n {\n if (rangeStatus.start !== 'invalid' && rangeStatus.end !== 'invalid') {\n onChange(range as IRawTimeRange);\n setVisible(false);\n }\n }}\n >\n 确定\n \n {extraFooter && extraFooter(setVisible)}\n
\n \n }\n trigger='click'\n placement='bottomRight'\n visible={visible}\n onVisibleChange={(v) => {\n setVisible(v);\n }}\n >\n {\n setVisible(!visible);\n }}\n >\n {props.label || label || placeholder}\n {!props.label && (\n \n {visible ? : }\n {\n e.nativeEvent.stopImmediatePropagation();\n e.stopPropagation();\n setRange(undefined);\n setLabel('');\n onClear();\n }}\n />\n \n )}\n \n \n \n );\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n/**\n * 时间选择器组件\n * 时间范围默认值:如果开启了本地缓存,需要调用 getDefaultValue(localKey: string, defaultValue: IRawTimeRange) 来获取真实的默认值\n */\nimport React from 'react';\nimport TimeRangePicker from './TimeRangePicker';\nimport { IRawTimeRange } from './types';\nimport TimeRangePickerWithRefresh from './TimeRangePickerWithRefresh';\nimport { parseRange, parse, valueAsString, isMathString, timeRangeUnix, describeTimeRange } from './utils';\nimport { ITimeRangePickerProps } from './types';\nimport { mapOptionToRelativeTimeRange, mapRelativeTimeRangeToOption } from './RelativeTimeRangePicker/utils';\nimport RelativeTimeRangePicker from './RelativeTimeRangePicker';\n\nexport default function index(props: ITimeRangePickerProps) {\n const { localKey, dateFormat = 'YYYY-MM-DD HH:mm', onChange } = props;\n\n return (\n {\n if (localKey) {\n localStorage.setItem(\n localKey,\n JSON.stringify({\n start: valueAsString(val.start, dateFormat),\n end: valueAsString(val.end, dateFormat),\n }),\n );\n }\n if (onChange) {\n onChange(val);\n }\n }}\n />\n );\n}\n\nexport type { IRawTimeRange } from './types';\nexport function getDefaultValue(localKey: string, defaultValue: IRawTimeRange) {\n const localeValue = localStorage.getItem(localKey);\n if (localeValue) {\n try {\n return JSON.parse(localeValue);\n } catch (e) {\n return defaultValue;\n }\n }\n return defaultValue;\n}\nexport {\n TimeRangePickerWithRefresh,\n RelativeTimeRangePicker,\n parseRange,\n parse,\n isMathString,\n timeRangeUnix,\n describeTimeRange,\n mapOptionToRelativeTimeRange,\n mapRelativeTimeRangeToOption,\n};\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport request from '@/utils/request';\nimport { RequestMethod } from '@/store/common';\nimport { N9EAPI } from '../../config/constant';\n\ninterface DashboardQuery {}\n// 大盘列表\nexport const getDashboard = function () {\n return request(`/api/n9e/dashboards`, {\n method: RequestMethod.Get,\n });\n};\ninterface Dashboard {\n name: string;\n tags: string;\n pure?: boolean;\n configs?: string;\n}\n// 创建大盘\nexport const createDashboard = function (id: number, data: Dashboard) {\n return request(`/api/n9e/busi-group/${id}/dashboards`, {\n method: RequestMethod.Post,\n data,\n });\n};\n\n// 克隆大盘\nexport const cloneDashboard = function (busiId: number, id: number) {\n return request(`/api/n9e/busi-group/${busiId}/dashboard/${id}/clone`, {\n method: RequestMethod.Post,\n });\n};\n\n// 删除大盘\nexport const removeDashboard = function (busiId: number, id: number) {\n return request(`/api/n9e/busi-group/${busiId}/dashboard/${id}`, {\n method: RequestMethod.Delete,\n });\n};\n\n// 导出大盘\nexport const exportDashboard = function (busiId: number, ids: number[]) {\n return request(`/api/n9e/busi-group/${busiId}/dashboards/export`, {\n method: RequestMethod.Post,\n data: { ids },\n });\n};\n\n// 导入大盘\nexport const importDashboard = function (busiId: number, data: any[]) {\n return request(`/api/n9e/busi-group/${busiId}/dashboards/import`, {\n method: RequestMethod.Post,\n data,\n });\n};\n\n// 获取大盘详情\nexport const getSingleDashboard = function (busiId: string, id: string | number) {\n return request(`/api/n9e/busi-group/${busiId}/dashboard/${id}`, {\n method: RequestMethod.Get,\n });\n};\n\n// 更新大盘\nexport const updateSingleDashboard = function (busiId: string | number, id: string, data: Dashboard) {\n return request(`/api/n9e/busi-group/${busiId}/dashboard/${id}`, {\n method: RequestMethod.Put,\n data,\n });\n};\n\ninterface Group {\n id?: number;\n dashboard_id: number;\n name: string;\n weight: number;\n}\n// 创建分组\nexport const createChartGroup = function (busiId: string, data: Group) {\n return request(`/api/n9e/busi-group/${busiId}/chart-groups`, {\n method: RequestMethod.Post,\n data,\n });\n};\n\n// 获取分组\nexport const getChartGroup = function (busiId: string, id: string) {\n return request(`/api/n9e/busi-group/${busiId}/chart-groups?did=${id}`, {\n method: RequestMethod.Get,\n });\n};\n\n// 删除分组\nexport const delChartGroup = function (busiId: string, id: number) {\n return request(`/api/n9e/busi-group/${busiId}/chart-groups`, {\n method: RequestMethod.Delete,\n data: { ids: [id] },\n });\n};\n\n// 更新分组\nexport const updateChartGroup = function (busiId: string, data: Group[]) {\n return request(`/api/n9e/busi-group/${busiId}/chart-groups`, {\n method: RequestMethod.Put,\n data,\n });\n};\n\ninterface Chart {\n configs: string | object;\n weight: number;\n group_id: number;\n id?: number | string;\n}\n\n// 创建Chart\nexport const createChart = function (busiId: string, data: Chart) {\n return request(`/api/n9e/busi-group/${busiId}/charts`, {\n method: RequestMethod.Post,\n data,\n });\n};\n\n// 编辑Chart\nexport const updateChart = function (chartId: number, data: Chart) {\n return request(`/api/n9e/chart/${chartId}`, {\n method: RequestMethod.Put,\n data,\n });\n};\n\n// 批量更新Chart\nexport const updateCharts = function (busiId: string, data: Chart[]) {\n const transformedData = data.map((item) => {\n return { ...item, configs: JSON.stringify(item.configs) };\n });\n return request(`/api/n9e/busi-group/${busiId}/charts`, {\n method: RequestMethod.Put,\n data: transformedData,\n });\n};\n\n// 移动Chart\nexport const moveChart = function (id: string, data: { id: number; weight: number; group_id: number }[]) {\n return request(`/api/n9e/charts/weights`, {\n method: RequestMethod.Put,\n data,\n });\n};\n\n// 获取某图表分组下面的所有chart\nexport const getCharts = function (busiId: string | number, id: number) {\n return request(`/api/n9e/busi-group/${busiId}/charts?cgid=${id}`, {\n method: RequestMethod.Get,\n });\n};\n\n// 删除Chart\nexport const removeChart = function (busiId: string | number, id: number | string) {\n return request(`/api/n9e/busi-group/${busiId}/charts`, {\n method: RequestMethod.Delete,\n data: { ids: [id] },\n });\n};\n\n// 删除Chart\nexport const checkPromql = function (promql: string) {\n return request(`/api/n9e/check-promql`, {\n method: RequestMethod.Get,\n params: { promql },\n });\n};\n\n// 告警策略 or 大盘 内置模版\nexport const getTemplate = function (type: 'alert_rule' | 'dashboard') {\n return request(`/api/n9e/tpl/list?tpl_type=${type}`, {\n method: RequestMethod.Get,\n });\n};\n\nexport const getTemplateContent = function (type: 'alert_rule' | 'dashboard', name: string) {\n return request(`/api/n9e/tpl/content?tpl_type=${type}&tpl_name=${name}`, {\n method: RequestMethod.Get,\n });\n};\n\nexport const getLabelNames = function (data, datasourceValue: string) {\n return request(`/api/n9e/prometheus/api/v1/labels`, {\n method: RequestMethod.Get,\n params: { ...data },\n headers: {\n 'X-Cluster': datasourceValue,\n },\n });\n};\n\nexport const getLabelValues = function (label, data, datasourceValue: string) {\n return request(`/api/n9e/prometheus/api/v1/label/${label}/values`, {\n method: RequestMethod.Get,\n params: { ...data },\n headers: {\n 'X-Cluster': datasourceValue,\n },\n });\n};\n\nexport const getMetricSeries = function (data, datasourceValue: string) {\n return request(`/api/n9e/prometheus/api/v1/series`, {\n method: RequestMethod.Get,\n params: { ...data },\n headers: {\n 'X-Cluster': datasourceValue,\n },\n });\n};\n\nexport const getMetric = function (data = {}, datasourceValue: string) {\n return request(`/api/n9e/prometheus/api/v1/label/__name__/values`, {\n method: RequestMethod.Get,\n params: { ...data },\n headers: {\n 'X-Cluster': datasourceValue,\n },\n });\n};\n\nexport const getQueryResult = function (data, datasourceValue: string) {\n return request(`/api/n9e/prometheus/api/v1/query`, {\n method: RequestMethod.Get,\n params: { ...data },\n headers: {\n 'X-Cluster': datasourceValue,\n },\n });\n};\n\nexport const getBuiltinDashboards = function () {\n return request('/api/n9e/dashboards/builtin/list', {\n method: RequestMethod.Get,\n });\n};\n\nexport const createBuiltinDashboards = function (name: string, cluster: string, id: number) {\n return request(`/api/n9e/busi-group/${id}/dashboards/builtin`, {\n method: RequestMethod.Post,\n data: { name, cluster },\n });\n};\n\n// boards v2 api\nexport const migrateDashboard = function (id: number, data: { name: string; tags: string; configs: string }) {\n return request(`/api/n9e/dashboard/${id}/migrate`, {\n method: RequestMethod.Put,\n data,\n });\n};\n\n//\n\nexport const getESVariableResult = function (data: { cate: string; cluster: string; index: string; query: any }) {\n return request('/api/n9e-plus/es-variable', {\n method: RequestMethod.Post,\n data,\n }).then((res) => res.dat);\n};\n","import React from 'react';\n\ninterface IProps {\n children: React.ReactNode;\n label: React.ReactNode;\n style?: React.CSSProperties;\n}\n\nexport default function FormItem(props: IProps) {\n return (\n \n
{props.label}
\n
{props.children}
\n \n );\n}\n","import React, { useState, useEffect } from 'react';\nimport { AutoComplete } from 'antd';\nimport _ from 'lodash';\nimport { getMetric } from '@/services/dashboard';\nimport FormItem from '../components/FormItem';\n\ninterface IProps {\n datasourceValue: string;\n params: {\n start: number;\n end: number;\n };\n value?: string;\n onChange: (val: string) => void;\n}\n\nexport default function index(props: IProps) {\n const { datasourceValue, params, value, onChange } = props;\n const [metricData, setMetricData] = useState([]);\n const [searchValue, setSearchValue] = useState();\n\n useEffect(() => {\n getMetric(params, datasourceValue).then((res) => {\n setMetricData(res.data);\n });\n }, []);\n\n useEffect(() => {\n setSearchValue(value);\n }, [value]);\n\n return (\n \n {\n return {\n value: item,\n };\n })}\n value={searchValue}\n filterOption={(inputValue, option) => {\n if (option && option.value) {\n return option.value.indexOf(inputValue) !== -1;\n }\n return true;\n }}\n onSearch={(val) => {\n setSearchValue(val);\n }}\n onBlur={(e: any) => {\n onChange(e.target.value);\n }}\n onSelect={(val) => {\n onChange(val);\n }}\n />\n \n );\n}\n","import _ from 'lodash';\n\nexport const getMatchByLabels = (\n metric: string,\n labels?: {\n label: string;\n value: string;\n op: string;\n }[],\n currentLabelName?: string,\n) => {\n const labelFilters = _.map(\n _.filter(labels, (item) => {\n if (currentLabelName) {\n return item.label !== currentLabelName;\n }\n return !!item.label && !!item.value;\n }),\n ({ label, value, op }) => `${label}${op}\"${value}\"`,\n );\n return `{__name__=\"${metric}\"${_.isEmpty(labelFilters) ? '' : `,${labelFilters.join(', ')}`}}`;\n};\n","import React, { useState, useEffect } from 'react';\nimport { AutoComplete } from 'antd';\nimport _ from 'lodash';\nimport { getLabelNames } from '@/services/dashboard';\nimport { getMatchByLabels } from './utils';\n\ninterface IProps {\n metric?: string;\n labels: {\n label: string;\n value: string;\n op: string;\n }[];\n datasourceValue: string;\n params: {\n start: number;\n end: number;\n };\n style?: React.CSSProperties;\n size?: 'small' | 'middle' | 'large';\n value?: string;\n onChange: (val: string) => void;\n}\n\nexport default function LabelNameSelect(props: IProps) {\n const { metric, labels, datasourceValue, params, style, size, value, onChange } = props;\n const [labelNames, setLabelNames] = useState([]);\n const [searchValue, setSearchValue] = useState();\n\n useEffect(() => {\n if (metric) {\n getLabelNames(\n {\n ...params,\n 'match[]': getMatchByLabels(metric, labels, value),\n },\n datasourceValue,\n ).then((res) => {\n setLabelNames(res.data);\n });\n }\n }, [metric, labels]);\n\n useEffect(() => {\n setSearchValue(value);\n }, [value]);\n\n return (\n {\n return {\n value: item,\n };\n })}\n value={searchValue}\n filterOption={(inputValue, option) => {\n if (option && option.value) {\n return option.value.indexOf(inputValue) !== -1;\n }\n return true;\n }}\n onSearch={(val) => {\n setSearchValue(val);\n }}\n onBlur={(e: any) => {\n onChange(e.target.value);\n }}\n onSelect={(val) => {\n onChange(val);\n }}\n />\n );\n}\n","import React, { useState, useEffect } from 'react';\nimport { AutoComplete } from 'antd';\nimport _ from 'lodash';\nimport { getLabelValues } from '@/services/dashboard';\n\ninterface IProps {\n label: string;\n datasourceValue: string;\n params: {\n start: number;\n end: number;\n };\n style?: React.CSSProperties;\n value?: string;\n onChange: (val: string) => void;\n}\n\nexport default function LabelValueSelect(props: IProps) {\n const { label, datasourceValue, params, style, value, onChange } = props;\n const [labelValues, setLabelValues] = useState([]);\n const [searchValue, setSearchValue] = useState();\n\n useEffect(() => {\n if (label) {\n getLabelValues(label, params, datasourceValue).then((res) => {\n setLabelValues(res.data);\n });\n }\n }, [label]);\n\n useEffect(() => {\n setSearchValue(value);\n }, [value]);\n\n return (\n {\n return {\n value: item,\n };\n })}\n value={searchValue}\n filterOption={(inputValue, option) => {\n if (option && option.value) {\n return option.value.indexOf(inputValue) !== -1;\n }\n return true;\n }}\n onSearch={(val) => {\n setSearchValue(val);\n }}\n onBlur={(e: any) => {\n onChange(e.target.value);\n }}\n onSelect={(val) => {\n onChange(val);\n }}\n />\n );\n}\n","import React, { useEffect } from 'react';\nimport { Select, Input, Button, Space } from 'antd';\nimport { PlusCircleOutlined, CloseOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport { useDynamicList } from 'ahooks';\nimport FormItem from '../components/FormItem';\nimport LabelNameSelect from './LabelNameSelect';\nimport LabelValueSelect from './LabelValueSelect';\nimport { PromVisualQueryLabelFilter } from '../types';\n\ninterface IProps {\n datasourceValue: string;\n metric?: string;\n params: {\n start: number;\n end: number;\n };\n value: PromVisualQueryLabelFilter[];\n onChange: (val: PromVisualQueryLabelFilter[]) => void;\n}\n\nexport default function index(props: IProps) {\n const { datasourceValue, metric, params, value, onChange } = props;\n const { list, remove, getKey, insert, replace } = useDynamicList(\n value || [\n {\n label: '',\n value: '',\n op: '=',\n },\n ],\n );\n\n useEffect(() => {\n onChange(list);\n }, [list]);\n\n return (\n <>\n \n 标签过滤\n {\n insert(list.length, {\n label: '',\n value: '',\n op: '=',\n });\n }}\n />\n \n }\n style={{ width: list.length > 1 ? '100%' : 'calc(50% - 4px)' }}\n >\n
\n {_.map(list, (item, index) => {\n return (\n 1 ? 'calc(50% - 4px)' : '100%',\n }}\n >\n {\n replace(index, {\n ...item,\n label: val,\n });\n }}\n />\n {\n replace(index, {\n ...item,\n op: val,\n });\n }}\n >\n =\n !=\n =~\n !~\n \n {\n replace(index, {\n ...item,\n value: val,\n });\n }}\n />\n }\n onClick={() => {\n remove(index);\n }}\n />\n \n );\n })}\n
\n \n \n );\n}\n","export function arrayMoveMutable(array, fromIndex, toIndex) {\n\tconst startIndex = fromIndex < 0 ? array.length + fromIndex : fromIndex;\n\n\tif (startIndex >= 0 && startIndex < array.length) {\n\t\tconst endIndex = toIndex < 0 ? array.length + toIndex : toIndex;\n\n\t\tconst [item] = array.splice(fromIndex, 1);\n\t\tarray.splice(endIndex, 0, item);\n\t}\n}\n\nexport function arrayMoveImmutable(array, fromIndex, toIndex) {\n\tarray = [...array];\n\tarrayMoveMutable(array, fromIndex, toIndex);\n\treturn array;\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\n/**\n * Use invariant() to assert state which your program assumes to be true.\n *\n * Provide sprintf-style format (only %s is supported) and arguments\n * to provide information about what broke and what you were\n * expecting.\n *\n * The invariant message will be stripped in production, but the invariant\n * will remain to ensure logic does not differ in production.\n */\n\nvar invariant = function(condition, format, a, b, c, d, e, f) {\n if (process.env.NODE_ENV !== 'production') {\n if (format === undefined) {\n throw new Error('invariant requires an error message argument');\n }\n }\n\n if (!condition) {\n var error;\n if (format === undefined) {\n error = new Error(\n 'Minified exception occurred; use the non-minified dev environment ' +\n 'for the full error message and additional helpful warnings.'\n );\n } else {\n var args = [a, b, c, d, e, f];\n var argIndex = 0;\n error = new Error(\n format.replace(/%s/g, function() { return args[argIndex++]; })\n );\n error.name = 'Invariant Violation';\n }\n\n error.framesToPop = 1; // we don't care about invariant's own frame\n throw error;\n }\n};\n\nmodule.exports = invariant;\n","import _extends from '@babel/runtime/helpers/esm/extends';\nimport _slicedToArray from '@babel/runtime/helpers/esm/slicedToArray';\nimport _objectSpread from '@babel/runtime/helpers/esm/objectSpread';\nimport _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck';\nimport _createClass from '@babel/runtime/helpers/esm/createClass';\nimport _possibleConstructorReturn from '@babel/runtime/helpers/esm/possibleConstructorReturn';\nimport _getPrototypeOf from '@babel/runtime/helpers/esm/getPrototypeOf';\nimport _inherits from '@babel/runtime/helpers/esm/inherits';\nimport _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized';\nimport _defineProperty from '@babel/runtime/helpers/esm/defineProperty';\nimport { createElement, Component } from 'react';\nimport PropTypes from 'prop-types';\nimport { findDOMNode } from 'react-dom';\nimport invariant from 'invariant';\nimport _toConsumableArray from '@babel/runtime/helpers/esm/toConsumableArray';\n\nvar Manager = function () {\n function Manager() {\n _classCallCheck(this, Manager);\n\n _defineProperty(this, \"refs\", {});\n }\n\n _createClass(Manager, [{\n key: \"add\",\n value: function add(collection, ref) {\n if (!this.refs[collection]) {\n this.refs[collection] = [];\n }\n\n this.refs[collection].push(ref);\n }\n }, {\n key: \"remove\",\n value: function remove(collection, ref) {\n var index = this.getIndex(collection, ref);\n\n if (index !== -1) {\n this.refs[collection].splice(index, 1);\n }\n }\n }, {\n key: \"isActive\",\n value: function isActive() {\n return this.active;\n }\n }, {\n key: \"getActive\",\n value: function getActive() {\n var _this = this;\n\n return this.refs[this.active.collection].find(function (_ref) {\n var node = _ref.node;\n return node.sortableInfo.index == _this.active.index;\n });\n }\n }, {\n key: \"getIndex\",\n value: function getIndex(collection, ref) {\n return this.refs[collection].indexOf(ref);\n }\n }, {\n key: \"getOrderedRefs\",\n value: function getOrderedRefs() {\n var collection = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.active.collection;\n return this.refs[collection].sort(sortByIndex);\n }\n }]);\n\n return Manager;\n}();\n\nfunction sortByIndex(_ref2, _ref3) {\n var index1 = _ref2.node.sortableInfo.index;\n var index2 = _ref3.node.sortableInfo.index;\n return index1 - index2;\n}\n\nfunction arrayMove(array, from, to) {\n if (process.env.NODE_ENV !== 'production') {\n if (typeof console !== 'undefined') {\n console.warn(\"Deprecation warning: arrayMove will no longer be exported by 'react-sortable-hoc' in the next major release. Please install the `array-move` package locally instead. https://www.npmjs.com/package/array-move\");\n }\n }\n\n array = array.slice();\n array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);\n return array;\n}\nfunction omit(obj, keysToOmit) {\n return Object.keys(obj).reduce(function (acc, key) {\n if (keysToOmit.indexOf(key) === -1) {\n acc[key] = obj[key];\n }\n\n return acc;\n }, {});\n}\nvar events = {\n end: ['touchend', 'touchcancel', 'mouseup'],\n move: ['touchmove', 'mousemove'],\n start: ['touchstart', 'mousedown']\n};\nvar vendorPrefix = function () {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n return '';\n }\n\n var styles = window.getComputedStyle(document.documentElement, '') || ['-moz-hidden-iframe'];\n var pre = (Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/) || styles.OLink === '' && ['', 'o'])[1];\n\n switch (pre) {\n case 'ms':\n return 'ms';\n\n default:\n return pre && pre.length ? pre[0].toUpperCase() + pre.substr(1) : '';\n }\n}();\nfunction setInlineStyles(node, styles) {\n Object.keys(styles).forEach(function (key) {\n node.style[key] = styles[key];\n });\n}\nfunction setTranslate3d(node, translate) {\n node.style[\"\".concat(vendorPrefix, \"Transform\")] = translate == null ? '' : \"translate3d(\".concat(translate.x, \"px,\").concat(translate.y, \"px,0)\");\n}\nfunction setTransitionDuration(node, duration) {\n node.style[\"\".concat(vendorPrefix, \"TransitionDuration\")] = duration == null ? '' : \"\".concat(duration, \"ms\");\n}\nfunction closest(el, fn) {\n while (el) {\n if (fn(el)) {\n return el;\n }\n\n el = el.parentNode;\n }\n\n return null;\n}\nfunction limit(min, max, value) {\n return Math.max(min, Math.min(value, max));\n}\n\nfunction getPixelValue(stringValue) {\n if (stringValue.substr(-2) === 'px') {\n return parseFloat(stringValue);\n }\n\n return 0;\n}\n\nfunction getElementMargin(element) {\n var style = window.getComputedStyle(element);\n return {\n bottom: getPixelValue(style.marginBottom),\n left: getPixelValue(style.marginLeft),\n right: getPixelValue(style.marginRight),\n top: getPixelValue(style.marginTop)\n };\n}\nfunction provideDisplayName(prefix, Component$$1) {\n var componentName = Component$$1.displayName || Component$$1.name;\n return componentName ? \"\".concat(prefix, \"(\").concat(componentName, \")\") : prefix;\n}\nfunction getScrollAdjustedBoundingClientRect(node, scrollDelta) {\n var boundingClientRect = node.getBoundingClientRect();\n return {\n top: boundingClientRect.top + scrollDelta.top,\n left: boundingClientRect.left + scrollDelta.left\n };\n}\nfunction getPosition(event) {\n if (event.touches && event.touches.length) {\n return {\n x: event.touches[0].pageX,\n y: event.touches[0].pageY\n };\n } else if (event.changedTouches && event.changedTouches.length) {\n return {\n x: event.changedTouches[0].pageX,\n y: event.changedTouches[0].pageY\n };\n } else {\n return {\n x: event.pageX,\n y: event.pageY\n };\n }\n}\nfunction isTouchEvent(event) {\n return event.touches && event.touches.length || event.changedTouches && event.changedTouches.length;\n}\nfunction getEdgeOffset(node, parent) {\n var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {\n left: 0,\n top: 0\n };\n\n if (!node) {\n return undefined;\n }\n\n var nodeOffset = {\n left: offset.left + node.offsetLeft,\n top: offset.top + node.offsetTop\n };\n\n if (node.parentNode === parent) {\n return nodeOffset;\n }\n\n return getEdgeOffset(node.parentNode, parent, nodeOffset);\n}\nfunction getTargetIndex(newIndex, prevIndex, oldIndex) {\n if (newIndex < oldIndex && newIndex > prevIndex) {\n return newIndex - 1;\n } else if (newIndex > oldIndex && newIndex < prevIndex) {\n return newIndex + 1;\n } else {\n return newIndex;\n }\n}\nfunction getLockPixelOffset(_ref) {\n var lockOffset = _ref.lockOffset,\n width = _ref.width,\n height = _ref.height;\n var offsetX = lockOffset;\n var offsetY = lockOffset;\n var unit = 'px';\n\n if (typeof lockOffset === 'string') {\n var match = /^[+-]?\\d*(?:\\.\\d*)?(px|%)$/.exec(lockOffset);\n invariant(match !== null, 'lockOffset value should be a number or a string of a ' + 'number followed by \"px\" or \"%\". Given %s', lockOffset);\n offsetX = parseFloat(lockOffset);\n offsetY = parseFloat(lockOffset);\n unit = match[1];\n }\n\n invariant(isFinite(offsetX) && isFinite(offsetY), 'lockOffset value should be a finite. Given %s', lockOffset);\n\n if (unit === '%') {\n offsetX = offsetX * width / 100;\n offsetY = offsetY * height / 100;\n }\n\n return {\n x: offsetX,\n y: offsetY\n };\n}\nfunction getLockPixelOffsets(_ref2) {\n var height = _ref2.height,\n width = _ref2.width,\n lockOffset = _ref2.lockOffset;\n var offsets = Array.isArray(lockOffset) ? lockOffset : [lockOffset, lockOffset];\n invariant(offsets.length === 2, 'lockOffset prop of SortableContainer should be a single ' + 'value or an array of exactly two values. Given %s', lockOffset);\n\n var _offsets = _slicedToArray(offsets, 2),\n minLockOffset = _offsets[0],\n maxLockOffset = _offsets[1];\n\n return [getLockPixelOffset({\n height: height,\n lockOffset: minLockOffset,\n width: width\n }), getLockPixelOffset({\n height: height,\n lockOffset: maxLockOffset,\n width: width\n })];\n}\n\nfunction isScrollable(el) {\n var computedStyle = window.getComputedStyle(el);\n var overflowRegex = /(auto|scroll)/;\n var properties = ['overflow', 'overflowX', 'overflowY'];\n return properties.find(function (property) {\n return overflowRegex.test(computedStyle[property]);\n });\n}\n\nfunction getScrollingParent(el) {\n if (!(el instanceof HTMLElement)) {\n return null;\n } else if (isScrollable(el)) {\n return el;\n } else {\n return getScrollingParent(el.parentNode);\n }\n}\nfunction getContainerGridGap(element) {\n var style = window.getComputedStyle(element);\n\n if (style.display === 'grid') {\n return {\n x: getPixelValue(style.gridColumnGap),\n y: getPixelValue(style.gridRowGap)\n };\n }\n\n return {\n x: 0,\n y: 0\n };\n}\nvar KEYCODE = {\n TAB: 9,\n ESC: 27,\n SPACE: 32,\n LEFT: 37,\n UP: 38,\n RIGHT: 39,\n DOWN: 40\n};\nvar NodeType = {\n Anchor: 'A',\n Button: 'BUTTON',\n Canvas: 'CANVAS',\n Input: 'INPUT',\n Option: 'OPTION',\n Textarea: 'TEXTAREA',\n Select: 'SELECT'\n};\nfunction cloneNode(node) {\n var selector = 'input, textarea, select, canvas, [contenteditable]';\n var fields = node.querySelectorAll(selector);\n var clonedNode = node.cloneNode(true);\n\n var clonedFields = _toConsumableArray(clonedNode.querySelectorAll(selector));\n\n clonedFields.forEach(function (field, i) {\n if (field.type !== 'file') {\n field.value = fields[i].value;\n }\n\n if (field.type === 'radio' && field.name) {\n field.name = \"__sortableClone__\".concat(field.name);\n }\n\n if (field.tagName === NodeType.Canvas && fields[i].width > 0 && fields[i].height > 0) {\n var destCtx = field.getContext('2d');\n destCtx.drawImage(fields[i], 0, 0);\n }\n });\n return clonedNode;\n}\n\nfunction sortableHandle(WrappedComponent) {\n var _class, _temp;\n\n var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n withRef: false\n };\n return _temp = _class = function (_React$Component) {\n _inherits(WithSortableHandle, _React$Component);\n\n function WithSortableHandle() {\n _classCallCheck(this, WithSortableHandle);\n\n return _possibleConstructorReturn(this, _getPrototypeOf(WithSortableHandle).apply(this, arguments));\n }\n\n _createClass(WithSortableHandle, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var node = findDOMNode(this);\n node.sortableHandle = true;\n }\n }, {\n key: \"getWrappedInstance\",\n value: function getWrappedInstance() {\n invariant(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableHandle() call');\n return this.refs.wrappedInstance;\n }\n }, {\n key: \"render\",\n value: function render() {\n var ref = config.withRef ? 'wrappedInstance' : null;\n return createElement(WrappedComponent, _extends({\n ref: ref\n }, this.props));\n }\n }]);\n\n return WithSortableHandle;\n }(Component), _defineProperty(_class, \"displayName\", provideDisplayName('sortableHandle', WrappedComponent)), _temp;\n}\nfunction isSortableHandle(node) {\n return node.sortableHandle != null;\n}\n\nvar AutoScroller = function () {\n function AutoScroller(container, onScrollCallback) {\n _classCallCheck(this, AutoScroller);\n\n this.container = container;\n this.onScrollCallback = onScrollCallback;\n }\n\n _createClass(AutoScroller, [{\n key: \"clear\",\n value: function clear() {\n if (this.interval == null) {\n return;\n }\n\n clearInterval(this.interval);\n this.interval = null;\n }\n }, {\n key: \"update\",\n value: function update(_ref) {\n var _this = this;\n\n var translate = _ref.translate,\n minTranslate = _ref.minTranslate,\n maxTranslate = _ref.maxTranslate,\n width = _ref.width,\n height = _ref.height;\n var direction = {\n x: 0,\n y: 0\n };\n var speed = {\n x: 1,\n y: 1\n };\n var acceleration = {\n x: 10,\n y: 10\n };\n var _this$container = this.container,\n scrollTop = _this$container.scrollTop,\n scrollLeft = _this$container.scrollLeft,\n scrollHeight = _this$container.scrollHeight,\n scrollWidth = _this$container.scrollWidth,\n clientHeight = _this$container.clientHeight,\n clientWidth = _this$container.clientWidth;\n var isTop = scrollTop === 0;\n var isBottom = scrollHeight - scrollTop - clientHeight === 0;\n var isLeft = scrollLeft === 0;\n var isRight = scrollWidth - scrollLeft - clientWidth === 0;\n\n if (translate.y >= maxTranslate.y - height / 2 && !isBottom) {\n direction.y = 1;\n speed.y = acceleration.y * Math.abs((maxTranslate.y - height / 2 - translate.y) / height);\n } else if (translate.x >= maxTranslate.x - width / 2 && !isRight) {\n direction.x = 1;\n speed.x = acceleration.x * Math.abs((maxTranslate.x - width / 2 - translate.x) / width);\n } else if (translate.y <= minTranslate.y + height / 2 && !isTop) {\n direction.y = -1;\n speed.y = acceleration.y * Math.abs((translate.y - height / 2 - minTranslate.y) / height);\n } else if (translate.x <= minTranslate.x + width / 2 && !isLeft) {\n direction.x = -1;\n speed.x = acceleration.x * Math.abs((translate.x - width / 2 - minTranslate.x) / width);\n }\n\n if (this.interval) {\n this.clear();\n this.isAutoScrolling = false;\n }\n\n if (direction.x !== 0 || direction.y !== 0) {\n this.interval = setInterval(function () {\n _this.isAutoScrolling = true;\n var offset = {\n left: speed.x * direction.x,\n top: speed.y * direction.y\n };\n _this.container.scrollTop += offset.top;\n _this.container.scrollLeft += offset.left;\n\n _this.onScrollCallback(offset);\n }, 5);\n }\n }\n }]);\n\n return AutoScroller;\n}();\n\nfunction defaultGetHelperDimensions(_ref) {\n var node = _ref.node;\n return {\n height: node.offsetHeight,\n width: node.offsetWidth\n };\n}\n\nfunction defaultShouldCancelStart(event) {\n var interactiveElements = [NodeType.Input, NodeType.Textarea, NodeType.Select, NodeType.Option, NodeType.Button];\n\n if (interactiveElements.indexOf(event.target.tagName) !== -1) {\n return true;\n }\n\n if (closest(event.target, function (el) {\n return el.contentEditable === 'true';\n })) {\n return true;\n }\n\n return false;\n}\n\nvar propTypes = {\n axis: PropTypes.oneOf(['x', 'y', 'xy']),\n contentWindow: PropTypes.any,\n disableAutoscroll: PropTypes.bool,\n distance: PropTypes.number,\n getContainer: PropTypes.func,\n getHelperDimensions: PropTypes.func,\n helperClass: PropTypes.string,\n helperContainer: PropTypes.oneOfType([PropTypes.func, typeof HTMLElement === 'undefined' ? PropTypes.any : PropTypes.instanceOf(HTMLElement)]),\n hideSortableGhost: PropTypes.bool,\n keyboardSortingTransitionDuration: PropTypes.number,\n lockAxis: PropTypes.string,\n lockOffset: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string]))]),\n lockToContainerEdges: PropTypes.bool,\n onSortEnd: PropTypes.func,\n onSortMove: PropTypes.func,\n onSortOver: PropTypes.func,\n onSortStart: PropTypes.func,\n pressDelay: PropTypes.number,\n pressThreshold: PropTypes.number,\n keyCodes: PropTypes.shape({\n lift: PropTypes.arrayOf(PropTypes.number),\n drop: PropTypes.arrayOf(PropTypes.number),\n cancel: PropTypes.arrayOf(PropTypes.number),\n up: PropTypes.arrayOf(PropTypes.number),\n down: PropTypes.arrayOf(PropTypes.number)\n }),\n shouldCancelStart: PropTypes.func,\n transitionDuration: PropTypes.number,\n updateBeforeSortStart: PropTypes.func,\n useDragHandle: PropTypes.bool,\n useWindowAsScrollContainer: PropTypes.bool\n};\nvar defaultKeyCodes = {\n lift: [KEYCODE.SPACE],\n drop: [KEYCODE.SPACE],\n cancel: [KEYCODE.ESC],\n up: [KEYCODE.UP, KEYCODE.LEFT],\n down: [KEYCODE.DOWN, KEYCODE.RIGHT]\n};\nvar defaultProps = {\n axis: 'y',\n disableAutoscroll: false,\n distance: 0,\n getHelperDimensions: defaultGetHelperDimensions,\n hideSortableGhost: true,\n lockOffset: '50%',\n lockToContainerEdges: false,\n pressDelay: 0,\n pressThreshold: 5,\n keyCodes: defaultKeyCodes,\n shouldCancelStart: defaultShouldCancelStart,\n transitionDuration: 300,\n useWindowAsScrollContainer: false\n};\nvar omittedProps = Object.keys(propTypes);\nfunction validateProps(props) {\n invariant(!(props.distance && props.pressDelay), 'Attempted to set both `pressDelay` and `distance` on SortableContainer, you may only use one or the other, not both at the same time.');\n}\n\nfunction _finallyRethrows(body, finalizer) {\n try {\n var result = body();\n } catch (e) {\n return finalizer(true, e);\n }\n\n if (result && result.then) {\n return result.then(finalizer.bind(null, false), finalizer.bind(null, true));\n }\n\n return finalizer(false, value);\n}\nfunction sortableContainer(WrappedComponent) {\n var _class, _temp;\n\n var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n withRef: false\n };\n return _temp = _class = function (_React$Component) {\n _inherits(WithSortableContainer, _React$Component);\n\n function WithSortableContainer(props) {\n var _this;\n\n _classCallCheck(this, WithSortableContainer);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(WithSortableContainer).call(this, props));\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"state\", {});\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"handleStart\", function (event) {\n var _this$props = _this.props,\n distance = _this$props.distance,\n shouldCancelStart = _this$props.shouldCancelStart;\n\n if (event.button === 2 || shouldCancelStart(event)) {\n return;\n }\n\n _this.touched = true;\n _this.position = getPosition(event);\n var node = closest(event.target, function (el) {\n return el.sortableInfo != null;\n });\n\n if (node && node.sortableInfo && _this.nodeIsChild(node) && !_this.state.sorting) {\n var useDragHandle = _this.props.useDragHandle;\n var _node$sortableInfo = node.sortableInfo,\n index = _node$sortableInfo.index,\n collection = _node$sortableInfo.collection,\n disabled = _node$sortableInfo.disabled;\n\n if (disabled) {\n return;\n }\n\n if (useDragHandle && !closest(event.target, isSortableHandle)) {\n return;\n }\n\n _this.manager.active = {\n collection: collection,\n index: index\n };\n\n if (!isTouchEvent(event) && event.target.tagName === NodeType.Anchor) {\n event.preventDefault();\n }\n\n if (!distance) {\n if (_this.props.pressDelay === 0) {\n _this.handlePress(event);\n } else {\n _this.pressTimer = setTimeout(function () {\n return _this.handlePress(event);\n }, _this.props.pressDelay);\n }\n }\n }\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"nodeIsChild\", function (node) {\n return node.sortableInfo.manager === _this.manager;\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"handleMove\", function (event) {\n var _this$props2 = _this.props,\n distance = _this$props2.distance,\n pressThreshold = _this$props2.pressThreshold;\n\n if (!_this.state.sorting && _this.touched && !_this._awaitingUpdateBeforeSortStart) {\n var position = getPosition(event);\n var delta = {\n x: _this.position.x - position.x,\n y: _this.position.y - position.y\n };\n var combinedDelta = Math.abs(delta.x) + Math.abs(delta.y);\n _this.delta = delta;\n\n if (!distance && (!pressThreshold || combinedDelta >= pressThreshold)) {\n clearTimeout(_this.cancelTimer);\n _this.cancelTimer = setTimeout(_this.cancel, 0);\n } else if (distance && combinedDelta >= distance && _this.manager.isActive()) {\n _this.handlePress(event);\n }\n }\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"handleEnd\", function () {\n _this.touched = false;\n\n _this.cancel();\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"cancel\", function () {\n var distance = _this.props.distance;\n var sorting = _this.state.sorting;\n\n if (!sorting) {\n if (!distance) {\n clearTimeout(_this.pressTimer);\n }\n\n _this.manager.active = null;\n }\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"handlePress\", function (event) {\n try {\n var active = _this.manager.getActive();\n\n var _temp6 = function () {\n if (active) {\n var _temp7 = function _temp7() {\n var index = _node.sortableInfo.index;\n var margin = getElementMargin(_node);\n var gridGap = getContainerGridGap(_this.container);\n\n var containerBoundingRect = _this.scrollContainer.getBoundingClientRect();\n\n var dimensions = _getHelperDimensions({\n index: index,\n node: _node,\n collection: _collection\n });\n\n _this.node = _node;\n _this.margin = margin;\n _this.gridGap = gridGap;\n _this.width = dimensions.width;\n _this.height = dimensions.height;\n _this.marginOffset = {\n x: _this.margin.left + _this.margin.right + _this.gridGap.x,\n y: Math.max(_this.margin.top, _this.margin.bottom, _this.gridGap.y)\n };\n _this.boundingClientRect = _node.getBoundingClientRect();\n _this.containerBoundingRect = containerBoundingRect;\n _this.index = index;\n _this.newIndex = index;\n _this.axis = {\n x: _axis.indexOf('x') >= 0,\n y: _axis.indexOf('y') >= 0\n };\n _this.offsetEdge = getEdgeOffset(_node, _this.container);\n\n if (_isKeySorting) {\n _this.initialOffset = getPosition(_objectSpread({}, event, {\n pageX: _this.boundingClientRect.left,\n pageY: _this.boundingClientRect.top\n }));\n } else {\n _this.initialOffset = getPosition(event);\n }\n\n _this.initialScroll = {\n left: _this.scrollContainer.scrollLeft,\n top: _this.scrollContainer.scrollTop\n };\n _this.initialWindowScroll = {\n left: window.pageXOffset,\n top: window.pageYOffset\n };\n _this.helper = _this.helperContainer.appendChild(cloneNode(_node));\n setInlineStyles(_this.helper, {\n boxSizing: 'border-box',\n height: \"\".concat(_this.height, \"px\"),\n left: \"\".concat(_this.boundingClientRect.left - margin.left, \"px\"),\n pointerEvents: 'none',\n position: 'fixed',\n top: \"\".concat(_this.boundingClientRect.top - margin.top, \"px\"),\n width: \"\".concat(_this.width, \"px\")\n });\n\n if (_isKeySorting) {\n _this.helper.focus();\n }\n\n if (_hideSortableGhost) {\n _this.sortableGhost = _node;\n setInlineStyles(_node, {\n opacity: 0,\n visibility: 'hidden'\n });\n }\n\n _this.minTranslate = {};\n _this.maxTranslate = {};\n\n if (_isKeySorting) {\n var _ref = _useWindowAsScrollContainer ? {\n top: 0,\n left: 0,\n width: _this.contentWindow.innerWidth,\n height: _this.contentWindow.innerHeight\n } : _this.containerBoundingRect,\n containerTop = _ref.top,\n containerLeft = _ref.left,\n containerWidth = _ref.width,\n containerHeight = _ref.height;\n\n var containerBottom = containerTop + containerHeight;\n var containerRight = containerLeft + containerWidth;\n\n if (_this.axis.x) {\n _this.minTranslate.x = containerLeft - _this.boundingClientRect.left;\n _this.maxTranslate.x = containerRight - (_this.boundingClientRect.left + _this.width);\n }\n\n if (_this.axis.y) {\n _this.minTranslate.y = containerTop - _this.boundingClientRect.top;\n _this.maxTranslate.y = containerBottom - (_this.boundingClientRect.top + _this.height);\n }\n } else {\n if (_this.axis.x) {\n _this.minTranslate.x = (_useWindowAsScrollContainer ? 0 : containerBoundingRect.left) - _this.boundingClientRect.left - _this.width / 2;\n _this.maxTranslate.x = (_useWindowAsScrollContainer ? _this.contentWindow.innerWidth : containerBoundingRect.left + containerBoundingRect.width) - _this.boundingClientRect.left - _this.width / 2;\n }\n\n if (_this.axis.y) {\n _this.minTranslate.y = (_useWindowAsScrollContainer ? 0 : containerBoundingRect.top) - _this.boundingClientRect.top - _this.height / 2;\n _this.maxTranslate.y = (_useWindowAsScrollContainer ? _this.contentWindow.innerHeight : containerBoundingRect.top + containerBoundingRect.height) - _this.boundingClientRect.top - _this.height / 2;\n }\n }\n\n if (_helperClass) {\n _helperClass.split(' ').forEach(function (className) {\n return _this.helper.classList.add(className);\n });\n }\n\n _this.listenerNode = event.touches ? _node : _this.contentWindow;\n\n if (_isKeySorting) {\n _this.listenerNode.addEventListener('wheel', _this.handleKeyEnd, true);\n\n _this.listenerNode.addEventListener('mousedown', _this.handleKeyEnd, true);\n\n _this.listenerNode.addEventListener('keydown', _this.handleKeyDown);\n } else {\n events.move.forEach(function (eventName) {\n return _this.listenerNode.addEventListener(eventName, _this.handleSortMove, false);\n });\n events.end.forEach(function (eventName) {\n return _this.listenerNode.addEventListener(eventName, _this.handleSortEnd, false);\n });\n }\n\n _this.setState({\n sorting: true,\n sortingIndex: index\n });\n\n if (_onSortStart) {\n _onSortStart({\n node: _node,\n index: index,\n collection: _collection,\n isKeySorting: _isKeySorting,\n nodes: _this.manager.getOrderedRefs(),\n helper: _this.helper\n }, event);\n }\n\n if (_isKeySorting) {\n _this.keyMove(0);\n }\n };\n\n var _this$props3 = _this.props,\n _axis = _this$props3.axis,\n _getHelperDimensions = _this$props3.getHelperDimensions,\n _helperClass = _this$props3.helperClass,\n _hideSortableGhost = _this$props3.hideSortableGhost,\n updateBeforeSortStart = _this$props3.updateBeforeSortStart,\n _onSortStart = _this$props3.onSortStart,\n _useWindowAsScrollContainer = _this$props3.useWindowAsScrollContainer;\n var _node = active.node,\n _collection = active.collection;\n var _isKeySorting = _this.manager.isKeySorting;\n\n var _temp8 = function () {\n if (typeof updateBeforeSortStart === 'function') {\n _this._awaitingUpdateBeforeSortStart = true;\n\n var _temp9 = _finallyRethrows(function () {\n var index = _node.sortableInfo.index;\n return Promise.resolve(updateBeforeSortStart({\n collection: _collection,\n index: index,\n node: _node,\n isKeySorting: _isKeySorting\n }, event)).then(function () {});\n }, function (_wasThrown, _result) {\n _this._awaitingUpdateBeforeSortStart = false;\n if (_wasThrown) throw _result;\n return _result;\n });\n\n if (_temp9 && _temp9.then) return _temp9.then(function () {});\n }\n }();\n\n return _temp8 && _temp8.then ? _temp8.then(_temp7) : _temp7(_temp8);\n }\n }();\n\n return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(function () {}) : void 0);\n } catch (e) {\n return Promise.reject(e);\n }\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"handleSortMove\", function (event) {\n var onSortMove = _this.props.onSortMove;\n\n if (typeof event.preventDefault === 'function') {\n event.preventDefault();\n }\n\n _this.updateHelperPosition(event);\n\n _this.animateNodes();\n\n _this.autoscroll();\n\n if (onSortMove) {\n onSortMove(event);\n }\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"handleSortEnd\", function (event) {\n var _this$props4 = _this.props,\n hideSortableGhost = _this$props4.hideSortableGhost,\n onSortEnd = _this$props4.onSortEnd;\n var _this$manager = _this.manager,\n collection = _this$manager.active.collection,\n isKeySorting = _this$manager.isKeySorting;\n\n var nodes = _this.manager.getOrderedRefs();\n\n if (_this.listenerNode) {\n if (isKeySorting) {\n _this.listenerNode.removeEventListener('wheel', _this.handleKeyEnd, true);\n\n _this.listenerNode.removeEventListener('mousedown', _this.handleKeyEnd, true);\n\n _this.listenerNode.removeEventListener('keydown', _this.handleKeyDown);\n } else {\n events.move.forEach(function (eventName) {\n return _this.listenerNode.removeEventListener(eventName, _this.handleSortMove);\n });\n events.end.forEach(function (eventName) {\n return _this.listenerNode.removeEventListener(eventName, _this.handleSortEnd);\n });\n }\n }\n\n _this.helper.parentNode.removeChild(_this.helper);\n\n if (hideSortableGhost && _this.sortableGhost) {\n setInlineStyles(_this.sortableGhost, {\n opacity: '',\n visibility: ''\n });\n }\n\n for (var i = 0, len = nodes.length; i < len; i++) {\n var _node2 = nodes[i];\n var el = _node2.node;\n _node2.edgeOffset = null;\n _node2.boundingClientRect = null;\n setTranslate3d(el, null);\n setTransitionDuration(el, null);\n _node2.translate = null;\n }\n\n _this.autoScroller.clear();\n\n _this.manager.active = null;\n _this.manager.isKeySorting = false;\n\n _this.setState({\n sorting: false,\n sortingIndex: null\n });\n\n if (typeof onSortEnd === 'function') {\n onSortEnd({\n collection: collection,\n newIndex: _this.newIndex,\n oldIndex: _this.index,\n isKeySorting: isKeySorting,\n nodes: nodes\n }, event);\n }\n\n _this.touched = false;\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"autoscroll\", function () {\n var disableAutoscroll = _this.props.disableAutoscroll;\n var isKeySorting = _this.manager.isKeySorting;\n\n if (disableAutoscroll) {\n _this.autoScroller.clear();\n\n return;\n }\n\n if (isKeySorting) {\n var translate = _objectSpread({}, _this.translate);\n\n var scrollX = 0;\n var scrollY = 0;\n\n if (_this.axis.x) {\n translate.x = Math.min(_this.maxTranslate.x, Math.max(_this.minTranslate.x, _this.translate.x));\n scrollX = _this.translate.x - translate.x;\n }\n\n if (_this.axis.y) {\n translate.y = Math.min(_this.maxTranslate.y, Math.max(_this.minTranslate.y, _this.translate.y));\n scrollY = _this.translate.y - translate.y;\n }\n\n _this.translate = translate;\n setTranslate3d(_this.helper, _this.translate);\n _this.scrollContainer.scrollLeft += scrollX;\n _this.scrollContainer.scrollTop += scrollY;\n return;\n }\n\n _this.autoScroller.update({\n height: _this.height,\n maxTranslate: _this.maxTranslate,\n minTranslate: _this.minTranslate,\n translate: _this.translate,\n width: _this.width\n });\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"onAutoScroll\", function (offset) {\n _this.translate.x += offset.left;\n _this.translate.y += offset.top;\n\n _this.animateNodes();\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"handleKeyDown\", function (event) {\n var keyCode = event.keyCode;\n var _this$props5 = _this.props,\n shouldCancelStart = _this$props5.shouldCancelStart,\n _this$props5$keyCodes = _this$props5.keyCodes,\n customKeyCodes = _this$props5$keyCodes === void 0 ? {} : _this$props5$keyCodes;\n\n var keyCodes = _objectSpread({}, defaultKeyCodes, customKeyCodes);\n\n if (_this.manager.active && !_this.manager.isKeySorting || !_this.manager.active && (!keyCodes.lift.includes(keyCode) || shouldCancelStart(event) || !_this.isValidSortingTarget(event))) {\n return;\n }\n\n event.stopPropagation();\n event.preventDefault();\n\n if (keyCodes.lift.includes(keyCode) && !_this.manager.active) {\n _this.keyLift(event);\n } else if (keyCodes.drop.includes(keyCode) && _this.manager.active) {\n _this.keyDrop(event);\n } else if (keyCodes.cancel.includes(keyCode)) {\n _this.newIndex = _this.manager.active.index;\n\n _this.keyDrop(event);\n } else if (keyCodes.up.includes(keyCode)) {\n _this.keyMove(-1);\n } else if (keyCodes.down.includes(keyCode)) {\n _this.keyMove(1);\n }\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"keyLift\", function (event) {\n var target = event.target;\n var node = closest(target, function (el) {\n return el.sortableInfo != null;\n });\n var _node$sortableInfo2 = node.sortableInfo,\n index = _node$sortableInfo2.index,\n collection = _node$sortableInfo2.collection;\n _this.initialFocusedNode = target;\n _this.manager.isKeySorting = true;\n _this.manager.active = {\n index: index,\n collection: collection\n };\n\n _this.handlePress(event);\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"keyMove\", function (shift) {\n var nodes = _this.manager.getOrderedRefs();\n\n var lastIndex = nodes[nodes.length - 1].node.sortableInfo.index;\n var newIndex = _this.newIndex + shift;\n var prevIndex = _this.newIndex;\n\n if (newIndex < 0 || newIndex > lastIndex) {\n return;\n }\n\n _this.prevIndex = prevIndex;\n _this.newIndex = newIndex;\n var targetIndex = getTargetIndex(_this.newIndex, _this.prevIndex, _this.index);\n var target = nodes.find(function (_ref2) {\n var node = _ref2.node;\n return node.sortableInfo.index === targetIndex;\n });\n var targetNode = target.node;\n var scrollDelta = _this.containerScrollDelta;\n var targetBoundingClientRect = target.boundingClientRect || getScrollAdjustedBoundingClientRect(targetNode, scrollDelta);\n var targetTranslate = target.translate || {\n x: 0,\n y: 0\n };\n var targetPosition = {\n top: targetBoundingClientRect.top + targetTranslate.y - scrollDelta.top,\n left: targetBoundingClientRect.left + targetTranslate.x - scrollDelta.left\n };\n var shouldAdjustForSize = prevIndex < newIndex;\n var sizeAdjustment = {\n x: shouldAdjustForSize && _this.axis.x ? targetNode.offsetWidth - _this.width : 0,\n y: shouldAdjustForSize && _this.axis.y ? targetNode.offsetHeight - _this.height : 0\n };\n\n _this.handleSortMove({\n pageX: targetPosition.left + sizeAdjustment.x,\n pageY: targetPosition.top + sizeAdjustment.y,\n ignoreTransition: shift === 0\n });\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"keyDrop\", function (event) {\n _this.handleSortEnd(event);\n\n if (_this.initialFocusedNode) {\n _this.initialFocusedNode.focus();\n }\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"handleKeyEnd\", function (event) {\n if (_this.manager.active) {\n _this.keyDrop(event);\n }\n });\n\n _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), \"isValidSortingTarget\", function (event) {\n var useDragHandle = _this.props.useDragHandle;\n var target = event.target;\n var node = closest(target, function (el) {\n return el.sortableInfo != null;\n });\n return node && node.sortableInfo && !node.sortableInfo.disabled && (useDragHandle ? isSortableHandle(target) : target.sortableInfo);\n });\n\n validateProps(props);\n _this.manager = new Manager();\n _this.events = {\n end: _this.handleEnd,\n move: _this.handleMove,\n start: _this.handleStart\n };\n return _this;\n }\n\n _createClass(WithSortableContainer, [{\n key: \"getChildContext\",\n value: function getChildContext() {\n return {\n manager: this.manager\n };\n }\n }, {\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var _this2 = this;\n\n var useWindowAsScrollContainer = this.props.useWindowAsScrollContainer;\n var container = this.getContainer();\n Promise.resolve(container).then(function (containerNode) {\n _this2.container = containerNode;\n _this2.document = _this2.container.ownerDocument || document;\n var contentWindow = _this2.props.contentWindow || _this2.document.defaultView || window;\n _this2.contentWindow = typeof contentWindow === 'function' ? contentWindow() : contentWindow;\n _this2.scrollContainer = useWindowAsScrollContainer ? _this2.document.scrollingElement || _this2.document.documentElement : getScrollingParent(_this2.container) || _this2.container;\n _this2.autoScroller = new AutoScroller(_this2.scrollContainer, _this2.onAutoScroll);\n Object.keys(_this2.events).forEach(function (key) {\n return events[key].forEach(function (eventName) {\n return _this2.container.addEventListener(eventName, _this2.events[key], false);\n });\n });\n\n _this2.container.addEventListener('keydown', _this2.handleKeyDown);\n });\n }\n }, {\n key: \"componentWillUnmount\",\n value: function componentWillUnmount() {\n var _this3 = this;\n\n if (this.helper && this.helper.parentNode) {\n this.helper.parentNode.removeChild(this.helper);\n }\n\n if (!this.container) {\n return;\n }\n\n Object.keys(this.events).forEach(function (key) {\n return events[key].forEach(function (eventName) {\n return _this3.container.removeEventListener(eventName, _this3.events[key]);\n });\n });\n this.container.removeEventListener('keydown', this.handleKeyDown);\n }\n }, {\n key: \"updateHelperPosition\",\n value: function updateHelperPosition(event) {\n var _this$props6 = this.props,\n lockAxis = _this$props6.lockAxis,\n lockOffset = _this$props6.lockOffset,\n lockToContainerEdges = _this$props6.lockToContainerEdges,\n transitionDuration = _this$props6.transitionDuration,\n _this$props6$keyboard = _this$props6.keyboardSortingTransitionDuration,\n keyboardSortingTransitionDuration = _this$props6$keyboard === void 0 ? transitionDuration : _this$props6$keyboard;\n var isKeySorting = this.manager.isKeySorting;\n var ignoreTransition = event.ignoreTransition;\n var offset = getPosition(event);\n var translate = {\n x: offset.x - this.initialOffset.x,\n y: offset.y - this.initialOffset.y\n };\n translate.y -= window.pageYOffset - this.initialWindowScroll.top;\n translate.x -= window.pageXOffset - this.initialWindowScroll.left;\n this.translate = translate;\n\n if (lockToContainerEdges) {\n var _getLockPixelOffsets = getLockPixelOffsets({\n height: this.height,\n lockOffset: lockOffset,\n width: this.width\n }),\n _getLockPixelOffsets2 = _slicedToArray(_getLockPixelOffsets, 2),\n minLockOffset = _getLockPixelOffsets2[0],\n maxLockOffset = _getLockPixelOffsets2[1];\n\n var minOffset = {\n x: this.width / 2 - minLockOffset.x,\n y: this.height / 2 - minLockOffset.y\n };\n var maxOffset = {\n x: this.width / 2 - maxLockOffset.x,\n y: this.height / 2 - maxLockOffset.y\n };\n translate.x = limit(this.minTranslate.x + minOffset.x, this.maxTranslate.x - maxOffset.x, translate.x);\n translate.y = limit(this.minTranslate.y + minOffset.y, this.maxTranslate.y - maxOffset.y, translate.y);\n }\n\n if (lockAxis === 'x') {\n translate.y = 0;\n } else if (lockAxis === 'y') {\n translate.x = 0;\n }\n\n if (isKeySorting && keyboardSortingTransitionDuration && !ignoreTransition) {\n setTransitionDuration(this.helper, keyboardSortingTransitionDuration);\n }\n\n setTranslate3d(this.helper, translate);\n }\n }, {\n key: \"animateNodes\",\n value: function animateNodes() {\n var _this$props7 = this.props,\n transitionDuration = _this$props7.transitionDuration,\n hideSortableGhost = _this$props7.hideSortableGhost,\n onSortOver = _this$props7.onSortOver;\n var containerScrollDelta = this.containerScrollDelta,\n windowScrollDelta = this.windowScrollDelta;\n var nodes = this.manager.getOrderedRefs();\n var sortingOffset = {\n left: this.offsetEdge.left + this.translate.x + containerScrollDelta.left,\n top: this.offsetEdge.top + this.translate.y + containerScrollDelta.top\n };\n var isKeySorting = this.manager.isKeySorting;\n var prevIndex = this.newIndex;\n this.newIndex = null;\n\n for (var i = 0, len = nodes.length; i < len; i++) {\n var _node3 = nodes[i].node;\n var index = _node3.sortableInfo.index;\n var width = _node3.offsetWidth;\n var height = _node3.offsetHeight;\n var offset = {\n height: this.height > height ? height / 2 : this.height / 2,\n width: this.width > width ? width / 2 : this.width / 2\n };\n var mustShiftBackward = isKeySorting && index > this.index && index <= prevIndex;\n var mustShiftForward = isKeySorting && index < this.index && index >= prevIndex;\n var translate = {\n x: 0,\n y: 0\n };\n var edgeOffset = nodes[i].edgeOffset;\n\n if (!edgeOffset) {\n edgeOffset = getEdgeOffset(_node3, this.container);\n nodes[i].edgeOffset = edgeOffset;\n\n if (isKeySorting) {\n nodes[i].boundingClientRect = getScrollAdjustedBoundingClientRect(_node3, containerScrollDelta);\n }\n }\n\n var nextNode = i < nodes.length - 1 && nodes[i + 1];\n var prevNode = i > 0 && nodes[i - 1];\n\n if (nextNode && !nextNode.edgeOffset) {\n nextNode.edgeOffset = getEdgeOffset(nextNode.node, this.container);\n\n if (isKeySorting) {\n nextNode.boundingClientRect = getScrollAdjustedBoundingClientRect(nextNode.node, containerScrollDelta);\n }\n }\n\n if (index === this.index) {\n if (hideSortableGhost) {\n this.sortableGhost = _node3;\n setInlineStyles(_node3, {\n opacity: 0,\n visibility: 'hidden'\n });\n }\n\n continue;\n }\n\n if (transitionDuration) {\n setTransitionDuration(_node3, transitionDuration);\n }\n\n if (this.axis.x) {\n if (this.axis.y) {\n if (mustShiftForward || index < this.index && (sortingOffset.left + windowScrollDelta.left - offset.width <= edgeOffset.left && sortingOffset.top + windowScrollDelta.top <= edgeOffset.top + offset.height || sortingOffset.top + windowScrollDelta.top + offset.height <= edgeOffset.top)) {\n translate.x = this.width + this.marginOffset.x;\n\n if (edgeOffset.left + translate.x > this.containerBoundingRect.width - offset.width) {\n if (nextNode) {\n translate.x = nextNode.edgeOffset.left - edgeOffset.left;\n translate.y = nextNode.edgeOffset.top - edgeOffset.top;\n }\n }\n\n if (this.newIndex === null) {\n this.newIndex = index;\n }\n } else if (mustShiftBackward || index > this.index && (sortingOffset.left + windowScrollDelta.left + offset.width >= edgeOffset.left && sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top || sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top + height)) {\n translate.x = -(this.width + this.marginOffset.x);\n\n if (edgeOffset.left + translate.x < this.containerBoundingRect.left + offset.width) {\n if (prevNode) {\n translate.x = prevNode.edgeOffset.left - edgeOffset.left;\n translate.y = prevNode.edgeOffset.top - edgeOffset.top;\n }\n }\n\n this.newIndex = index;\n }\n } else {\n if (mustShiftBackward || index > this.index && sortingOffset.left + windowScrollDelta.left + offset.width >= edgeOffset.left) {\n translate.x = -(this.width + this.marginOffset.x);\n this.newIndex = index;\n } else if (mustShiftForward || index < this.index && sortingOffset.left + windowScrollDelta.left <= edgeOffset.left + offset.width) {\n translate.x = this.width + this.marginOffset.x;\n\n if (this.newIndex == null) {\n this.newIndex = index;\n }\n }\n }\n } else if (this.axis.y) {\n if (mustShiftBackward || index > this.index && sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top) {\n translate.y = -(this.height + this.marginOffset.y);\n this.newIndex = index;\n } else if (mustShiftForward || index < this.index && sortingOffset.top + windowScrollDelta.top <= edgeOffset.top + offset.height) {\n translate.y = this.height + this.marginOffset.y;\n\n if (this.newIndex == null) {\n this.newIndex = index;\n }\n }\n }\n\n setTranslate3d(_node3, translate);\n nodes[i].translate = translate;\n }\n\n if (this.newIndex == null) {\n this.newIndex = this.index;\n }\n\n if (isKeySorting) {\n this.newIndex = prevIndex;\n }\n\n var oldIndex = isKeySorting ? this.prevIndex : prevIndex;\n\n if (onSortOver && this.newIndex !== oldIndex) {\n onSortOver({\n collection: this.manager.active.collection,\n index: this.index,\n newIndex: this.newIndex,\n oldIndex: oldIndex,\n isKeySorting: isKeySorting,\n nodes: nodes,\n helper: this.helper\n });\n }\n }\n }, {\n key: \"getWrappedInstance\",\n value: function getWrappedInstance() {\n invariant(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableContainer() call');\n return this.refs.wrappedInstance;\n }\n }, {\n key: \"getContainer\",\n value: function getContainer() {\n var getContainer = this.props.getContainer;\n\n if (typeof getContainer !== 'function') {\n return findDOMNode(this);\n }\n\n return getContainer(config.withRef ? this.getWrappedInstance() : undefined);\n }\n }, {\n key: \"render\",\n value: function render() {\n var ref = config.withRef ? 'wrappedInstance' : null;\n return createElement(WrappedComponent, _extends({\n ref: ref\n }, omit(this.props, omittedProps)));\n }\n }, {\n key: \"helperContainer\",\n get: function get() {\n var helperContainer = this.props.helperContainer;\n\n if (typeof helperContainer === 'function') {\n return helperContainer();\n }\n\n return this.props.helperContainer || this.document.body;\n }\n }, {\n key: \"containerScrollDelta\",\n get: function get() {\n var useWindowAsScrollContainer = this.props.useWindowAsScrollContainer;\n\n if (useWindowAsScrollContainer) {\n return {\n left: 0,\n top: 0\n };\n }\n\n return {\n left: this.scrollContainer.scrollLeft - this.initialScroll.left,\n top: this.scrollContainer.scrollTop - this.initialScroll.top\n };\n }\n }, {\n key: \"windowScrollDelta\",\n get: function get() {\n return {\n left: this.contentWindow.pageXOffset - this.initialWindowScroll.left,\n top: this.contentWindow.pageYOffset - this.initialWindowScroll.top\n };\n }\n }]);\n\n return WithSortableContainer;\n }(Component), _defineProperty(_class, \"displayName\", provideDisplayName('sortableList', WrappedComponent)), _defineProperty(_class, \"defaultProps\", defaultProps), _defineProperty(_class, \"propTypes\", propTypes), _defineProperty(_class, \"childContextTypes\", {\n manager: PropTypes.object.isRequired\n }), _temp;\n}\n\nvar propTypes$1 = {\n index: PropTypes.number.isRequired,\n collection: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n disabled: PropTypes.bool\n};\nvar omittedProps$1 = Object.keys(propTypes$1);\nfunction sortableElement(WrappedComponent) {\n var _class, _temp;\n\n var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n withRef: false\n };\n return _temp = _class = function (_React$Component) {\n _inherits(WithSortableElement, _React$Component);\n\n function WithSortableElement() {\n _classCallCheck(this, WithSortableElement);\n\n return _possibleConstructorReturn(this, _getPrototypeOf(WithSortableElement).apply(this, arguments));\n }\n\n _createClass(WithSortableElement, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n this.register();\n }\n }, {\n key: \"componentDidUpdate\",\n value: function componentDidUpdate(prevProps) {\n if (this.node) {\n if (prevProps.index !== this.props.index) {\n this.node.sortableInfo.index = this.props.index;\n }\n\n if (prevProps.disabled !== this.props.disabled) {\n this.node.sortableInfo.disabled = this.props.disabled;\n }\n }\n\n if (prevProps.collection !== this.props.collection) {\n this.unregister(prevProps.collection);\n this.register();\n }\n }\n }, {\n key: \"componentWillUnmount\",\n value: function componentWillUnmount() {\n this.unregister();\n }\n }, {\n key: \"register\",\n value: function register() {\n var _this$props = this.props,\n collection = _this$props.collection,\n disabled = _this$props.disabled,\n index = _this$props.index;\n var node = findDOMNode(this);\n node.sortableInfo = {\n collection: collection,\n disabled: disabled,\n index: index,\n manager: this.context.manager\n };\n this.node = node;\n this.ref = {\n node: node\n };\n this.context.manager.add(collection, this.ref);\n }\n }, {\n key: \"unregister\",\n value: function unregister() {\n var collection = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props.collection;\n this.context.manager.remove(collection, this.ref);\n }\n }, {\n key: \"getWrappedInstance\",\n value: function getWrappedInstance() {\n invariant(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableElement() call');\n return this.refs.wrappedInstance;\n }\n }, {\n key: \"render\",\n value: function render() {\n var ref = config.withRef ? 'wrappedInstance' : null;\n return createElement(WrappedComponent, _extends({\n ref: ref\n }, omit(this.props, omittedProps$1)));\n }\n }]);\n\n return WithSortableElement;\n }(Component), _defineProperty(_class, \"displayName\", provideDisplayName('sortableElement', WrappedComponent)), _defineProperty(_class, \"contextTypes\", {\n manager: PropTypes.object.isRequired\n }), _defineProperty(_class, \"propTypes\", propTypes$1), _defineProperty(_class, \"defaultProps\", {\n collection: 0\n }), _temp;\n}\n\nexport { sortableContainer as SortableContainer, sortableContainer, sortableElement as SortableElement, sortableElement, sortableHandle as SortableHandle, sortableHandle, arrayMove };\n","export enum PromVisualQueryOperationCategory {\n Aggregations = 'Aggregations',\n BinaryOps = 'Binary operations',\n Functions = 'Functions',\n Trigonometric = 'Trigonometric',\n}\n\nexport interface PromVisualQueryBinary {\n operator: string;\n vectorMatchesType?: 'on' | 'ignoring';\n vectorMatches?: string;\n query: T;\n}\n\nexport interface PromVisualQueryLabelFilter {\n label: string;\n op: string;\n value: string;\n}\n\nexport type QueryBuilderOperationRenderer = (model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) => string;\nexport type VisualQueryOperationParamValue = string | number | boolean;\n\nexport interface PromVisualQueryOperation {\n id: string;\n params: VisualQueryOperationParamValue[];\n}\n\nexport interface QueryWithOperations {\n operations: PromVisualQueryOperation[];\n}\n\nexport interface PromVisualQuery {\n metric?: string;\n labels: PromVisualQueryLabelFilter[];\n operations: PromVisualQueryOperation[];\n binaryQueries?: Array>;\n}\n\nexport enum PromVisualQueryOperationId {\n Abs = 'abs',\n Absent = 'absent',\n AbsentOverTime = 'absent_over_time',\n Acos = 'acos',\n Acosh = 'acosh',\n Asin = 'asin',\n Asinh = 'asinh',\n Atan = 'atan',\n Atanh = 'atanh',\n Avg = 'avg',\n AvgOverTime = 'avg_over_time',\n BottomK = 'bottomk',\n Ceil = 'ceil',\n Changes = 'changes',\n Clamp = 'clamp',\n ClampMax = 'clamp_max',\n ClampMin = 'clamp_min',\n Cos = 'cos',\n Cosh = 'cosh',\n Count = 'count',\n CountOverTime = 'count_over_time',\n CountScalar = 'count_scalar',\n CountValues = 'count_values',\n DayOfMonth = 'day_of_month',\n DayOfWeek = 'day_of_week',\n DaysInMonth = 'days_in_month',\n Deg = 'deg',\n Delta = 'delta',\n Deriv = 'deriv',\n DropCommonLabels = 'drop_common_labels',\n Exp = 'exp',\n Floor = 'floor',\n Group = 'group',\n HistogramQuantile = 'histogram_quantile',\n HoltWinters = 'holt_winters',\n Hour = 'hour',\n Idelta = 'idelta',\n Increase = 'increase',\n Irate = 'irate',\n LabelJoin = 'label_join',\n LabelReplace = 'label_replace',\n Last = 'last',\n LastOverTime = 'last_over_time',\n Ln = 'ln',\n Log10 = 'log10',\n Log2 = 'log2',\n Max = 'max',\n MaxOverTime = 'max_over_time',\n Min = 'min',\n MinOverTime = 'min_over_time',\n Minute = 'minute',\n Month = 'month',\n Pi = 'pi',\n PredictLinear = 'predict_linear',\n Present = 'present',\n PresentOverTime = 'present_over_time',\n Quantile = 'quantile',\n QuantileOverTime = 'quantile_over_time',\n Rad = 'rad',\n Rate = 'rate',\n Resets = 'resets',\n Round = 'round',\n Scalar = 'scalar',\n Sgn = 'sgn',\n Sin = 'sin',\n Sinh = 'sinh',\n Sort = 'sort',\n SortDesc = 'sort_desc',\n Sqrt = 'sqrt',\n Stddev = 'stddev',\n StddevOverTime = 'stddev_over_time',\n Sum = 'sum',\n SumOverTime = 'sum_over_time',\n Tan = 'tan',\n Tanh = 'tanh',\n Time = 'time',\n Timestamp = 'timestamp',\n TopK = 'topk',\n Vector = 'vector',\n Year = 'year',\n ArithmeticBinary = '__arithmetic_binary_operators',\n ComparisonBinary = '__comparison_binary_operators',\n NestedQuery = '__nested_query',\n}\n\nexport interface QueryBuilderOperationDef {\n id: string;\n name: string;\n description?: string;\n documentation?: string;\n params: QueryBuilderOperationParamDef[];\n defaultParams: VisualQueryOperationParamValue[];\n category: string;\n hideFromList?: boolean;\n alternativesKey?: string;\n orderRank?: number;\n renderer: QueryBuilderOperationRenderer;\n addOperationHandler: QueryBuilderAddOperationHandler;\n paramChangedHandler?: QueryBuilderOnParamChangedHandler;\n}\n\nexport interface QueryBuilderOperationParamDef {\n name: string;\n type: 'string' | 'number' | 'boolean';\n options?:\n | string[]\n | number[]\n | {\n label: string;\n value: string | number;\n }[];\n hideName?: boolean;\n restParam?: boolean;\n optional?: boolean;\n placeholder?: string;\n description?: string;\n minWidth?: number;\n subType?: string;\n runQueryOnEnter?: boolean;\n}\n\nexport type VisualQueryModeller = any;\n\nexport type QueryBuilderAddOperationHandler = (def: QueryBuilderOperationDef, query: T, modeller: VisualQueryModeller) => T;\n\nexport type QueryBuilderOnParamChangedHandler = (index: number, operation: PromVisualQueryOperation, operationDef: QueryBuilderOperationDef) => PromVisualQueryOperation;\n\nexport type QueryBuilderExplainOperationHandler = (op: PromVisualQueryOperation, def?: QueryBuilderOperationDef) => string;\n","import { QueryBuilderOperationDef, PromVisualQueryOperation } from '../../types';\n\nfunction renderParams(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n return (model.params ?? []).map((value, index) => {\n const paramDef = def.params[index];\n if (paramDef.type === 'string') {\n return '\"' + value + '\"';\n }\n\n return value;\n });\n}\n\nexport function functionRendererLeft(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n const params = renderParams(model, def, innerExpr);\n const str = model.id + '(';\n\n if (innerExpr) {\n params.push(innerExpr);\n }\n\n return str + params.join(', ') + ')';\n}\n\nexport function functionRendererRight(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n const params = renderParams(model, def, innerExpr);\n const str = model.id + '(';\n\n if (innerExpr) {\n params.unshift(innerExpr);\n }\n\n return str + params.join(', ') + ')';\n}\n\nexport function getAggregationByRendererWithParameter(aggregation: string) {\n return function aggregationRenderer(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n const restParamIndex = def.params.findIndex((param) => param.restParam);\n const params = model.params.slice(0, restParamIndex);\n const restParams = model.params.slice(restParamIndex);\n\n return `${aggregation} by(${restParams.join(', ')}) (${params.map((param, idx) => (def.params[idx].type === 'string' ? `\\\"${param}\\\"` : param)).join(', ')}, ${innerExpr})`;\n };\n}\n\nexport function getAggregationByRenderer(aggregation: string) {\n return function aggregationRenderer(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n return `${aggregation} by(${model.params.join(', ')}) (${innerExpr})`;\n };\n}\n\nexport function getAggregationWithoutRenderer(aggregation: string) {\n return function aggregationRenderer(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n return `${aggregation} without(${model.params.join(', ')}) (${innerExpr})`;\n };\n}\n\nexport function operationWithRangeVectorRenderer(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n let rangeVector = (model.params ?? [])[0] ?? '5m';\n return `${def.id}(${innerExpr}[${rangeVector}])`;\n}\n\nfunction rangeRendererWithParams(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string, renderLeft: boolean) {\n if (def.params.length < 2) {\n throw `Cannot render a function with params of length [${def.params.length}]`;\n }\n\n let rangeVector = (model.params ?? [])[0] ?? '5m';\n\n const params = renderParams(\n {\n ...model,\n params: model.params.slice(1),\n },\n {\n ...def,\n params: def.params.slice(1),\n defaultParams: def.defaultParams.slice(1),\n },\n innerExpr,\n );\n\n const str = model.id + '(';\n\n if (innerExpr) {\n renderLeft ? params.push(`${innerExpr}[${rangeVector}]`) : params.unshift(`${innerExpr}[${rangeVector}]`);\n }\n\n return str + params.join(', ') + ')';\n}\n\nexport function rangeRendererRightWithParams(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n return rangeRendererWithParams(model, def, innerExpr, false);\n}\n\nexport function rangeRendererLeftWithParams(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n return rangeRendererWithParams(model, def, innerExpr, true);\n}\n\nexport function labelJoinRenderer(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n if (typeof model.params[1] !== 'string') {\n throw 'The separator must be a string';\n }\n const separator = `\"${model.params[1]}\"`;\n return `${model.id}(${innerExpr}, \"${model.params[0]}\", ${separator}, \"${model.params.slice(2).join(separator)}\")`;\n}\n\nexport function getSimpleBinaryRenderer(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n let operator = model.params[0];\n let param = model.params[1];\n let bool = '';\n if (model.params.length === 3) {\n bool = model.params[2] ? ' bool' : '';\n }\n\n return `${innerExpr} ${operator}${bool} ${param}`;\n}\n","import { PromVisualQuery, QueryBuilderOperationDef, PromVisualQueryOperation, QueryWithOperations } from '../../types';\n\nexport function defaultAddOperationHandler(def: QueryBuilderOperationDef, query: T) {\n const newOperation: PromVisualQueryOperation = {\n id: def.id,\n params: def.defaultParams,\n };\n\n return {\n ...query,\n operations: [...query.operations, newOperation],\n };\n}\n\nexport function addOperationWithRangeVector(def: QueryBuilderOperationDef, query: PromVisualQuery, firstOp: QueryBuilderOperationDef) {\n const newOperation: PromVisualQueryOperation = {\n id: def.id,\n params: def.defaultParams,\n };\n\n if (query.operations.length > 0) {\n if (firstOp.addOperationHandler === addOperationWithRangeVector) {\n return {\n ...query,\n operations: [newOperation, ...query.operations.slice(1)],\n };\n }\n }\n\n return {\n ...query,\n operations: [newOperation, ...query.operations],\n };\n}\n\nexport function labelJoinAddOperationHandler(def: QueryBuilderOperationDef, query: T) {\n const newOperation: PromVisualQueryOperation = {\n id: def.id,\n params: def.defaultParams,\n };\n\n return {\n ...query,\n operations: [...query.operations, newOperation],\n };\n}\n","import _ from 'lodash';\nimport {\n PromVisualQueryOperationCategory,\n QueryBuilderOperationDef,\n QueryBuilderOperationParamDef,\n VisualQueryOperationParamValue,\n PromVisualQueryOperation,\n QueryWithOperations,\n} from '../../types';\nimport { getPromOperationDisplayName, getRangeVectorParamDef } from './index';\nimport { functionRendererLeft, getAggregationByRenderer, getAggregationWithoutRenderer, operationWithRangeVectorRenderer } from './renderer';\nimport { defaultAddOperationHandler, addOperationWithRangeVector } from './addOperationHandler';\n\nexport function createAggregationOperation(name: string, overrides: Partial = {}): QueryBuilderOperationDef[] {\n const operations: QueryBuilderOperationDef[] = [\n {\n id: name,\n name: getPromOperationDisplayName(name),\n params: [\n {\n name: 'By label',\n type: 'string',\n restParam: true,\n optional: true,\n },\n ],\n defaultParams: [],\n alternativesKey: 'plain aggregations',\n category: PromVisualQueryOperationCategory.Aggregations,\n renderer: functionRendererLeft,\n paramChangedHandler: getOnLabelAddedHandler(`__${name}_by`),\n addOperationHandler: defaultAddOperationHandler,\n ...overrides,\n },\n {\n id: `__${name}_by`,\n name: `${getPromOperationDisplayName(name)} by`,\n params: [\n {\n name: 'Label',\n type: 'string',\n restParam: true,\n optional: true,\n subType: 'labelNameSelect',\n },\n ],\n defaultParams: [''],\n alternativesKey: 'aggregations by',\n category: PromVisualQueryOperationCategory.Aggregations,\n renderer: getAggregationByRenderer(name),\n paramChangedHandler: getLastLabelRemovedHandler(name),\n addOperationHandler: defaultAddOperationHandler,\n hideFromList: true,\n ...overrides,\n },\n {\n id: `__${name}_without`,\n name: `${getPromOperationDisplayName(name)} without`,\n params: [\n {\n name: 'Label',\n type: 'string',\n restParam: true,\n optional: true,\n subType: 'labelNameSelect',\n },\n ],\n defaultParams: [''],\n alternativesKey: 'aggregations by',\n category: PromVisualQueryOperationCategory.Aggregations,\n renderer: getAggregationWithoutRenderer(name),\n paramChangedHandler: getLastLabelRemovedHandler(name),\n addOperationHandler: defaultAddOperationHandler,\n hideFromList: true,\n ...overrides,\n },\n ];\n\n return operations;\n}\n\nexport function getOnLabelAddedHandler(changeToOperationId: string) {\n return function onParamChanged(index: number, op: PromVisualQueryOperation, def: QueryBuilderOperationDef) {\n if (op.params.length === def.params.length) {\n return {\n ...op,\n id: changeToOperationId,\n };\n }\n return op;\n };\n}\n\nexport function getLastLabelRemovedHandler(changeToOperationId: string) {\n return function onParamChanged(index: number, op: PromVisualQueryOperation, def: QueryBuilderOperationDef) {\n if (op.params.length < def.params.length) {\n return {\n ...op,\n id: changeToOperationId,\n };\n }\n\n return op;\n };\n}\n\nexport function createAggregationOperationWithParam(\n name: string,\n paramsDef: { params: QueryBuilderOperationParamDef[]; defaultParams: VisualQueryOperationParamValue[] },\n overrides: Partial = {},\n): QueryBuilderOperationDef[] {\n const operations = createAggregationOperation(name, overrides);\n operations[0].params.unshift(...paramsDef.params);\n operations[1].params.unshift(...paramsDef.params);\n operations[2].params.unshift(...paramsDef.params);\n operations[0].defaultParams = paramsDef.defaultParams;\n operations[1].defaultParams = [...paramsDef.defaultParams, ''];\n operations[2].defaultParams = [...paramsDef.defaultParams, ''];\n operations[1].renderer = getAggregationByRendererWithParameter(name);\n operations[2].renderer = getAggregationByRendererWithParameter(name);\n return operations;\n}\n\nfunction getAggregationByRendererWithParameter(aggregation: string) {\n return function aggregationRenderer(model: PromVisualQueryOperation, def: QueryBuilderOperationDef, innerExpr: string) {\n const restParamIndex = def.params.findIndex((param) => param.restParam);\n const params = model.params.slice(0, restParamIndex);\n const restParams = model.params.slice(restParamIndex);\n\n return `${aggregation} by(${restParams.join(', ')}) (${params.map((param, idx) => (def.params[idx].type === 'string' ? `\\\"${param}\\\"` : param)).join(', ')}, ${innerExpr})`;\n };\n}\n\nexport function createAggregationOverTime(name: string): QueryBuilderOperationDef {\n return {\n id: name,\n name: getPromOperationDisplayName(name),\n params: [getRangeVectorParamDef()],\n defaultParams: ['5m'],\n alternativesKey: 'overtime function',\n category: PromVisualQueryOperationCategory.Aggregations,\n renderer: operationWithRangeVectorRenderer,\n addOperationHandler: addOperationWithRangeVector,\n };\n}\n","import { PromVisualQueryOperationCategory, QueryBuilderOperationDef, QueryBuilderOperationParamDef } from '../../types';\nimport { getPromOperationDisplayName } from './index';\nimport { operationWithRangeVectorRenderer } from './renderer';\nimport { addOperationWithRangeVector } from './addOperationHandler';\n\nexport function createRangeFunction(name: string): QueryBuilderOperationDef {\n return {\n id: name,\n name: getPromOperationDisplayName(name),\n params: [getRangeVectorParamDef()],\n defaultParams: ['5m'],\n alternativesKey: 'range function',\n category: PromVisualQueryOperationCategory.Functions,\n renderer: operationWithRangeVectorRenderer,\n addOperationHandler: addOperationWithRangeVector,\n };\n}\n\nexport function getRangeVectorParamDef(): QueryBuilderOperationParamDef {\n const param: QueryBuilderOperationParamDef = {\n name: 'Range',\n type: 'string',\n options: [\n { label: '1m', value: '1m' },\n { label: '5m', value: '5m' },\n { label: '10m', value: '10m' },\n { label: '1h', value: '1h' },\n { label: '24h', value: '24h' },\n ],\n };\n return param;\n}\n","import { PromVisualQueryOperationCategory, QueryBuilderOperationDef } from '../../types';\nimport { getPromOperationDisplayName } from './index';\nimport { functionRendererRight, functionRendererLeft } from './renderer';\nimport { defaultAddOperationHandler } from './addOperationHandler';\n\nexport function createFunction(definition: Partial): QueryBuilderOperationDef {\n return {\n ...definition,\n id: definition.id!,\n name: definition.name ?? getPromOperationDisplayName(definition.id!),\n params: definition.params ?? [],\n defaultParams: definition.defaultParams ?? [],\n category: definition.category ?? PromVisualQueryOperationCategory.Functions,\n renderer: definition.renderer ?? (definition.params ? functionRendererRight : functionRendererLeft),\n addOperationHandler: definition.addOperationHandler ?? defaultAddOperationHandler,\n };\n}\n","import _ from 'lodash';\nimport { PromVisualQuery, PromVisualQueryOperationCategory, QueryBuilderOperationDef, PromVisualQueryOperationId, QueryBuilderOperationParamDef } from '../../types';\nimport { createAggregationOperation, createAggregationOperationWithParam, createAggregationOverTime } from './createAggregationOperation';\nimport { createRangeFunction } from './createRangeFunction';\nimport { createFunction } from './createFunction';\nimport { rangeRendererRightWithParams, rangeRendererLeftWithParams, functionRendererLeft, labelJoinRenderer, getSimpleBinaryRenderer } from './renderer';\nimport { addOperationWithRangeVector, labelJoinAddOperationHandler, defaultAddOperationHandler } from './addOperationHandler';\n\nexport const arithmeticBinaryOperators = ['+', '-', '*', '/', '%', '^'];\nexport const comparisonBinaryOperators = ['==', '!=', '>', '<', '>=', '<='];\n\nexport function getOperationDefinitions(): QueryBuilderOperationDef[] {\n const list: QueryBuilderOperationDef[] = [\n ...createAggregationOperation(PromVisualQueryOperationId.Sum),\n ...createAggregationOperation(PromVisualQueryOperationId.Avg),\n ...createAggregationOperation(PromVisualQueryOperationId.Min),\n ...createAggregationOperation(PromVisualQueryOperationId.Max),\n ...createAggregationOperation(PromVisualQueryOperationId.Count),\n ...createAggregationOperationWithParam(PromVisualQueryOperationId.TopK, {\n params: [{ name: 'K-value', type: 'number' }],\n defaultParams: [5],\n }),\n ...createAggregationOperationWithParam(PromVisualQueryOperationId.BottomK, {\n params: [{ name: 'K-value', type: 'number' }],\n defaultParams: [5],\n }),\n ...createAggregationOperationWithParam(PromVisualQueryOperationId.CountValues, {\n params: [{ name: 'Identifier', type: 'string' }],\n defaultParams: ['count'],\n }),\n createAggregationOverTime(PromVisualQueryOperationId.SumOverTime),\n createAggregationOverTime(PromVisualQueryOperationId.AvgOverTime),\n createAggregationOverTime(PromVisualQueryOperationId.MinOverTime),\n createAggregationOverTime(PromVisualQueryOperationId.MaxOverTime),\n createAggregationOverTime(PromVisualQueryOperationId.CountOverTime),\n createAggregationOverTime(PromVisualQueryOperationId.LastOverTime),\n createAggregationOverTime(PromVisualQueryOperationId.PresentOverTime),\n createAggregationOverTime(PromVisualQueryOperationId.AbsentOverTime),\n createAggregationOverTime(PromVisualQueryOperationId.StddevOverTime),\n {\n id: PromVisualQueryOperationId.ArithmeticBinary,\n name: 'Arithmetic',\n params: [\n {\n name: 'Operator',\n type: 'string',\n options: _.map(arithmeticBinaryOperators, (item) => {\n return {\n label: item,\n value: item,\n };\n }),\n },\n { name: 'Value', type: 'number' },\n ],\n defaultParams: ['+', 2],\n alternativesKey: 'binary scalar operations',\n category: PromVisualQueryOperationCategory.BinaryOps,\n renderer: getSimpleBinaryRenderer,\n addOperationHandler: defaultAddOperationHandler,\n },\n {\n id: PromVisualQueryOperationId.ComparisonBinary,\n name: 'Comparison',\n params: [\n {\n name: 'Operator',\n type: 'string',\n options: _.map(comparisonBinaryOperators, (item) => {\n return {\n label: item,\n value: item,\n };\n }),\n },\n { name: 'Value', type: 'number' },\n { name: 'Bool', type: 'boolean' },\n ],\n defaultParams: ['==', 2, false],\n alternativesKey: 'binary scalar operations',\n category: PromVisualQueryOperationCategory.BinaryOps,\n renderer: getSimpleBinaryRenderer,\n addOperationHandler: defaultAddOperationHandler,\n },\n {\n id: PromVisualQueryOperationId.NestedQuery,\n name: 'Binary operation with query',\n params: [],\n defaultParams: [],\n category: PromVisualQueryOperationCategory.BinaryOps,\n renderer: (model, def, innerExpr) => innerExpr,\n addOperationHandler: addNestedQueryHandler,\n },\n createRangeFunction(PromVisualQueryOperationId.Changes),\n createRangeFunction(PromVisualQueryOperationId.Rate),\n createRangeFunction(PromVisualQueryOperationId.Irate),\n createRangeFunction(PromVisualQueryOperationId.Increase),\n createRangeFunction(PromVisualQueryOperationId.Idelta),\n createRangeFunction(PromVisualQueryOperationId.Delta),\n createFunction({\n id: PromVisualQueryOperationId.HoltWinters,\n params: [getRangeVectorParamDef(), { name: 'Smoothing Factor', type: 'number' }, { name: 'Trend Factor', type: 'number' }],\n defaultParams: ['5m', 0.5, 0.5],\n alternativesKey: 'range function',\n category: PromVisualQueryOperationCategory.Functions,\n renderer: rangeRendererRightWithParams,\n addOperationHandler: addOperationWithRangeVector,\n }),\n createFunction({\n id: PromVisualQueryOperationId.PredictLinear,\n params: [getRangeVectorParamDef(), { name: 'Seconds from now', type: 'number' }],\n defaultParams: ['5m', 60],\n alternativesKey: 'range function',\n category: PromVisualQueryOperationCategory.Functions,\n renderer: rangeRendererRightWithParams,\n addOperationHandler: addOperationWithRangeVector,\n }),\n createFunction({\n id: PromVisualQueryOperationId.QuantileOverTime,\n params: [getRangeVectorParamDef(), { name: 'Quantile', type: 'number' }],\n defaultParams: ['5m', 0.5],\n alternativesKey: 'overtime function',\n category: PromVisualQueryOperationCategory.Functions,\n renderer: rangeRendererLeftWithParams,\n addOperationHandler: addOperationWithRangeVector,\n }),\n createFunction({ id: PromVisualQueryOperationId.Absent }),\n createFunction({\n id: PromVisualQueryOperationId.Acos,\n category: PromVisualQueryOperationCategory.Trigonometric,\n }),\n createFunction({\n id: PromVisualQueryOperationId.Acosh,\n category: PromVisualQueryOperationCategory.Trigonometric,\n }),\n createFunction({\n id: PromVisualQueryOperationId.Asin,\n category: PromVisualQueryOperationCategory.Trigonometric,\n }),\n createFunction({\n id: PromVisualQueryOperationId.Asinh,\n category: PromVisualQueryOperationCategory.Trigonometric,\n }),\n createFunction({\n id: PromVisualQueryOperationId.Atan,\n category: PromVisualQueryOperationCategory.Trigonometric,\n }),\n createFunction({\n id: PromVisualQueryOperationId.Atanh,\n category: PromVisualQueryOperationCategory.Trigonometric,\n }),\n createFunction({ id: PromVisualQueryOperationId.Ceil }),\n createFunction({\n id: PromVisualQueryOperationId.Clamp,\n name: 'Clamp',\n params: [\n { name: 'Minimum Scalar', type: 'number' },\n { name: 'Maximum Scalar', type: 'number' },\n ],\n defaultParams: [1, 1],\n }),\n\n createFunction({\n id: PromVisualQueryOperationId.ClampMax,\n params: [{ name: 'Maximum Scalar', type: 'number' }],\n defaultParams: [1],\n }),\n createFunction({\n id: PromVisualQueryOperationId.ClampMin,\n params: [{ name: 'Minimum Scalar', type: 'number' }],\n defaultParams: [1],\n }),\n createFunction({\n id: PromVisualQueryOperationId.Cos,\n category: PromVisualQueryOperationCategory.Trigonometric,\n }),\n createFunction({\n id: PromVisualQueryOperationId.Cosh,\n category: PromVisualQueryOperationCategory.Trigonometric,\n }),\n createFunction({\n id: PromVisualQueryOperationId.DayOfMonth,\n category: PromVisualQueryOperationCategory.Functions,\n }),\n createFunction({\n id: PromVisualQueryOperationId.DayOfWeek,\n category: PromVisualQueryOperationCategory.Functions,\n }),\n createFunction({\n id: PromVisualQueryOperationId.DaysInMonth,\n category: PromVisualQueryOperationCategory.Functions,\n }),\n createFunction({ id: PromVisualQueryOperationId.Deg }),\n createRangeFunction(PromVisualQueryOperationId.Deriv),\n //\n createFunction({ id: PromVisualQueryOperationId.Exp }),\n createFunction({ id: PromVisualQueryOperationId.Floor }),\n createFunction({ id: PromVisualQueryOperationId.Group }),\n createFunction({ id: PromVisualQueryOperationId.Hour }),\n createFunction({\n id: PromVisualQueryOperationId.LabelJoin,\n params: [\n {\n name: 'Destination Label',\n type: 'string',\n subType: 'labelNameSelect',\n },\n {\n name: 'Separator',\n type: 'string',\n },\n {\n name: 'Source Label',\n type: 'string',\n restParam: true,\n optional: true,\n subType: 'labelNameSelect',\n },\n ],\n defaultParams: ['', ',', ''],\n renderer: labelJoinRenderer,\n addOperationHandler: labelJoinAddOperationHandler,\n }),\n createFunction({ id: PromVisualQueryOperationId.Log10 }),\n createFunction({ id: PromVisualQueryOperationId.Log2 }),\n createFunction({ id: PromVisualQueryOperationId.Minute }),\n createFunction({ id: PromVisualQueryOperationId.Month }),\n createFunction({\n id: PromVisualQueryOperationId.Pi,\n renderer: (model) => `${model.id}()`,\n }),\n createFunction({\n id: PromVisualQueryOperationId.Quantile,\n params: [{ name: 'Value', type: 'number' }],\n defaultParams: [1],\n renderer: functionRendererLeft,\n }),\n createFunction({ id: PromVisualQueryOperationId.Rad }),\n createRangeFunction(PromVisualQueryOperationId.Resets),\n createFunction({\n id: PromVisualQueryOperationId.Round,\n category: PromVisualQueryOperationCategory.Functions,\n params: [{ name: 'To Nearest', type: 'number' }],\n defaultParams: [1],\n }),\n createFunction({ id: PromVisualQueryOperationId.Scalar }),\n createFunction({ id: PromVisualQueryOperationId.Sgn }),\n createFunction({ id: PromVisualQueryOperationId.Sin, category: PromVisualQueryOperationCategory.Trigonometric }),\n createFunction({\n id: PromVisualQueryOperationId.Sinh,\n category: PromVisualQueryOperationCategory.Trigonometric,\n }),\n createFunction({ id: PromVisualQueryOperationId.Sort }),\n createFunction({ id: PromVisualQueryOperationId.SortDesc }),\n createFunction({ id: PromVisualQueryOperationId.Sqrt }),\n createFunction({ id: PromVisualQueryOperationId.Stddev }),\n createFunction({\n id: PromVisualQueryOperationId.Tan,\n category: PromVisualQueryOperationCategory.Trigonometric,\n }),\n createFunction({\n id: PromVisualQueryOperationId.Tanh,\n category: PromVisualQueryOperationCategory.Trigonometric,\n }),\n createFunction({\n id: PromVisualQueryOperationId.Time,\n renderer: (model) => `${model.id}()`,\n }),\n createFunction({ id: PromVisualQueryOperationId.Timestamp }),\n createFunction({\n id: PromVisualQueryOperationId.Vector,\n params: [{ name: 'Value', type: 'number' }],\n defaultParams: [1],\n renderer: (model) => `${model.id}(${model.params[0]})`,\n }),\n createFunction({ id: PromVisualQueryOperationId.Year }),\n ];\n\n return list;\n}\n\nexport function getRangeVectorParamDef(): QueryBuilderOperationParamDef {\n const param: QueryBuilderOperationParamDef = {\n name: 'Range',\n type: 'string',\n options: [\n { label: '1m', value: '1m' },\n { label: '5m', value: '5m' },\n { label: '10m', value: '10m' },\n { label: '1h', value: '1h' },\n { label: '24h', value: '24h' },\n ],\n };\n return param;\n}\n\nexport function getPromOperationDisplayName(funcName: string) {\n return _.capitalize(funcName.replace(/_/g, ' '));\n}\n\nfunction addNestedQueryHandler(def: QueryBuilderOperationDef, query: PromVisualQuery): PromVisualQuery {\n return {\n ...query,\n binaryQueries: [\n ...(query.binaryQueries ?? []),\n {\n operator: '/',\n query,\n },\n ],\n };\n}\n","import React from 'react';\nimport { Button, Col, Row, Select, Input, InputNumber, Switch } from 'antd';\nimport { CloseCircleOutlined, CloseOutlined, PlusOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport { SortableElement, SortableHandle } from 'react-sortable-hoc';\nimport { PromVisualQuery, PromVisualQueryOperation, VisualQueryOperationParamValue, QueryBuilderOperationParamDef, QueryBuilderOperationDef } from '../types';\nimport { getOperationDefinitions } from './utils';\nimport LabelNameSelect from '../LabelFilters/LabelNameSelect';\n\ninterface IProps {\n metric?: string;\n datasourceValue: string;\n params: {\n start: number;\n end: number;\n };\n query: PromVisualQuery;\n onChange: (query: PromVisualQuery) => void;\n operation: PromVisualQueryOperation;\n index: number;\n}\n\nconst SortableItem = SortableElement(({ children }) =>
{children}
);\nconst DragHandle = SortableHandle(({ children }) =>
{children}
);\nfunction renderOperationParamEditor(\n paramDef: QueryBuilderOperationParamDef,\n paramEditorProps: any,\n value: VisualQueryOperationParamValue,\n onChange: (val: VisualQueryOperationParamValue) => void,\n): React.ReactNode {\n if (paramDef.subType === 'labelNameSelect') {\n return (\n {\n onChange(val);\n }}\n />\n );\n }\n\n if (paramDef.options) {\n return (\n {\n onChange(val);\n }}\n >\n {_.map(paramDef.options, (option) => {\n return (\n \n {option.label}\n \n );\n })}\n \n );\n }\n\n switch (paramDef.type) {\n case 'boolean':\n return (\n {\n onChange(checked);\n }}\n />\n );\n case 'number':\n return (\n {\n onChange(val);\n }}\n />\n );\n case 'string':\n default:\n return (\n {\n onChange(e.target.value);\n }}\n />\n );\n }\n}\n\nexport default function Operation(props: IProps) {\n const { metric, datasourceValue, params, query, onChange, operation, index } = props;\n const { operations } = query;\n const addOperationOptions = getOperationDefinitions();\n const operationDef = _.find(addOperationOptions, { id: operation.id });\n const operationElements: React.ReactNode[] = [];\n\n for (let paramIndex = 0; paramIndex < operation.params.length; paramIndex++) {\n const paramDef = operationDef.params[Math.min(operationDef.params.length - 1, paramIndex)];\n\n operationElements.push(\n
\n {!paramDef.hideName &&
{paramDef.name}
}\n
\n \n
\n {renderOperationParamEditor(\n paramDef,\n {\n metric,\n datasourceValue,\n params,\n labels: query.labels,\n },\n _.get(operation, `params[${paramIndex}]`),\n (val) => {\n const newOperations = _.cloneDeep(operations);\n let newOperation = {\n ...operation,\n params: [...operation.params.slice(0, paramIndex), val, ...operation.params.slice(paramIndex + 1)],\n };\n if (operationDef.paramChangedHandler) {\n newOperation = operationDef.paramChangedHandler(index, newOperation, operationDef);\n }\n newOperations[index] = newOperation;\n onChange({\n ...query,\n operations: newOperations,\n });\n },\n )}\n \n {paramDef.restParam && (operation.params.length > operationDef.params.length || paramDef.optional) && (\n \n }\n title={`Remove ${paramDef.name}`}\n onClick={() => {\n let newOperation = {\n ...operation,\n params: [...operation.params.slice(0, paramIndex), ...operation.params.slice(paramIndex + 1)],\n };\n if (operationDef.paramChangedHandler) {\n newOperation = operationDef.paramChangedHandler(index, newOperation, operationDef);\n }\n const newOperations = _.cloneDeep(operations);\n newOperations[index] = newOperation;\n onChange({\n ...query,\n operations: newOperations,\n });\n }}\n />\n \n )}\n \n \n ,\n );\n }\n\n let restParam: React.ReactNode | undefined;\n if (operationDef.params.length > 0) {\n const lastParamDef = operationDef.params[operationDef.params.length - 1];\n if (lastParamDef.restParam) {\n restParam = (\n }\n onClick={() => {\n let newOperation = { ...operation, params: [...operation.params, ''] };\n if (operationDef.paramChangedHandler) {\n newOperation = operationDef.paramChangedHandler(operation.params.length, newOperation, operationDef);\n }\n const newOperations = _.cloneDeep(operations);\n newOperations[index] = newOperation;\n onChange({\n ...query,\n operations: newOperations,\n });\n }}\n >\n {lastParamDef.name}\n \n );\n }\n }\n\n if (!operationDef) {\n return null;\n }\n return (\n \n
\n
\n {operationDef.name}\n {\n onChange({\n ...query,\n operations: _.filter(operations, (o) => o.id !== operation.id),\n });\n }}\n />\n
\n
\n {operationElements}\n {restParam}\n {_.isEmpty(operationDef.params) &&
无参数
}\n
\n
\n
\n );\n}\n","import React from 'react';\nimport { Cascader, Button } from 'antd';\nimport _ from 'lodash';\nimport { arrayMoveImmutable } from 'array-move';\nimport { SortableContainer } from 'react-sortable-hoc';\nimport { getOperationDefinitions } from './utils';\nimport { PromVisualQuery } from '../types';\nimport Operation from './Operation';\n\ninterface IProps {\n metric?: string;\n datasourceValue: string;\n params: {\n start: number;\n end: number;\n };\n query: PromVisualQuery;\n value?: any[];\n onChange: (query: PromVisualQuery) => void;\n}\n\nconst SortableBody = SortableContainer(({ children }) =>
{children}
);\n\nexport default function index(props: IProps) {\n const { query, onChange } = props;\n const { operations } = query;\n const addOperationOptions = getOperationDefinitions();\n const categories = _.groupBy(addOperationOptions, 'category');\n\n return (\n
\n
\n {!_.isEmpty(operations) && (\n {\n const newOperations = arrayMoveImmutable(operations, oldIndex, newIndex);\n onChange({\n ...query,\n operations: newOperations,\n });\n }}\n >\n {_.map(operations, (operation, index) => {\n return ;\n })}\n \n )}\n {\n return {\n value: key,\n label: key,\n children: _.map(options, (option) => {\n return {\n value: option.id,\n label: option.name,\n };\n }),\n };\n })}\n onChange={(val) => {\n const id = _.last(val);\n const operationDef = _.find(addOperationOptions, { id });\n if (!operationDef) {\n return;\n }\n const firstOperationDef = _.find(addOperationOptions, { id: query.operations[0]?.id });\n onChange(operationDef.addOperationHandler(operationDef, query, firstOperationDef));\n }}\n >\n \n \n
\n
\n );\n}\n","import React from 'react';\nimport _ from 'lodash';\nimport PromQLInput from '@/components/PromQLInput';\nimport { PromVisualQuery, PromVisualQueryOperation, PromVisualQueryBinary, PromVisualQueryLabelFilter } from '../types';\nimport { getOperationDefinitions } from '../Operations/utils';\n\nfunction hasBinaryOp(query: PromVisualQuery): boolean {\n return (\n query.operations.find((op) => {\n const addOperationOptions = getOperationDefinitions();\n const def = _.find(addOperationOptions, { id: op.id });\n return def?.category === 'Binary operations';\n }) !== undefined\n );\n}\n\nfunction renderOperations(queryString: string, operations: PromVisualQueryOperation[]) {\n const addOperationOptions = getOperationDefinitions();\n for (const operation of operations) {\n const operationDef = _.find(addOperationOptions, { id: operation.id });\n if (!operationDef) {\n throw new Error(`Could not find operation ${operation.id} in the registry`);\n }\n queryString = operationDef.renderer(operation, operationDef, queryString);\n }\n\n return queryString;\n}\n\nfunction renderBinaryQueries(queryString: string, binaryQueries?: Array>) {\n if (binaryQueries) {\n for (const binQuery of binaryQueries) {\n queryString = `${renderBinaryQuery(queryString, binQuery)}`;\n }\n }\n return queryString;\n}\n\nfunction renderBinaryQuery(leftOperand: string, binaryQuery: PromVisualQueryBinary) {\n let result = leftOperand + ` ${binaryQuery.operator} `;\n\n if (binaryQuery.vectorMatches) {\n result += `${binaryQuery.vectorMatchesType}(${binaryQuery.vectorMatches}) `;\n }\n\n return result + renderQuery(binaryQuery.query, true);\n}\n\nfunction renderLabels(labels: PromVisualQueryLabelFilter[]) {\n const filteredLabels = _.filter(labels, (label) => {\n return !!label.label && !!label.value;\n });\n if (filteredLabels.length === 0) {\n return '';\n }\n\n let expr = '{';\n for (const filter of filteredLabels) {\n if (expr !== '{') {\n expr += ', ';\n }\n\n expr += `${filter.label}${filter.op}\"${filter.value}\"`;\n }\n\n return expr + `}`;\n}\n\nexport function renderQuery(query: PromVisualQuery, nested?: boolean) {\n let queryString = `${query.metric ?? ''}${renderLabels(query.labels)}`;\n queryString = renderOperations(queryString, query.operations);\n\n if (!nested && hasBinaryOp(query) && Boolean(query.binaryQueries?.length)) {\n queryString = `(${queryString})`;\n }\n\n queryString = renderBinaryQueries(queryString, query.binaryQueries);\n\n if (nested && (hasBinaryOp(query) || Boolean(query.binaryQueries?.length))) {\n queryString = `(${queryString})`;\n }\n\n return queryString;\n}\n\nexport default function index(props: { query: PromVisualQuery }) {\n const promql = renderQuery(props.query);\n if (!promql) return null;\n return (\n
\n \n
\n );\n}\n","import React from 'react';\nimport { Select, Input, Space } from 'antd';\nimport { CloseCircleOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport PromQueryBuilder from '../index';\nimport { PromVisualQueryBinary, PromVisualQuery } from '../types';\n\ninterface IProps {\n nestedQuery: PromVisualQueryBinary;\n datasourceValue: string;\n params: {\n start: number;\n end: number;\n };\n index: number;\n onChange: (index: number, update: PromVisualQueryBinary) => void;\n onRemove: (index: number) => void;\n}\n\nconst operators = ['+', '-', '*', '/', '%', '^', '==', '!=', '<', '<=', '>', '>='];\n\nexport default function NestedQuery(props: IProps) {\n const { nestedQuery, datasourceValue, params, index, onChange, onRemove } = props;\n\n return (\n
\n \n
Operator
\n {\n onChange(index, {\n ...nestedQuery,\n operator: value,\n });\n }}\n >\n {_.map(operators, (operator) => {\n return (\n \n {operator}\n \n );\n })}\n \n
Vector matches
\n \n {\n onChange(index, {\n ...nestedQuery,\n vectorMatchesType: value,\n });\n }}\n >\n on\n ignoring\n \n {\n onChange(index, {\n ...nestedQuery,\n vectorMatches: e.target.value,\n vectorMatchesType: nestedQuery.vectorMatchesType || 'on',\n });\n }}\n />\n \n onRemove(index)} />\n
\n
\n {\n onChange(index, { ...nestedQuery, query: update });\n }}\n />\n
\n
\n );\n}\n","import React from 'react';\nimport _ from 'lodash';\nimport { PromVisualQueryBinary, PromVisualQuery } from '../types';\nimport NestedQuery from './NestedQuery';\n\ninterface IProps {\n datasourceValue: string;\n params: {\n start: number;\n end: number;\n };\n value: PromVisualQuery['binaryQueries'];\n onChange: (value: PromVisualQuery['binaryQueries']) => void;\n}\n\nexport default function index(props: IProps) {\n const { datasourceValue, params, onChange } = props;\n const value = props.value ?? [];\n\n const onNestedQueryUpdate = (index: number, update: PromVisualQueryBinary) => {\n const updatedList = [...value];\n updatedList.splice(index, 1, update);\n onChange(updatedList);\n };\n\n const onRemove = (index: number) => {\n const updatedList = [...value.slice(0, index), ...value.slice(index + 1)];\n onChange(updatedList);\n };\n\n return (\n
\n {_.map(value, (item, index) => {\n return (\n \n );\n })}\n
\n );\n}\n","import { LRParser } from '@lezer/lr';\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst \n inf = 146,\n nan = 147,\n Bool = 1,\n Ignoring = 2,\n On = 3,\n GroupLeft = 4,\n GroupRight = 5,\n Offset = 6,\n Atan2 = 7,\n Avg = 8,\n Bottomk = 9,\n Count = 10,\n CountValues = 11,\n Group = 12,\n Max = 13,\n Min = 14,\n Quantile = 15,\n Stddev = 16,\n Stdvar = 17,\n Sum = 18,\n Topk = 19,\n By = 20,\n Without = 21,\n And = 22,\n Or = 23,\n Unless = 24,\n Start = 25,\n End = 26;\n\n// Copyright 2021 The Prometheus Authors\n\nconst keywordTokens = {\n inf: inf,\n nan: nan,\n bool: Bool,\n ignoring: Ignoring,\n on: On,\n group_left: GroupLeft,\n group_right: GroupRight,\n offset: Offset,\n};\n\nconst specializeIdentifier = (value, stack) => {\n return keywordTokens[value.toLowerCase()] || -1;\n};\n\nconst contextualKeywordTokens = {\n avg: Avg,\n atan2: Atan2,\n bottomk: Bottomk,\n count: Count,\n count_values: CountValues,\n group: Group,\n max: Max,\n min: Min,\n quantile: Quantile,\n stddev: Stddev,\n stdvar: Stdvar,\n sum: Sum,\n topk: Topk,\n by: By,\n without: Without,\n and: And,\n or: Or,\n unless: Unless,\n start: Start,\n end: End,\n};\n\nconst extendIdentifier = (value, stack) => {\n return contextualKeywordTokens[value.toLowerCase()] || -1;\n};\n\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst spec_Identifier = {__proto__:null,absent_over_time:307, absent:309, abs:311, acos:313, acosh:315, asin:317, asinh:319, atan:321, atanh:323, avg_over_time:325, ceil:327, changes:329, clamp:331, clamp_max:333, clamp_min:335, cos:337, cosh:339, count_over_time:341, days_in_month:343, day_of_month:345, day_of_week:347, deg:349, delta:351, deriv:353, exp:355, floor:357, histogram_quantile:359, holt_winters:361, hour:363, idelta:365, increase:367, irate:369, label_replace:371, label_join:373, last_over_time:375, ln:377, log10:379, log2:381, max_over_time:383, min_over_time:385, minute:387, month:389, pi:391, predict_linear:393, present_over_time:395, quantile_over_time:397, rad:399, rate:401, resets:403, round:405, scalar:407, sgn:409, sin:411, sinh:413, sort:415, sort_desc:417, sqrt:419, stddev_over_time:421, stdvar_over_time:423, sum_over_time:425, tan:427, tanh:429, timestamp:431, time:433, vector:435, year:437};\nconst parser = LRParser.deserialize({\n version: 13,\n states: \"6[OYQPOOO&{QPOOOOQO'#C{'#C{O'QQPO'#CzQ']QQOOOOQO'#De'#DeO'WQPO'#DdOOQO'#E}'#E}O(jQPO'#FTOYQPO'#FPOYQPO'#FSOOQO'#FV'#FVO.fQSO'#FWO.nQQO'#FUOOQO'#FU'#FUOOQO'#Cy'#CyOOQO'#Df'#DfOOQO'#Dh'#DhOOQO'#Di'#DiOOQO'#Dj'#DjOOQO'#Dk'#DkOOQO'#Dl'#DlOOQO'#Dm'#DmOOQO'#Dn'#DnOOQO'#Do'#DoOOQO'#Dp'#DpOOQO'#Dq'#DqOOQO'#Dr'#DrOOQO'#Ds'#DsOOQO'#Dt'#DtOOQO'#Du'#DuOOQO'#Dv'#DvOOQO'#Dw'#DwOOQO'#Dx'#DxOOQO'#Dy'#DyOOQO'#Dz'#DzOOQO'#D{'#D{OOQO'#D|'#D|OOQO'#D}'#D}OOQO'#EO'#EOOOQO'#EP'#EPOOQO'#EQ'#EQOOQO'#ER'#EROOQO'#ES'#ESOOQO'#ET'#ETOOQO'#EU'#EUOOQO'#EV'#EVOOQO'#EW'#EWOOQO'#EX'#EXOOQO'#EY'#EYOOQO'#EZ'#EZOOQO'#E['#E[OOQO'#E]'#E]OOQO'#E^'#E^OOQO'#E_'#E_OOQO'#E`'#E`OOQO'#Ea'#EaOOQO'#Eb'#EbOOQO'#Ec'#EcOOQO'#Ed'#EdOOQO'#Ee'#EeOOQO'#Ef'#EfOOQO'#Eg'#EgOOQO'#Eh'#EhOOQO'#Ei'#EiOOQO'#Ej'#EjOOQO'#Ek'#EkOOQO'#El'#ElOOQO'#Em'#EmOOQO'#En'#EnOOQO'#Eo'#EoOOQO'#Ep'#EpOOQO'#Eq'#EqOOQO'#Er'#ErOOQO'#Es'#EsOOQO'#Et'#EtOOQO'#Eu'#EuOOQO'#Ev'#EvOOQO'#Ew'#EwOOQO'#Ex'#ExOOQO'#Ey'#EyOOQO'#Ez'#EzQOQPOOO0XQPO'#C|O0^QPO'#DRO'WQPO,59fO0eQQO,59fO2RQPO,59oO2RQPO,59oO2RQPO,59oO2RQPO,59oO2RQPO,59oO7}QQO,5;gO8SQQO,5;jO8[QPO,5;yOOQO,5:O,5:OOOQO,5;i,5;iO8sQQO,5;kO8zQQO,5;nO:bQPO'#FYO:pQPO,5;rOOQO'#FX'#FXOOQO,5;r,5;rOOQO,5;p,5;pO:xQSO'#C}OOQO,59h,59hO;QQPO,59mO;YQQO'#DSOOQO,59m,59mOOQO1G/Q1G/QO0XQPO'#DWOAVQPO'#DVOAaQPO'#DVOYQPO1G/ZOYQPO1G/ZOYQPO1G/ZOYQPO1G/ZOYQPO1G/ZOAkQSO1G1ROOQO1G1U1G1UOAsQQO1G1UOAxQPO'#E}OOQO'#Fa'#FaOOQO1G1e1G1eOBTQPO1G1eOOQO1G1V1G1VOOQO'#FZ'#FZOBYQPO,5;tOB_QSO1G1^OOQO1G1^1G1^OOQO'#DP'#DPOBgQPO,59iOOQO'#DO'#DOOOQO,59i,59iOYQPO,59nOOQO1G/X1G/XOOQO,59r,59rOH_QPO,59qOHfQPO,59qOI}QQO7+$uOJ_QQO7+$uOKsQQO7+$uOLZQQO7+$uOMrQQO7+$uOOQO7+&m7+&mON]QQO7+&sOOQO7+&p7+&pONeQPO7+'POOQO1G1`1G1`OOQO1G1_1G1_OOQO7+&x7+&xONjQSO1G/TOOQO1G/T1G/TONrQQO1G/YOOQO1G/]1G/]ON|QPO1G/]OOQO< (specializeIdentifier(value) << 1)},{term: 57, get: (value, stack) => (extendIdentifier(value) << 1) | 1},{term: 57, get: value => spec_Identifier[value] || -1}],\n tokenPrec: 0\n});\n// This file was generated by lezer-generator. You probably shouldn't edit it.\nconst \n inf$1 = 146,\n nan$1 = 147,\n Bool$1 = 1,\n Ignoring$1 = 2,\n On$1 = 3,\n GroupLeft$1 = 4,\n GroupRight$1 = 5,\n Offset$1 = 6,\n Atan2$1 = 7,\n Avg$1 = 8,\n Bottomk$1 = 9,\n Count$1 = 10,\n CountValues$1 = 11,\n Group$1 = 12,\n Max$1 = 13,\n Min$1 = 14,\n Quantile$1 = 15,\n Stddev$1 = 16,\n Stdvar$1 = 17,\n Sum$1 = 18,\n Topk$1 = 19,\n By$1 = 20,\n Without$1 = 21,\n And$1 = 22,\n Or$1 = 23,\n Unless$1 = 24,\n Start$1 = 25,\n End$1 = 26,\n LineComment = 27,\n PromQL = 28,\n Expr = 29,\n AggregateExpr = 30,\n AggregateOp = 31,\n AggregateModifier = 32,\n GroupingLabels = 33,\n GroupingLabelList = 34,\n GroupingLabel = 35,\n LabelName = 36,\n FunctionCallBody = 37,\n FunctionCallArgs = 38,\n BinaryExpr = 39,\n Pow = 40,\n BinModifiers = 41,\n OnOrIgnoring = 42,\n Mul = 43,\n Div = 44,\n Mod = 45,\n Add = 46,\n Sub = 47,\n Eql = 48,\n Gte = 49,\n Gtr = 50,\n Lte = 51,\n Lss = 52,\n Neq = 53,\n FunctionCall = 54,\n FunctionIdentifier = 55,\n AbsentOverTime = 56,\n Identifier = 57,\n Absent = 58,\n Abs = 59,\n Acos = 60,\n Acosh = 61,\n Asin = 62,\n Asinh = 63,\n Atan = 64,\n Atanh = 65,\n AvgOverTime = 66,\n Ceil = 67,\n Changes = 68,\n Clamp = 69,\n ClampMax = 70,\n ClampMin = 71,\n Cos = 72,\n Cosh = 73,\n CountOverTime = 74,\n DaysInMonth = 75,\n DayOfMonth = 76,\n DayOfWeek = 77,\n Deg = 78,\n Delta = 79,\n Deriv = 80,\n Exp = 81,\n Floor = 82,\n HistogramQuantile = 83,\n HoltWinters = 84,\n Hour = 85,\n Idelta = 86,\n Increase = 87,\n Irate = 88,\n LabelReplace = 89,\n LabelJoin = 90,\n LastOverTime = 91,\n Ln = 92,\n Log10 = 93,\n Log2 = 94,\n MaxOverTime = 95,\n MinOverTime = 96,\n Minute = 97,\n Month = 98,\n Pi = 99,\n PredictLinear = 100,\n PresentOverTime = 101,\n QuantileOverTime = 102,\n Rad = 103,\n Rate = 104,\n Resets = 105,\n Round = 106,\n Scalar = 107,\n Sgn = 108,\n Sin = 109,\n Sinh = 110,\n Sort = 111,\n SortDesc = 112,\n Sqrt = 113,\n StddevOverTime = 114,\n StdvarOverTime = 115,\n SumOverTime = 116,\n Tan = 117,\n Tanh = 118,\n Timestamp = 119,\n Time = 120,\n Vector = 121,\n Year = 122,\n MatrixSelector = 123,\n Duration = 124,\n NumberLiteral = 125,\n OffsetExpr = 126,\n ParenExpr = 127,\n StringLiteral = 128,\n SubqueryExpr = 129,\n UnaryExpr = 130,\n UnaryOp = 131,\n VectorSelector = 132,\n MetricIdentifier = 133,\n LabelMatchers = 134,\n LabelMatchList = 135,\n LabelMatcher = 136,\n MatchOp = 137,\n EqlSingle = 138,\n EqlRegex = 139,\n NeqRegex = 140,\n StepInvariantExpr = 141,\n At = 142,\n AtModifierPreprocessors = 143,\n MetricName = 144;\n\nexport { Abs, Absent, AbsentOverTime, Acos, Acosh, Add, AggregateExpr, AggregateModifier, AggregateOp, And$1 as And, Asin, Asinh, At, AtModifierPreprocessors, Atan, Atan2$1 as Atan2, Atanh, Avg$1 as Avg, AvgOverTime, BinModifiers, BinaryExpr, Bool$1 as Bool, Bottomk$1 as Bottomk, By$1 as By, Ceil, Changes, Clamp, ClampMax, ClampMin, Cos, Cosh, Count$1 as Count, CountOverTime, CountValues$1 as CountValues, DayOfMonth, DayOfWeek, DaysInMonth, Deg, Delta, Deriv, Div, Duration, End$1 as End, Eql, EqlRegex, EqlSingle, Exp, Expr, Floor, FunctionCall, FunctionCallArgs, FunctionCallBody, FunctionIdentifier, Group$1 as Group, GroupLeft$1 as GroupLeft, GroupRight$1 as GroupRight, GroupingLabel, GroupingLabelList, GroupingLabels, Gte, Gtr, HistogramQuantile, HoltWinters, Hour, Idelta, Identifier, Ignoring$1 as Ignoring, Increase, Irate, LabelJoin, LabelMatchList, LabelMatcher, LabelMatchers, LabelName, LabelReplace, LastOverTime, LineComment, Ln, Log10, Log2, Lss, Lte, MatchOp, MatrixSelector, Max$1 as Max, MaxOverTime, MetricIdentifier, MetricName, Min$1 as Min, MinOverTime, Minute, Mod, Month, Mul, Neq, NeqRegex, NumberLiteral, Offset$1 as Offset, OffsetExpr, On$1 as On, OnOrIgnoring, Or$1 as Or, ParenExpr, Pi, Pow, PredictLinear, PresentOverTime, PromQL, Quantile$1 as Quantile, QuantileOverTime, Rad, Rate, Resets, Round, Scalar, Sgn, Sin, Sinh, Sort, SortDesc, Sqrt, Start$1 as Start, Stddev$1 as Stddev, StddevOverTime, Stdvar$1 as Stdvar, StdvarOverTime, StepInvariantExpr, StringLiteral, Sub, SubqueryExpr, Sum$1 as Sum, SumOverTime, Tan, Tanh, Time, Timestamp, Topk$1 as Topk, UnaryExpr, UnaryOp, Unless$1 as Unless, Vector, VectorSelector, Without$1 as Without, Year, inf$1 as inf, nan$1 as nan, parser };\n","import _ from 'lodash';\nimport { SyntaxNode, TreeCursor } from '@lezer/common';\nimport {\n AggregateExpr,\n AggregateModifier,\n AggregateOp,\n BinaryExpr,\n BinModifiers,\n Expr,\n FunctionCall,\n FunctionCallArgs,\n FunctionCallBody,\n FunctionIdentifier,\n GroupingLabel,\n GroupingLabelList,\n GroupingLabels,\n LabelMatcher,\n LabelName,\n MatchOp,\n MetricIdentifier,\n NumberLiteral,\n On,\n OnOrIgnoring,\n ParenExpr,\n parser,\n StringLiteral,\n VectorSelector,\n Without,\n} from 'lezer-promql';\n\nimport { PromVisualQuery, PromVisualQueryLabelFilter, PromVisualQueryOperation, PromVisualQueryBinary, VisualQueryOperationParamValue, PromVisualQueryOperationId } from '../types';\nimport { arithmeticBinaryOperators, comparisonBinaryOperators } from '../Operations/utils';\n\nexport function buildPromVisualQueryFromPromQL(expr: string): Context {\n const tree = parser.parse(expr);\n const node = tree.topNode as any;\n\n const visQuery: PromVisualQuery = {\n metric: '',\n labels: [],\n operations: [],\n };\n const context: Context = {\n query: visQuery,\n errors: [],\n };\n\n try {\n handleExpression(expr, node, context);\n } catch (err) {\n console.error(err);\n if (err instanceof Error) {\n context.errors.push({\n text: err.message,\n });\n }\n }\n\n if (isEmptyQuery(context.query)) {\n context.errors = [];\n }\n return context;\n}\n\ninterface ParsingError {\n text: string;\n from?: number;\n to?: number;\n parentType?: string;\n}\n\ninterface Context {\n query: PromVisualQuery;\n errors: ParsingError[];\n}\n\nfunction handleExpression(expr: string, node: SyntaxNode, context: Context) {\n const visQuery = context.query;\n\n switch (node.type.id) {\n case MetricIdentifier: {\n visQuery.metric = getString(expr, node);\n break;\n }\n\n case LabelMatcher: {\n visQuery.labels.push(getLabel(expr, node));\n const err = node.getChild(ErrorId);\n if (err) {\n context.errors.push(makeError(expr, err));\n }\n break;\n }\n\n case FunctionCall: {\n handleFunction(expr, node, context);\n break;\n }\n\n case AggregateExpr: {\n handleAggregation(expr, node, context);\n break;\n }\n\n case BinaryExpr: {\n handleBinary(expr, node, context);\n break;\n }\n\n case ErrorId: {\n if (isIntervalVariableError(node)) {\n break;\n }\n context.errors.push(makeError(expr, node));\n break;\n }\n\n default: {\n if (node.type.id === ParenExpr) {\n context.errors.push(makeError(expr, node));\n }\n let child = node.firstChild;\n while (child) {\n handleExpression(expr, child, context);\n child = child.nextSibling;\n }\n }\n }\n}\n\nfunction isIntervalVariableError(node: SyntaxNode) {\n return node.prevSibling?.type.id === Expr && node.prevSibling?.firstChild?.type.id === VectorSelector;\n}\n\nfunction getLabel(expr: string, node: SyntaxNode): PromVisualQueryLabelFilter {\n const label = getString(expr, node.getChild(LabelName));\n const op = getString(expr, node.getChild(MatchOp));\n const value = getString(expr, node.getChild(StringLiteral)).replace(/\"|'/g, '');\n return {\n label,\n op,\n value,\n };\n}\n\nconst rangeFunctions = ['changes', 'rate', 'irate', 'increase', 'delta'];\n\nfunction handleFunction(expr: string, node: SyntaxNode, context: Context) {\n const visQuery = context.query;\n const nameNode = node.getChild(FunctionIdentifier);\n const funcName = getString(expr, nameNode);\n\n const body = node.getChild(FunctionCallBody);\n const callArgs = body!.getChild(FunctionCallArgs);\n const params: any[] = [];\n let interval = '';\n\n if (rangeFunctions.includes(funcName) || funcName.endsWith('_over_time')) {\n let match = getString(expr, node).match(/\\[(.+)\\]/);\n if (match?.[1]) {\n interval = match[1];\n params.push(match[1]);\n }\n }\n\n const op = { id: funcName, params };\n visQuery.operations.unshift(op);\n\n if (callArgs) {\n if (getString(expr, callArgs) === interval + ']') {\n return;\n }\n updateFunctionArgs(expr, callArgs, context, op);\n }\n}\n\nfunction handleAggregation(expr: string, node: SyntaxNode, context: Context) {\n const visQuery = context.query;\n const nameNode = node.getChild(AggregateOp);\n let funcName = getString(expr, nameNode);\n\n const modifier = node.getChild(AggregateModifier);\n const labels: any = [];\n\n if (modifier) {\n const byModifier = modifier.getChild(`By`);\n if (byModifier && funcName) {\n funcName = `__${funcName}_by`;\n }\n\n const withoutModifier = modifier.getChild(Without);\n if (withoutModifier) {\n funcName = `__${funcName}_without`;\n }\n\n labels.push(...getAllByType(expr, modifier, GroupingLabel));\n }\n\n const body = node.getChild(FunctionCallBody);\n const callArgs = body!.getChild(FunctionCallArgs);\n\n const op: PromVisualQueryOperation = { id: funcName, params: [] };\n visQuery.operations.unshift(op);\n updateFunctionArgs(expr, callArgs, context, op);\n op.params.push(...labels);\n}\n\nfunction updateFunctionArgs(expr: string, node: SyntaxNode | null, context: Context, op: PromVisualQueryOperation) {\n if (!node) {\n return;\n }\n switch (node.type.id) {\n case Expr:\n case FunctionCallArgs: {\n let child = node.firstChild;\n while (child) {\n updateFunctionArgs(expr, child, context, op);\n child = child.nextSibling;\n }\n break;\n }\n\n case NumberLiteral: {\n op.params.push(parseFloat(getString(expr, node)));\n break;\n }\n\n case StringLiteral: {\n op.params.push(getString(expr, node).replace(/\"/g, ''));\n break;\n }\n\n default: {\n handleExpression(expr, node, context);\n }\n }\n}\n\nfunction handleBinary(expr: string, node: SyntaxNode, context: Context) {\n const visQuery = context.query;\n const left = node.firstChild!;\n const op = getString(expr, left.nextSibling);\n const binModifier = getBinaryModifier(expr, node.getChild(BinModifiers));\n\n const right = node.lastChild!;\n\n const opDef = binaryScalarOperatorToOperatorName(op);\n\n const leftNumber = left.getChild(NumberLiteral);\n const rightNumber = right.getChild(NumberLiteral);\n\n const rightBinary = right.getChild(BinaryExpr);\n\n if (leftNumber) {\n } else {\n handleExpression(expr, left, context);\n }\n\n if (rightNumber) {\n visQuery.operations.push(makeBinOp(op, opDef, expr, right, !!binModifier?.isBool));\n } else if (rightBinary) {\n const leftMostChild = getLeftMostChild(right);\n if (leftMostChild?.type.id === NumberLiteral) {\n visQuery.operations.push(makeBinOp(op, opDef, expr, leftMostChild, !!binModifier?.isBool));\n }\n\n handleExpression(expr, right, context);\n } else {\n visQuery.binaryQueries = visQuery.binaryQueries || [];\n const binQuery: PromVisualQueryBinary = {\n operator: op,\n query: {\n metric: '',\n labels: [],\n operations: [],\n },\n };\n if (binModifier?.isMatcher) {\n binQuery.vectorMatchesType = binModifier.matchType;\n binQuery.vectorMatches = binModifier.matches;\n }\n visQuery.binaryQueries.push(binQuery);\n handleExpression(expr, right, {\n query: binQuery.query,\n errors: context.errors,\n });\n }\n}\n\nfunction getBinaryModifier(\n expr: string,\n node: SyntaxNode | null,\n): { isBool: true; isMatcher: false } | { isBool: false; isMatcher: true; matches: string; matchType: 'ignoring' | 'on' } | undefined {\n if (!node) {\n return undefined;\n }\n if (node.getChild('Bool')) {\n return { isBool: true, isMatcher: false };\n } else {\n const matcher = node.getChild(OnOrIgnoring);\n if (!matcher) {\n return undefined;\n }\n const labels = getString(expr, matcher.getChild(GroupingLabels)?.getChild(GroupingLabelList));\n return {\n isMatcher: true,\n isBool: false,\n matches: labels,\n matchType: matcher.getChild(On) ? 'on' : 'ignoring',\n };\n }\n}\n\nfunction isEmptyQuery(query: PromVisualQuery) {\n if (query.labels.length === 0 && query.operations.length === 0 && !query.metric) {\n return true;\n }\n return false;\n}\n\nconst ErrorId = 0;\n\nfunction getLeftMostChild(cur: SyntaxNode): SyntaxNode {\n return cur.firstChild ? getLeftMostChild(cur.firstChild) : cur;\n}\n\nfunction makeError(expr: string, node: SyntaxNode) {\n return {\n text: getString(expr, node),\n from: node.from,\n to: node.to,\n parentType: node.parent?.name,\n };\n}\n\nfunction getString(expr: string, node: SyntaxNode | TreeCursor | null | undefined) {\n if (!node) {\n return '';\n }\n return returnVariables(expr.substring(node.from, node.to));\n}\n\nconst varTypeFunc = [(v: string, f?: string) => `\\$${v}`, (v: string, f?: string) => `[[${v}${f ? `:${f}` : ''}]]`, (v: string, f?: string) => `\\$\\{${v}${f ? `:${f}` : ''}\\}`];\n\nfunction returnVariables(expr: string) {\n return expr.replace(/__V_(\\d)__(.+?)__V__(?:__F__(\\w+)__F__)?/g, (match, type, v, f) => {\n return varTypeFunc[parseInt(type, 10)](v, f);\n });\n}\n\nfunction makeBinOp(op: string, opDef: { id: string; comparison?: boolean }, expr: string, numberNode: SyntaxNode, hasBool: boolean): PromVisualQueryOperation {\n const params: VisualQueryOperationParamValue[] = [op, parseFloat(getString(expr, numberNode))];\n if (opDef.comparison) {\n params.push(hasBool);\n }\n return {\n id: opDef.id,\n params,\n };\n}\n\nfunction getAllByType(expr: string, cur: SyntaxNode, type: number | string): string[] {\n if (cur.type.id === type || cur.name === type) {\n return [getString(expr, cur)];\n }\n const values: string[] = [];\n let pos = 0;\n let child = cur.childAfter(pos);\n while (child) {\n values.push(...getAllByType(expr, child, type));\n pos = child.to;\n child = cur.childAfter(pos);\n }\n return values;\n}\n\nfunction binaryScalarOperatorToOperatorName(op: string) {\n const acc = {};\n _.forEach(arithmeticBinaryOperators, (item) => {\n acc[item] = {\n id: PromVisualQueryOperationId.ArithmeticBinary,\n };\n });\n _.forEach(comparisonBinaryOperators, (item) => {\n acc[item] = {\n id: PromVisualQueryOperationId.ComparisonBinary,\n comparison: true,\n };\n });\n return acc[op];\n}\n","import React from 'react';\nimport MetricSelect from './MetricSelect';\nimport LabelFilters from './LabelFilters';\nimport Operations from './Operations';\nimport RawQuery from './RawQuery';\nimport { PromVisualQuery } from './types';\nimport NestedQueryList from './NestedQueryList';\nimport { normalizeDefaultValue } from './utils';\nimport './style.less';\n\nexport type { PromVisualQuery } from './types';\nexport { renderQuery } from './RawQuery';\nexport { buildPromVisualQueryFromPromQL } from './utils/buildPromVisualQueryFromPromQL';\n\ninterface IProps {\n datasourceValue: string;\n params: {\n start: number;\n end: number;\n };\n rawQueryOpen?: boolean;\n value: PromVisualQuery;\n onChange: (query: PromVisualQuery) => void;\n}\n\nexport default function index(props: IProps) {\n const { datasourceValue, params, rawQueryOpen = true, value, onChange } = props;\n const query = normalizeDefaultValue(value);\n\n return (\n
\n
\n {\n onChange({\n ...query,\n metric: val,\n });\n }}\n />\n {\n onChange({\n ...query,\n labels: val,\n });\n }}\n />\n
\n {\n onChange(val);\n }}\n />\n {query.binaryQueries && query.binaryQueries.length > 0 && (\n {\n onChange({\n ...query,\n binaryQueries: val,\n });\n }}\n />\n )}\n {rawQueryOpen && }\n
\n );\n}\n","import _ from 'lodash';\nimport { PromVisualQuery } from '../types';\n\nexport const normalizeDefaultValue = (value: PromVisualQuery) => {\n const valueClone = _.cloneDeep(value);\n if (valueClone.labels.length === 0) {\n valueClone.labels.push({\n label: '',\n value: '',\n op: '=',\n });\n }\n return valueClone;\n};\n","import React, { useState } from 'react';\nimport { Modal } from 'antd';\nimport moment from 'moment';\nimport ModalHOC, { ModalWrapProps } from '@/components/ModalHOC';\nimport { IRawTimeRange, parseRange } from '@/components/TimeRangePicker';\nimport PromQueryBuilder, { PromVisualQuery, renderQuery, buildPromVisualQueryFromPromQL } from './index';\n\ninterface IProps {\n datasourceValue: string;\n range: IRawTimeRange;\n value?: string;\n onChange: (value: string) => void;\n}\n\nfunction PromQueryBuilderModal(props: ModalWrapProps & IProps) {\n const { visible, datasourceValue, range, value = '', onChange } = props;\n const parsedRange = parseRange(range);\n const start = moment(parsedRange.start).unix();\n const end = moment(parsedRange.end).unix();\n const queryContext = buildPromVisualQueryFromPromQL(value);\n const [query, setQuery] = useState(queryContext.query);\n\n return (\n {\n onChange(renderQuery(query));\n props.destroy();\n }}\n onCancel={() => {\n props.destroy();\n }}\n >\n {\n setQuery(query);\n }}\n />\n \n );\n}\n\nexport default ModalHOC(PromQueryBuilderModal);\n","import React from 'react';\nimport { Row, Col, Button } from 'antd';\nimport _ from 'lodash';\nimport PromQueryBuilderModal from '@/components/PromQueryBuilder/PromQueryBuilderModal';\nimport PromQLInput, { CMExpressionInputProps } from './index';\n\nexport function PromQLInputWithBuilder(props: CMExpressionInputProps & { cluster: string }) {\n return (\n \n
\n \n \n \n {\n PromQueryBuilderModal({\n // TODO: PromQL 默认是最近12小时,这块应该从使用组件的环境获取实际的时间范围\n range: {\n start: 'now-12h',\n end: 'now',\n },\n datasourceValue: props.cluster,\n value: props.value,\n onChange: (val) => {\n props.onChange && props.onChange(val);\n },\n });\n }}\n >\n 新手模式\n \n \n \n );\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useEffect, useRef } from 'react';\nimport classNames from 'classnames';\nimport _ from 'lodash';\nimport { EditorView, highlightSpecialChars, keymap, ViewUpdate, placeholder } from '@codemirror/view';\nimport { EditorState, Prec } from '@codemirror/state';\nimport { indentOnInput } from '@codemirror/language';\nimport { history, historyKeymap } from '@codemirror/history';\nimport { defaultKeymap, insertNewlineAndIndent } from '@codemirror/commands';\nimport { bracketMatching } from '@codemirror/matchbrackets';\nimport { closeBrackets, closeBracketsKeymap } from '@codemirror/closebrackets';\nimport { highlightSelectionMatches } from '@codemirror/search';\nimport { commentKeymap } from '@codemirror/comment';\nimport { lintKeymap } from '@codemirror/lint';\nimport { autocompletion, completionKeymap } from '@codemirror/autocomplete';\nimport { PromQLExtension } from 'codemirror-promql';\nimport { baseTheme, promqlHighlighter } from './CMTheme';\n\nexport { PromQLInputWithBuilder } from './PromQLInputWithBuilder';\n\nconst promqlExtension = new PromQLExtension();\n\nexport interface CMExpressionInputProps {\n url: string;\n readonly?: boolean;\n headers?: { [index: string]: string };\n value?: string;\n onChange?: (expr?: string) => void;\n executeQuery?: (expr?: string) => void;\n validateTrigger?: string[];\n completeEnabled?: boolean;\n trigger?: ('onBlur' | 'onEnter')[]; // 触发 onChang 的事件\n}\n\nconst ExpressionInput = (\n {\n url,\n headers,\n value,\n onChange,\n executeQuery,\n readonly = false,\n validateTrigger = ['onChange', 'onBlur'],\n completeEnabled = true,\n trigger = ['onBlur', 'onEnter'],\n }: CMExpressionInputProps,\n ref,\n) => {\n const containerRef = useRef(null);\n const viewRef = useRef(null);\n const executeQueryCallback = useRef(executeQuery);\n const realValue = useRef(value || '');\n const defaultHeaders = {\n Authorization: `Bearer ${localStorage.getItem('access_token') || ''}`,\n };\n\n useEffect(() => {\n executeQueryCallback.current = executeQuery;\n promqlExtension\n .activateCompletion(true)\n .activateLinter(true)\n .setComplete(\n completeEnabled\n ? {\n remote: {\n url,\n fetchFn: (resource, options = {}) => {\n const params = options.body?.toString();\n const search = params ? `?${params}` : '';\n return fetch(resource + search, {\n method: 'Get',\n headers: new Headers(\n headers\n ? {\n ...defaultHeaders,\n ...headers,\n }\n : defaultHeaders,\n ),\n });\n },\n },\n }\n : undefined,\n );\n\n // Create or reconfigure the editor.\n const view = viewRef.current;\n if (view === null) {\n // If the editor does not exist yet, create it.\n if (!containerRef.current) {\n throw new Error('expected CodeMirror container element to exist');\n }\n\n const startState = EditorState.create({\n doc: value,\n extensions: [\n baseTheme,\n highlightSpecialChars(),\n history(),\n EditorState.allowMultipleSelections.of(true),\n indentOnInput(),\n bracketMatching(),\n closeBrackets(),\n autocompletion(),\n highlightSelectionMatches(),\n promqlHighlighter,\n EditorView.lineWrapping,\n keymap.of([...closeBracketsKeymap, ...defaultKeymap, ...historyKeymap, ...commentKeymap, ...completionKeymap, ...lintKeymap]),\n placeholder('Input promql to query. Press Shift+Enter for newlines'),\n promqlExtension.asExtension(),\n EditorView.editable.of(!readonly),\n keymap.of([\n {\n key: 'Escape',\n run: (v: EditorView): boolean => {\n v.contentDOM.blur();\n return false;\n },\n },\n ]),\n Prec.override(\n keymap.of([\n {\n key: 'Enter',\n run: (v: EditorView): boolean => {\n if (typeof executeQueryCallback.current === 'function') {\n executeQueryCallback.current(realValue.current);\n }\n if (typeof onChange === 'function' && _.includes(trigger, 'onEnter')) {\n onChange(realValue.current);\n }\n return true;\n },\n },\n {\n key: 'Shift-Enter',\n run: insertNewlineAndIndent,\n },\n ]),\n ),\n EditorView.updateListener.of((update: ViewUpdate): void => {\n if (typeof onChange === 'function') {\n const val = update.state.doc.toString();\n if (val !== realValue.current) {\n realValue.current = val;\n if (_.includes(validateTrigger, 'onChange')) {\n onChange(val);\n }\n }\n }\n }),\n ],\n });\n\n const view = new EditorView({\n state: startState,\n parent: containerRef.current,\n });\n\n viewRef.current = view;\n\n if (ref) {\n ref.current = view;\n }\n\n view.focus();\n }\n }, [onChange, JSON.stringify(headers), completeEnabled]);\n\n useEffect(() => {\n if (realValue.current !== value) {\n const oldValue = realValue.current;\n realValue.current = value || '';\n const view = viewRef.current;\n if (view === null) {\n return;\n }\n view.dispatch(\n view.state.update({\n changes: { from: 0, to: oldValue?.length || 0, insert: value },\n }),\n );\n }\n }, [value]);\n\n return (\n {\n if (typeof onChange === 'function' && _.includes(trigger, 'onBlur')) {\n if (realValue.current !== value) {\n onChange(realValue.current);\n }\n }\n }}\n >\n
\n
\n );\n};\n\nexport default React.forwardRef(ExpressionInput);\n","import React, { useState, useEffect } from 'react';\nimport { Form, InputNumber, Radio, Select, Checkbox, Space, Input } from 'antd';\nimport { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';\nimport { getBrainParams } from '@/services/warning';\n\ninterface IProps {\n form: any;\n}\n\nexport default function index(props: IProps) {\n const { form } = props;\n const [settingsVisible, setSettingsVisible] = useState(false);\n const [defaultParams, setDefaultParams] = useState({});\n\n useEffect(() => {\n getBrainParams().then((res) => {\n setDefaultParams(res);\n });\n }, []);\n\n return (\n <>\n \n {({ getFieldValue }) => {\n return (\n <>\n \n {\n if (e.target.value === 'abnormalDetection') {\n form.setFieldsValue({\n algorithm: 'holtwinters',\n algo_params: defaultParams?.holtwinters,\n });\n } else {\n form.setFieldsValue({\n algorithm: '',\n algo_params: undefined,\n });\n }\n }}\n >\n 阈值告警\n 智能告警\n \n \n {getFieldValue('algorithm') === 'holtwinters' && (\n <>\n \n \n \n \n \n \n
\n 季节性周期时间为:\n \n \n {' '}\n {/* , 根据{' '}\n \n \n {' '}\n 秒区间, 对数据进行平滑计算 */}\n
\n
\n
偏离
\n
\n
\n {\n return e.target.checked ? 1 : 0;\n }}\n >\n 上界\n \n \n \n {' '}\n 倍误差\n
\n
\n {\n return e.target.checked ? 1 : 0;\n }}\n >\n 下界\n \n \n \n {' '}\n 倍误差\n
\n
\n
\n
\n \n {(fields, { add, remove }) => (\n <>\n
\n 同环比{' '}\n {\n add({\n operator: 1,\n offset: 86400,\n bound_type: 0,\n });\n }}\n />\n
\n {fields.map(({ key, name, ...restField }) => (\n \n \n \n \n 相比\n \n \n \n 天前同时期\n \n \n \n \n \n \n {' %'}\n remove(name)} />\n \n ))}\n \n )}\n
\n
\n \n
\n \n )}\n \n );\n }}\n
\n \n );\n}\n","import React from 'react';\nimport { Input } from 'antd';\nimport classNames from 'classnames';\nimport './style.less';\n\ninterface IProps {\n children: React.ReactNode;\n label: React.ReactNode;\n labelWidth?: number | string;\n noStyle?: boolean;\n}\n\nexport default function index(props: IProps) {\n const { children, label, labelWidth = 'max-content', noStyle = false } = props;\n return (\n \n \n {label}\n \n
{children}
\n
\n );\n}\n","import React, { useState, useEffect } from 'react';\nimport { Form, Row, Col, Input, Select, AutoComplete } from 'antd';\nimport { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport { useDebounceFn } from 'ahooks';\nimport { getFields } from '@/services/warning';\nimport InputGroupWithFormItem from '@/components/InputGroupWithFormItem';\n\ninterface IProps {\n prefixField?: any;\n prefixFields?: string[]; // 前缀字段名\n prefixNameField?: string[]; // 列表字段名\n cate: string;\n cluster: string[];\n index: string;\n valueRefVisible?: boolean;\n}\n\nconst alphabet = 'ABCDEFGHIGKLMNOPQRSTUVWXYZ'.split('');\nconst functions = ['count', 'avg', 'sum', 'max', 'min', 'p90', 'p95', 'p99', 'rawData'];\nconst functionsLabelMap = {\n count: 'count',\n avg: 'avg',\n sum: 'sum',\n max: 'max',\n min: 'min',\n p90: 'p90',\n p95: 'p95',\n p99: 'p99',\n rawData: 'raw data',\n};\n\nexport default function index({ prefixField = {}, prefixFields = [], prefixNameField = [], cate, cluster, index, valueRefVisible = true }: IProps) {\n const [search, setSearch] = useState('');\n const [fieldsOptions, setFieldsOptions] = useState([]);\n const { run } = useDebounceFn(\n () => {\n getFields({ cate, cluster: _.join(cluster, ' '), index }).then((res) => {\n setFieldsOptions(\n _.map(res.dat, (item) => {\n return {\n value: item,\n };\n }),\n );\n });\n },\n {\n wait: 500,\n },\n );\n\n useEffect(() => {\n if (cate === 'elasticsearch' && !_.isEmpty(cluster) && index) {\n run();\n }\n }, [cate, _.join(cluster), index]);\n\n return (\n \n {(fields, { add, remove }) => (\n
\n {\n const preQueryValues = _.get(prevValues, [...prefixFields, ...prefixNameField, 'query', 'values']);\n const curQueryValues = _.get(curValues, [...prefixFields, ...prefixNameField, 'query', 'values']);\n return !_.isEqual(preQueryValues, curQueryValues);\n }}\n noStyle\n >\n {({ getFieldValue }) => {\n const targetQueryValues = getFieldValue([...prefixFields, ...prefixNameField, 'query', 'values']);\n // 当提取日志原文时不可再添加 func\n if (_.get(targetQueryValues, [0, 'func']) === 'rawData') {\n return
数值提取
;\n }\n return (\n
\n 数值提取{' '}\n {\n add({\n ref: alphabet[fields.length],\n func: functions[0],\n field: undefined,\n });\n }}\n />\n
\n );\n }}\n \n\n {fields.map((field, index) => {\n return (\n
\n
\n \n \n \n {valueRefVisible && {alphabet[index]}}\n \n {\n if (val === 'rawData') {\n setFields([\n {\n name: [...prefixFields, ...prefixNameField, 'query', 'values'],\n value: [\n {\n func: 'rawData',\n },\n ],\n },\n {\n name: [...prefixFields, ...prefixNameField, 'query', 'limit'],\n value: 100,\n },\n ]);\n }\n }}\n >\n {functions.map((func) => (\n \n {functionsLabelMap[func]}\n \n ))}\n \n \n \n \n {func !== 'count' && func !== 'rawData' && (\n \n \n \n {\n if (search) {\n return item.value.includes(search);\n }\n return true;\n })}\n style={{ width: '100%' }}\n onSearch={setSearch}\n />\n \n \n \n )}\n \n \n {fields.length > 1 && (\n \n {\n remove(field.name);\n }}\n >\n \n \n \n )}\n \n );\n }}\n \n \n );\n })}\n \n )}\n \n );\n}\n","export const groupByCates = ['terms']; // 关闭 'filters' 'histgram'\nexport const groupByCatesMap = {\n // filters: '根据查询条件分组',\n terms: '根据指定 field 分组',\n};\n","import React from 'react';\nimport { Form, Select, Row, Col, Input, Space } from 'antd';\nimport { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';\nimport { groupByCates, groupByCatesMap } from './configs';\n\nexport default function Filters({ prefixField }) {\n return (\n <>\n \n \n \n \n {(fields, { add, remove }) => {\n return (\n
\n {fields.map((field, index) => {\n return (\n \n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n {\n add({\n alias: '',\n query: '',\n });\n }}\n />\n {fields.length > 1 && (\n {\n remove(field.name);\n }}\n />\n )}\n \n \n \n );\n })}\n \n );\n }}\n \n \n );\n}\n","import React, { useState } from 'react';\nimport { Row, Col, Form, Select, Button, Input, InputNumber, AutoComplete } from 'antd';\nimport { VerticalRightOutlined, VerticalLeftOutlined } from '@ant-design/icons';\nimport InputGroupWithFormItem from '@/components/InputGroupWithFormItem';\nimport _ from 'lodash';\nimport { groupByCates, groupByCatesMap } from './configs';\n\nexport default function Terms({ prefixField, fieldsOptions }) {\n const [expanded, setExpanded] = useState(false);\n const [search, setSearch] = useState('');\n\n return (\n \n \n \n \n \n \n \n \n \n \n \n {\n if (search) {\n return item.value.includes(search);\n }\n return true;\n })}\n style={{ width: '100%' }}\n onSearch={setSearch}\n />\n \n \n \n {expanded && (\n <>\n \n \n 匹配个数\n \n \n \n \n \n \n \n 文档最小值\n \n \n \n \n \n \n )}\n \n \n \n {\n setExpanded(!expanded);\n }}\n >\n 高级设置 {expanded ? : }\n \n \n \n );\n}\n","import React, { useState } from 'react';\nimport { Row, Col, Form, Select, Button, Input, InputNumber } from 'antd';\nimport { VerticalRightOutlined, VerticalLeftOutlined } from '@ant-design/icons';\nimport { groupByCates } from './configs';\n\nexport default function Terms({ prefixField }) {\n const [expanded, setExpanded] = useState(false);\n return (\n \n \n \n \n \n \n \n \n \n \n \n \n \n {expanded && (\n <>\n \n \n 步长\n \n \n \n \n \n \n \n 文档最小值\n \n \n \n \n \n \n )}\n \n \n \n {\n setExpanded(!expanded);\n }}\n >\n 高级设置 {expanded ? : }\n \n \n \n );\n}\n","import React, { useEffect, useState } from 'react';\nimport { Form, Row, Col } from 'antd';\nimport { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport { useDebounceFn } from 'ahooks';\nimport { getFields } from '@/services/warning';\nimport Filters from './Filters';\nimport Terms from './Terms';\nimport Histgram from './Histgram';\n\ninterface IProps {\n prefixField?: any;\n prefixFields?: string[]; // 前缀字段名\n prefixNameField?: (string | number)[]; // 列表字段名\n cate: string;\n cluster: string[];\n index: string;\n backgroundVisible?: boolean;\n}\n\nexport default function index({ prefixField = {}, prefixFields = [], prefixNameField = [], cate, cluster, index, backgroundVisible = true }: IProps) {\n const [fieldsOptions, setFieldsOptions] = useState([]);\n const { run } = useDebounceFn(\n () => {\n getFields({ cate, cluster: _.join(cluster, ' '), index }).then((res) => {\n setFieldsOptions(\n _.map(res.dat, (item) => {\n return {\n value: item,\n };\n }),\n );\n });\n },\n {\n wait: 500,\n },\n );\n\n useEffect(() => {\n if (cate === 'elasticsearch' && !_.isEmpty(cluster) && index) {\n run();\n }\n }, [cate, _.join(cluster), index]);\n\n return (\n \n {(fields, { add, remove }) => (\n
\n
\n Group By{' '}\n {\n add({\n cate: 'terms',\n params: [\n {\n alias: '',\n query: '',\n },\n ],\n });\n }}\n />\n
\n {fields.map((field) => {\n return (\n
\n \n {({ getFieldValue }) => {\n const cate = getFieldValue([...prefixFields, ...prefixNameField, 'group_by', field.name, 'cate']);\n return (\n \n
\n \n {cate === 'filters' && }\n {cate === 'terms' && }\n {cate === 'histgram' && }\n \n \n \n {\n remove(field.name);\n }}\n style={{ height: 32, lineHeight: '32px' }}\n >\n \n \n \n \n );\n }}\n \n \n );\n })}\n \n )}\n \n );\n}\n","import React from 'react';\nimport { Row, Col, Form, Input, InputNumber, Select } from 'antd';\n\nexport default function index({ prefixField = {}, prefixNameField = [] }: any) {\n return (\n <>\n
时间颗粒度
\n \n
\n \n \n \n \n \n \n 间隔\n \n \n \n \n \n \n \n \n \n \n \n \n );\n}\n","export const ops = ['>', '>=', '<', '<=', '=', '!='];\nexport const functions = ['cur', 'diff', 'diff_abs', 'diff_percent', 'diff_percent_abs', 'query_percent', 'nodata'];\nexport const functionsNameMap = {\n cur: '当前值',\n diff: '变化值',\n diff_abs: '变化值绝对值',\n diff_percent: '变化百分比',\n diff_percent_abs: '变化百分比绝对值',\n query_percent: '查询占比',\n nodata: '无数据',\n};\n","import React, { useState, useEffect } from 'react';\nimport { Form, Row, Col, Input, Space, Select, InputNumber } from 'antd';\nimport { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport { ops, functions, functionsNameMap } from './configs';\n\nexport default function Rule({ restField, name, queryValues, form, defaultRuleOp }) {\n const [ruleOp, setRuleOp] = useState(defaultRuleOp || 'AND');\n\n useEffect(() => {\n setRuleOp(defaultRuleOp || 'AND');\n }, [defaultRuleOp]);\n\n function renderQueryAndFunc(subName) {\n return (\n \n \n \n \n \n \n \n \n \n \n );\n }\n function renderOp(subName) {\n return (\n \n \n \n );\n }\n function renderThreshold(subName) {\n return (\n \n \n \n );\n }\n function renderRuleOp() {\n return (\n \n {\n setRuleOp(val);\n form.setFields([\n {\n name: ['query', 'rules', name, 'rule_op'],\n value: val,\n },\n ]);\n }}\n >\n AND\n OR\n \n \n );\n }\n return (\n \n {(fields, { add, remove }) => {\n return (\n
\n {fields.map(({ key, name: subName }, index) => {\n return (\n \n
\n \n {({ getFieldValue }) => {\n const func = getFieldValue(['query', 'rules', name, 'rule', subName, 'func']);\n if (func === 'cur') {\n return (\n \n {renderQueryAndFunc(subName)}\n {renderOp(subName)}\n {renderThreshold(subName)}\n {renderRuleOp()}\n \n );\n }\n if (_.includes(['diff', 'diff_abs', 'diff_percent', 'diff_percent_abs'], func)) {\n return (\n \n {renderQueryAndFunc(subName)}\n {renderOp(subName)}\n {renderThreshold(subName)}\n \n \n 相比\n \n {({ getFieldValue }) => {\n const compare_time_unit = getFieldValue(['query', 'rules', name, 'rule', subName, 'compare_time_unit']);\n const maxMap = {\n min: 59,\n hour: 23,\n day: undefined,\n };\n return (\n \n \n \n );\n }}\n \n \n \n \n \n \n \n \n {renderRuleOp()}\n \n );\n }\n if (func === 'query_percent') {\n return (\n \n {renderQueryAndFunc(subName)}\n {renderOp(subName)}\n {renderThreshold(subName)}\n \n \n 占比\n \n \n \n \n \n {renderRuleOp()}\n \n );\n }\n if (func === 'nodata') {\n return (\n \n {renderQueryAndFunc(subName)}\n {renderRuleOp()}\n \n );\n }\n }}\n \n \n \n \n {\n add({\n value: 'A',\n func: functions[0],\n op: ops[0],\n });\n }}\n />\n {fields.length > 1 && (\n {\n remove(name);\n }}\n />\n )}\n \n \n \n );\n })}\n \n );\n }}\n \n );\n}\n","import React from 'react';\nimport { Form, Row, Col, Input, Select } from 'antd';\nimport { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';\nimport Rule from './Rule';\nimport { ops, functions } from './configs';\n\nexport const severityMap = ['一级告警', '二级告警', '三级告警'];\n\nexport default function index({ form }) {\n return (\n \n {({ getFieldValue }) => {\n const queryValues = getFieldValue(['query', 'values']);\n return (\n \n {(fields, { add, remove }) => (\n
\n
\n 告警条件{' '}\n {\n add({\n rule: [\n {\n value: 'A',\n func: functions[0],\n op: ops[0],\n },\n ],\n rule_op: 'AND',\n severity: 1,\n });\n }}\n />\n
\n {fields.map(({ key, name, ...restField }) => {\n const ruleOp = getFieldValue(['query', 'rules', name, 'rule_op']);\n return (\n
\n \n
\n \n \n \n 触发\n \n \n \n \n \n {\n remove(name);\n }}\n >\n \n \n \n )}\n \n \n );\n })}\n \n )}\n \n );\n }}\n \n );\n}\n","!function(e,t){if(\"object\"==typeof exports&&\"object\"==typeof module)module.exports=t(require(\"d3\"),require(\"lodash\"));else if(\"function\"==typeof define&&define.amd)define([,],t);else{var i=\"object\"==typeof exports?t(require(\"d3\"),require(\"lodash\")):t(e.d3,e._);for(var n in i)(\"object\"==typeof exports?exports:e)[n]=i[n]}}(window,(function(e,t){return function(e){var t={};function i(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,i),o.l=!0,o.exports}return i.m=e,i.c=t,i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},i.r=function(e){\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(e,\"__esModule\",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&\"object\"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,\"default\",{enumerable:!0,value:e}),2&t&&\"string\"!=typeof e)for(var o in e)i.d(n,o,function(t){return e[t]}.bind(null,o));return n},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,\"a\",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p=\"\",i(i.s=13)}([function(t,i){t.exports=e},function(e,i){e.exports=t},function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){function i(e,t){for(var i=0;ie.length)&&(t=e.length);for(var i=0,n=new Array(t);i0&&s.length>o&&!s.warned){s.warned=!0;var c=new Error(\"Possible EventEmitter memory leak detected. \"+s.length+\" \"+String(t)+\" listeners added. Use emitter.setMaxListeners() to increase limit\");c.name=\"MaxListenersExceededWarning\",c.emitter=e,c.type=t,c.count=s.length,a=c,console&&console.warn&&console.warn(a)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function f(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},o=d.bind(n);return o.listener=i,n.wrapFn=o,o}function p(e,t,i){var n=e._events;if(void 0===n)return[];var o=n[t];return void 0===o?[]:\"function\"==typeof o?i?[o.listener||o]:[o]:i?function(e){for(var t=new Array(e.length),i=0;i0&&(s=t[0]),s instanceof Error)throw s;var a=new Error(\"Unhandled error.\"+(s?\" (\"+s.message+\")\":\"\"));throw a.context=s,a}var c=o[e];if(void 0===c)return!1;if(\"function\"==typeof c)r(c,this,t);else{var l=c.length,h=y(c,l);for(i=0;i=0;r--)if(i[r]===t||i[r].listener===t){s=i[r].listener,o=r;break}if(o<0)return this;0===o?i.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},a.prototype.listeners=function(e){return p(this,e,!0)},a.prototype.rawListeners=function(e){return p(this,e,!1)},a.listenerCount=function(e,t){return\"function\"==typeof e.listenerCount?e.listenerCount(t):v.call(e,t)},a.prototype.listenerCount=v,a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},function(e,t,i){var n=i(6);e.exports=function(e){if(Array.isArray(e))return n(e)},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){e.exports=function(e){if(\"undefined\"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e[\"@@iterator\"])return Array.from(e)},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t,i){var n=i(6);e.exports=function(e,t){if(e){if(\"string\"==typeof e)return n(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return\"Object\"===i&&e.constructor&&(i=e.constructor.name),\"Map\"===i||\"Set\"===i?Array.from(e):\"Arguments\"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){e.exports=function(){throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\")},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t,i){},function(e,t,i){\"use strict\";i.r(t),i.d(t,\"default\",(function(){return K}));var n=i(5),o=i.n(n),r=i(4),s=i.n(r),a=i(2),c=i.n(a),l=i(3),h=i.n(l),u=i(0),d=i(1);let f=null;let p=null;function v(e,t={}){let i=document.createElement(e);return Object.keys(t).forEach(e=>{i[e]=t[e]}),i}function y(e,t,i){return(window.getComputedStyle(e,i||null)||{display:\"none\"})[t]}function m(e){if(!document.documentElement.contains(e))return{detached:!0,rendered:!1};let t=e;for(;t!==document;){if(\"none\"===y(t,\"display\"))return{detached:!1,rendered:!1};t=t.parentNode}return{detached:!1,rendered:!0}}let g=0,b=null;function x(e,t){if(e.__resize_mutation_handler__||(e.__resize_mutation_handler__=_.bind(e)),!e.__resize_listeners__)if(e.__resize_listeners__=[],window.ResizeObserver){let{offsetWidth:t,offsetHeight:i}=e,n=new ResizeObserver(()=>{(e.__resize_observer_triggered__||(e.__resize_observer_triggered__=!0,e.offsetWidth!==t||e.offsetHeight!==i))&&w(e)}),{detached:o,rendered:r}=m(e);e.__resize_observer_triggered__=!1===o&&!1===r,e.__resize_observer__=n,n.observe(e)}else if(e.attachEvent&&e.addEventListener)e.__resize_legacy_resize_handler__=function(){w(e)},e.attachEvent(\"onresize\",e.__resize_legacy_resize_handler__),document.addEventListener(\"DOMSubtreeModified\",e.__resize_mutation_handler__);else if(g||(b=function(e){var t=document.createElement(\"style\");return t.type=\"text/css\",t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e)),(document.querySelector(\"head\")||document.body).appendChild(t),t}('.resize-triggers{visibility:hidden;opacity:0;pointer-events:none}.resize-contract-trigger,.resize-contract-trigger:before,.resize-expand-trigger,.resize-triggers{content:\"\";position:absolute;top:0;left:0;height:100%;width:100%;overflow:hidden}.resize-contract-trigger,.resize-expand-trigger{background:#eee;overflow:auto}.resize-contract-trigger:before{width:200%;height:200%}')),function(e){let t=y(e,\"position\");t&&\"static\"!==t||(e.style.position=\"relative\");e.__resize_old_position__=t,e.__resize_last__={};let i=v(\"div\",{className:\"resize-triggers\"}),n=v(\"div\",{className:\"resize-expand-trigger\"}),o=v(\"div\"),r=v(\"div\",{className:\"resize-contract-trigger\"});n.appendChild(o),i.appendChild(n),i.appendChild(r),e.appendChild(i),e.__resize_triggers__={triggers:i,expand:n,expandChild:o,contract:r},C(e),e.addEventListener(\"scroll\",k,!0),e.__resize_last__={width:e.offsetWidth,height:e.offsetHeight}}(e),e.__resize_rendered__=m(e).rendered,window.MutationObserver){let t=new MutationObserver(e.__resize_mutation_handler__);t.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0}),e.__resize_mutation_observer__=t}e.__resize_listeners__.push(t),g++}function _(){let{rendered:e,detached:t}=m(this);e!==this.__resize_rendered__&&(!t&&this.__resize_triggers__&&(C(this),this.addEventListener(\"scroll\",k,!0)),this.__resize_rendered__=e,w(this))}function k(){var e,t;C(this),this.__resize_raf__&&(e=this.__resize_raf__,p||(p=(window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(e){clearTimeout(e)}).bind(window)),p(e)),this.__resize_raf__=(t=()=>{let e=function(e){let{width:t,height:i}=e.__resize_last__,{offsetWidth:n,offsetHeight:o}=e;return n!==t||o!==i?{width:n,height:o}:null}(this);e&&(this.__resize_last__=e,w(this))},f||(f=(window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(e){return setTimeout(e,16)}).bind(window)),f(t))}function w(e){e&&e.__resize_listeners__&&e.__resize_listeners__.forEach(t=>{t.call(e,e)})}function C(e){let{expand:t,expandChild:i,contract:n}=e.__resize_triggers__,{scrollWidth:o,scrollHeight:r}=n,{offsetWidth:s,offsetHeight:a,scrollWidth:c,scrollHeight:l}=t;n.scrollLeft=o,n.scrollTop=r,i.style.width=s+1+\"px\",i.style.height=a+1+\"px\",t.scrollLeft=c,t.scrollTop=l}var O=i(7),S=i.n(O);function L(e,t){var i=e.length;return t2&&void 0!==arguments[2]?arguments[2]:0,n=e.getBoundingClientRect(),o=t.touches[i].clientX,r=t.touches[i].clientY,s=o-n.left,a=r-n.top;return{offsetX:s,offsetY:a,clientX:o,clientY:r}}function j(e){var t=String(e);if(e>=1e3){t=u.format(\".5s\")(e);var i=/[kMGTPEZY]$/;if(i.test(t)){var n=t[t.length-1];t=t.replace(i,\"\"),t=parseFloat(t)+n}}return t}function A(e,t){var i=e;return null!==e&&\"function\"==typeof t&&(i=t(e)),i}var T=function(){function e(t,i,n){c()(this,e),this.options=void 0,this.ctx=void 0,this.yAxis=void 0,this.options=t,this.ctx=i,this.yAxis=n}return h()(e,[{key:\"init\",value:function(){var e=this.options,t=e.chart.width,i=e.timestamp,n=e.xmin,o=e.xmax,r=u.scaleTime().range([this.yAxis.tickMaxWidth,t]);return r.domain([E(n,i)-(n===o?1e3:0),E(o,i)+(n===o?1e3:0)]),r}},{key:\"draw\",value:function(e){var t=this.ctx,i=this.options,n=i.chart,o=i.xAxis,r=i.time,s=e.ticks(Math.floor(n.width/90));o.ticks&&(s=o.ticks);var a=n.height-o.tickpadding-o.labels.fontSize;t.beginPath(),s.forEach((function(i){var n=e(i);n&&(t.moveTo(n,a),t.lineTo(n,a-o.tickLength))})),t.lineWidth=1,t.strokeStyle=o.tickColor,t.stroke(),t.closePath(),t.beginPath(),t.moveTo(0,a-o.tickLength),t.lineTo(n.width,a-o.tickLength),t.lineWidth=1,t.strokeStyle=o.lineColor,t.stroke(),t.closePath(),t.textAlign=\"center\",t.textBaseline=\"bottom\",t.fillStyle=o.labels.color,t.font=\"\".concat(o.labels.fontSize,\"px Palantino\"),s.forEach((function(i,a){var c=\"%H:%M\";0!==i.getSeconds()&&(c=\"%H:%M:%S\"),0===i.getHours()&&0===i.getMinutes()&&0===i.getSeconds()&&(c=\"%m-%d\"),o.labels.timeFormat&&(c=o.labels.timeFormat);var l=i;if(r&&r.timezoneOffset){var h=i.getTimezoneOffset(),d=i.getTime()+60*h*1e3+60*r.timezoneOffset*1e3;l=new Date(d)}if(o.ticks&&o.ticks.length>1){var f=e(i);0===a?f+=c.length*o.labels.fontSize/4+1:a===s.length-1&&(f-=c.length*o.labels.fontSize/4-1),t.fillText(u.timeFormat(c)(l),f,n.height)}else e(i)&&t.fillText(u.timeFormat(c)(l),e(i),n.height)}))}},{key:\"drawPlotLines\",value:function(e){var t=this.ctx,i=this.options,n=i.chart,o=i.xAxis,r=i.xAxis.plotLines,s=n.height-o.tickpadding-o.labels.fontSize;Array.isArray(r)&&r.forEach((function(n){var r=e(\"X\"===i.timestamp?1e3*n.value:n.value);t.setLineDash([5,3]),t.beginPath(),t.moveTo(r,0),t.lineTo(r,s-o.tickLength),t.strokeStyle=n.color,t.stroke(),t.setLineDash([])}))}}]),e}(),M=function(){function e(t,i){c()(this,e),this.options=void 0,this.ctx=void 0,this.tickLength=void 0,this.ticks=void 0,this.tickMaxWidth=void 0,this.options=t;var n=t.yAxis;i.font=\"\".concat(n.labels.fontSize,\"px Palantino\"),this.ctx=i,this.tickLength=Math.floor(t.chart.height/50),this.ticks=[],this.tickMaxWidth=0}return h()(e,[{key:\"init\",value:function(){var e=this.options,t=e.chart,i=e.xAxis,n=e.yAxis,o=u.scaleLinear();n.scale&&\"log\"===n.scale.type&&(o=u.scaleLog().base(n.scale.log||10));var r=o.range([t.height-(i.labels.fontSize+i.tickpadding+i.tickLength),10]);return this.setDomain(r,this.options),r}},{key:\"getRealData\",value:function(e){var t=this.options,i=t.yAxis.plotLines,n=t.ykey,o=t.fillNull;return Array.isArray(e)?(Array.isArray(i)&&i.forEach((function(t){\"number\"==typeof t.value&&e.push(s()({},n,t.value))})),\"number\"==typeof o&&e.push(s()({},n,o)),e):[]}},{key:\"getPlotLinesMaxAbs\",value:function(){var e,t=this.options.yAxis.plotLines;return Array.isArray(t)&&t.forEach((function(t){(!e||Math.abs(e)n){var c=i;i=n,n=c}if(o.plotLinesFixed){var l=this.getPlotLinesMaxAbs();l&&(ln&&(n=l))}e.domain([i,n]),e.nice(r);var h=e.ticks(r),u=function(e,t,i){var n=e.map((function(e){var n;return n=\"function\"==typeof i?i(e):j(e),t.measureText(n).width}));return Object(d.max)(n)}(h,this.ctx,o.tickValueFormatter)+5;this.ticks=h,this.tickMaxWidth=u}},{key:\"draw\",value:function(e){var t=this,i=this.ctx,n=this.options,o=n.yAxis,r=n.chart;i.beginPath(),i.fillStyle=o.backgroundColor||\"#fff\",i.fillRect(0,0,this.tickMaxWidth,r.height-12),i.stroke(),i.closePath(),i.textAlign=\"right\",i.textBaseline=\"middle\",i.strokeStyle=o.labels.color,i.lineWidth=1,i.fillStyle=o.labels.color,this.ticks.forEach((function(n){var r;r=\"function\"==typeof o.tickValueFormatter?o.tickValueFormatter(n):j(n);var s=e(n);i.fillText(r,t.tickMaxWidth-5,s)}))}},{key:\"drawGridLine\",value:function(e){var t=this.ctx,i=this.options,n=i.chart,o=i.yAxis;t.beginPath(),this.ticks.forEach((function(i){var o=e(i);t.moveTo(0,o),t.lineTo(n.width,o)})),t.lineWidth=1,t.strokeStyle=o.gridLineColor,t.stroke(),t.closePath()}},{key:\"drawPlotLines\",value:function(e){var t=this.ctx,i=this.options,n=i.chart,o=i.yAxis,r=i.yAxis.plotLines;Array.isArray(r)&&r.forEach((function(i){var r=i.labelEnable,s=void 0===r||r,a=e(i.value);t.setLineDash([5,3]),t.beginPath(),t.moveTo(0,a),t.lineTo(n.width,a),t.strokeStyle=i.color,t.stroke(),t.setLineDash([]),s&&(t.textAlign=\"right\",t.textBaseline=\"top\",t.shadowColor=i.shadowColor||\"#fff\",t.shadowBlur=1,t.lineWidth=1,t.fillStyle=i.color,t.font=\"\".concat(o.labels.fontSize,\"px Palantino\"),t.strokeText(String(i.value),n.width-10,a),t.fillText(String(i.value),n.width-10,a))}))}}]),e}();function P(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function N(e){for(var t=1;tn?1:i>=n?0:NaN;var i,n},{left:function(e,i,n,o){for(null==n&&(n=0),null==o&&(o=e.length);n>>1;t(e[r],i)<0?n=r+1:o=r}return n},right:function(e,i,n,o){for(null==n&&(n=0),null==o&&(o=e.length);n>>1;t(e[r],i)>0?o=r:n=r+1}return n}}).left,u=new Date(n).getTime(),f=[];return\"[object Array]\"!==Object.prototype.toString.call(i)?[]:(i.forEach((function(e,t){if(!function(e,t){return Object(d.some)(e.data,(function(e){return t&&t in e}))}(e,s)&&!1!==e.visible){var i=e.name,p=e.color,v=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&\"[object Function]\"===Object.prototype.toString.call(t)&&t(n)&&(i[n]=e[n]);return i}(e,(function(e){return\"data\"!==e})),y=e.data,m=void 0===y?[]:y;if(\"[object Array]\"===Object.prototype.toString.call(m)&&0!==(m=m.filter((function(e){return\"number\"==typeof e[r]||\"number\"==typeof l}))).length){var g,b=h(m,n),x=m[b-1],_=m[b];if(x&&_){var k=I(x[o],c),w=I(_[o],c),C=x[r],O=_[r];null===C&&void 0!==l&&(C=l),null===O&&void 0!==l&&(O=l),g=u-k1){var k=Number.POSITIVE_INFINITY;for(var w in _)if(Object.prototype.hasOwnProperty.call(_,w)){var C=(b=e.offsetX,x=Number(w),Math.sqrt(Math.pow(x-b,2)));Cy&&(e=e.slice(0,y),m=!0),p.className=\"ts-graph-tooltip-content\",f.appendChild(p),\"[object Function]\"===Object.prototype.toString.call(a.formatter))p.innerHTML=a.formatter(o()(e),o()(v));else{var g=e[0],b=document.createDocumentFragment(),x=document.createElement(\"ul\"),_=document.createElement(\"li\"),k=new Date(g.timestamp);if(c&&c.timezoneOffset){var w=k.getTimezoneOffset(),C=k.getTime()+60*w*1e3+60*c.timezoneOffset*1e3;k=new Date(C)}var O=document.createTextNode(u.timeFormat(a.timeFormat)(k));if(_.appendChild(O),_.style.color=\"#666\",x.style.maxWidth=\"\".concat(window.innerWidth/1.5,\"px\"),x.appendChild(_),b.appendChild(x),e.forEach((function(e){var t=e.color,i=e.name,n=e.origin,o=e.filledNull;if(!(l.indexOf(i)>-1)){var r=document.createElement(\"li\");if(t){var s=document.createElement(\"span\"),c=document.createTextNode(\"● \");s.style.color=t,s.appendChild(c),r.appendChild(s)}if(i){var h=document.createTextNode(\"\".concat(i,\": \"));r.appendChild(h)}var f=n;if(Object(d.isNumber)(f)){var p,v=document.createElement(\"strong\");if(\"function\"==typeof a.pointValueformatter)p=a.pointValueformatter(f);else if(\"origin\"===a.precision)p=f;else if(\"short\"===a.precision){p=function(e){e:for(var t,i=e.length,n=1,o=-1;n0){if(!+e[n])break e;o=0}}return o>0?e.slice(0,o)+e.slice(t+1):e}(u.format(\".5s\")(f))}else p=a.precision>0?u.format(\",.\"+a.precision+\"f\")(f):u.format(\",.3f\")(f);p+=o?\"(空值填补,仅限看图使用)\":\"\";var y=document.createTextNode(p);v.appendChild(y),r.appendChild(v)}x.appendChild(r)}})),m){var S=document.createElement(\"li\"),L=document.createTextNode(\"......\");S.appendChild(L),x.appendChild(S)}p.appendChild(b)}var E=p.offsetWidth,z=p.offsetHeight,j=this.container.getBoundingClientRect(),A=t.layerX+j.left,T=t.layerY+j.top;f.style.left=\"\".concat(A-E-20,\"px\"),f.style.top=\"\".concat(T+20,\"px\"),A-E-20<0&&(f.style.left=\"\".concat(A+20,\"px\")),T+20+z>h&&(f.style.top=T-z-20<0?\"0px\":\"\".concat(T-z-20,\"px\")),f.style.zIndex=\"9999\",f.style.visibility=\"visible\"}},{key:\"drawSymbol\",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=this.ctx,i=this.options;e.forEach((function(e){var n=e.x,o=e.y,r=e.color,s=e.name;i.notDisplayedSeries.indexOf(s)>-1||(t.beginPath(),t.arc(n,o,5,0,360,!1),t.lineWidth=1,t.fillStyle=r,t.fill(),t.beginPath(),t.arc(n,o,3,0,360,!1),t.lineWidth=1,t.fillStyle=\"white\",t.fill())}))}},{key:\"drawCrosshair\",value:function(e){var t=this.ctx,i=this.options,n=i.chart,o=i.xAxis,r=n.height-o.tickpadding-o.labels.fontSize-o.tickLength;t.beginPath(),t.moveTo(e,0),t.lineTo(e,r),t.lineWidth=1,t.strokeStyle=o.lineColor,t.stroke()}},{key:\"destroy\",value:function(){var e=this.options.chart.id,t=document.getElementById(\"\".concat(e,\"-tooltip\"));t&&t.parentNode&&t.parentNode.removeChild(t)}}]),e}(),X=function(){function e(t,i){c()(this,e),this.options=void 0,this.ctx=void 0,this.options=t,this.ctx=i}return h()(e,[{key:\"draw\",value:function(e,t){var i=this.options,n=i.series,o=i.chart,r=o.colors,s=o.height,a=i.xAxis,c=i.xkey,l=i.ykey,h=i.ykey2,f=i.timestamp,p=i.fillNull,v=i.notDisplayedSeries,y=i.curve,m=this.options.line.width,g=this.options.area,b=g.opacity,x=g.gradientMode,_=g.gradientOpacityStopColor,k=this.ctx,w=function(t){var i=\"X\"===f?1e3*t[c]:t[c];return e(new Date(i))},C=function(e,i){var n=e[i];return\"number\"!=typeof n||isNaN(n)?\"number\"==typeof p?t(p):void 0:t(n)},O=function(e){return\"number\"==typeof e[l]||\"number\"==typeof p};Object(d.sortBy)(n,\"zIndex\").forEach((function(e,t){if(!1!==e.visible&&!(v.indexOf(e.name)>-1)){var i,n=e.color||L(r,t);if(e.color=n,\"opacity\"===x&&((i=k.createLinearGradient(0,0,0,s)).addColorStop(0,n),i.addColorStop(1,_)),b>0||e.opacity){k.beginPath();var o=u.area().x(w).y0((function(e){return h&&h in e?C(e,l):s-a.tickpadding-a.labels.fontSize-5})).y1((function(e){return C(e,h&&h in e?h:l)})).defined(O).context(k);y.enabled&&\"smooth\"===y.mode&&o.curve(u.curveMonotoneX),o(e.data||[]),k.fillStyle=\"opacity\"===x&&i?i:n,k.globalAlpha=b||(e.opacity?e.opacity:.5),k.fill(),k.closePath()}if(m>0&&void 0===e.opacity){k.beginPath();var c=u.line().x(w).y((function(e){return C(e,l)})).defined(O).context(k);y.enabled&&\"smooth\"===y.mode&&c.curve(u.curveMonotoneX),k.lineTo(0,0),c(e.data||[]),k.lineJoin=\"round\",k.lineWidth=m,k.strokeStyle=n,k.lineCap=\"round\",k.globalAlpha=1,k.setLineDash(e.lineDash||[]),k.stroke(),k.closePath()}}}))}}]),e}(),F=function(){function e(t,i){c()(this,e),this.options=void 0,this.ctx=void 0,this.options=t,this.ctx=i}return h()(e,[{key:\"draw\",value:function(e,t,i){var n=this.options,o=n.series,r=n.chart,s=r.colors,a=r.height,c=r.width,l=n.xAxis,h=n.timestamp,f=n.xkey,p=n.ykey,v=n.notDisplayedSeries,y=this.ctx,m=this.options.area.opacity;Object(d.sortBy)(o,\"zIndex\").forEach((function(n,o){if(!1!==n.visible&&!(v.indexOf(n.name)>-1)){var r=n.color||L(s,o);n.color=r,y.fillStyle=r,y.globalAlpha=m;var d=u.scaleBand().domain(n.data.map((function(e){return\"X\"===h?1e3*e[f]:e[f]}))).range([0,c]).padding(.3),g=(null==i?void 0:i.k)||1;n.data.forEach((function(i){var n=\"X\"===h?1e3*i[f]:i[f];y.fillRect(e(n)-d.bandwidth()*g/2,t(i[p]),d.bandwidth()*g,a-t(i[p])-l.tickpadding-l.labels.fontSize-5)})),y.globalAlpha=1}}))}}]),e}(),H=function(){function e(t,i,n,o){c()(this,e),this.options=void 0,this.reset=void 0,this.options=t,this.init(n,o),this.reset=i}return h()(e,[{key:\"init\",value:function(e,t){var i=this.options.chart,n=i.id,o=i.containerHeight,r=document.getElementById(\"\".concat(n,\"-zoom\"));r&&r.remove(),r=document.createElement(\"div\");var s=document.createElement(\"div\"),a=document.createElement(\"a\"),c=document.createTextNode(\"Reset zoom\");r.id=\"\".concat(n,\"-zoom\"),r.className=\"ts-graph-zoom\",s.id=\"\".concat(n,\"-zoom-marker\"),s.className=\"ts-graph-zoom-marker\",s.style.height=\"\".concat(o,\"px\"),a.id=\"\".concat(n,\"-zoom-resetBtn\"),a.className=\"ts-graph-zoom-resetBtn\",a.appendChild(c),r.appendChild(s),r.appendChild(a),e.insertBefore(r,t),this.onReset()}},{key:\"onReset\",value:function(){var e=this,t=this.options.chart.id,i=document.getElementById(\"\".concat(t,\"-zoom-resetBtn\"));null==i||i.addEventListener(\"click\",(function(t){t.stopPropagation(),e.reset(),e.clearResetBtn()}))}},{key:\"onZoom\",value:function(e,t,i){var n=this.options.chart.width,o=t.layerX-e.layerX;if(o){var r=n/Math.abs(o),s=t.layerX>e.layerX?e.layerX:t.layerX,a=u.zoomIdentity.translate(-s*r,0).scale(r);this.drawResetBtn(),i(a)}}},{key:\"clearMarker\",value:function(){var e=this.options.chart.id,t=document.getElementById(\"\".concat(e,\"-zoom-marker\"));t.style.display=\"none\",t.style.width=\"0px\",t.style.left=\"unset\",t.style.right=\"unset\"}},{key:\"drawMarker\",value:function(e,t){var i=this.options.chart.marginLeft,n=e.layerX,o=t.layerX,r=this.options.chart,s=r.id,a=r.containerWidth,c=document.getElementById(\"\".concat(s,\"-zoom-marker\"));c.style.display=\"block\",c.style.top=\"0px\",n=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\")}var r,s=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return s=e.done,e},e:function(e){a=!0,r=e},f:function(){try{s||null==i.return||i.return()}finally{if(a)throw r}}}}function V(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i=0&&n<=s}));return U(U({},e),{},{data:t})}return e}))},this.handleResize=function(){var e=i.options.chart,t=e.renderTo.offsetWidth,n=e.renderTo.offsetHeight;i.options.chart.width=t-e.marginLeft-e.marginRight,i.options.chart.height=n-e.marginTop-e.marginBottom,i.options.chart.containerWidth=t,i.options.chart.containerHeight=n,i.container.style.width=\"\".concat(t,\"px\"),i.container.style.height=\"\".concat(n,\"px\"),i.retinaScaled(i.backCanvas,\"back\"),i.retinaScaled(i.frontCanvas,\"front\"),i.retinaScaled(i.eventCanvas,\"event\"),i.initScales(),i.initZoom(),i.draw(!1)},this.handleZoom=function(e,t){if(i.options.onZoomWithoutDefult){var n;t&&(n=Object(d.sortBy)(t,\"layerX\").map((function(e){return i.xScales.invert(e.layerX)}))),i.options.onZoomWithoutDefult(n)}else{var o=i.options,r=o.ykey,s=o.yAxis,a=o.ykeyFormatter,c=i.options.series;if(e?(i.transform=e,i.xScales=e.rescaleX(i.xScales),c=i.getZoomedSeries()):(i.transform=void 0,i.xScales=i.xAxis.init()),Array.isArray(c)){var l,h=s.min||-1/0,u=s.max||1/0,f=Y(c);try{for(f.s();!(l=f.n()).done;){var p=l.value,v=Array.isArray(p.data)?p.data:[],y=void 0;for(y=0;ym&&(u=m))}}}catch(e){f.e(e)}finally{f.f()}i.yAxis.setDomain(i.yScales,{ymin:h,ymax:u})}i.options.onZoom(i.getZoomedSeries)}i.draw(!1)},this.handleLegendItemClick=function(e){var t=i.options.notDisplayedSeries;-1===t.indexOf(e)?t.push(e):i.options.notDisplayedSeries=t.filter((function(t){return t!==e})),i.draw(!1)};var n={ratio:window.devicePixelRatio||1,xkey:0,ykey:1,ykey2:2,oykey:\"__originValue\",timestamp:\"x\",chart:{id:Object(d.uniqueId)(\"ts-graph-\"),colors:[\"#3399CC\",\"#CC9933\",\"#9966CC\",\"#66CC66\",\"#CC3333\",\"#99CCCC\",\"#CCCC66\",\"#CC99CC\",\"#99CC99\",\"#CC6666\",\"#336699\",\"#996633\",\"#993399\",\"#339966\",\"#993333\"],width:t.chart.renderTo.offsetWidth,height:t.chart.renderTo.offsetHeight||350,marginTop:10,marginRight:10,marginBottom:10,marginLeft:10},xAxis:{visible:!0,lineColor:\"#ccc\",lineWidth:1,tickLength:5,tickpadding:5,tickColor:\"#ccc\",labels:{color:\"#999\",fontSize:11}},yAxis:{scale:{type:\"linear\",log:10},visible:!0,lineColor:\"#ccc\",lineWidth:1,tickLength:5,tickpadding:5,tickColor:\"#ccc\",gridLineColor:\"#efefef\",labels:{color:\"#999\",fontSize:11}},type:\"line\",line:{enable:!0,width:2},area:{opacity:0,gradientMode:\"none\",gradientOpacityStopColor:\"rgba(255, 255, 255, 0)\"},bars:{},stack:{enabled:!1},curve:{enabled:!1},tooltip:{shared:!0,cascade:!1,cascadeScope:void 0,timeFormat:\"%Y-%m-%d %H:%M:%S\"},series:[],legend:{align:\"center\",verticalAlign:\"top\",enabled:!1},fillNull:void 0,onClick:void 0,onRightClick:function(){},onZoom:function(){},onShapeMouseOver:function(){},onShapeClick:function(){}},o=Object(d.merge)({},n,t);void 0===t.chart.marginTop&&o.legend.enabled&&(o.chart.marginTop=20),this.handleResize=Object(d.debounce)(this.handleResize,300),this.init(o)}return h()(e,[{key:\"init\",value:function(e){var t=e.chart;this.options=e,this.options.notDisplayedSeries=[],this.options.chart.containerWidth=t.width,this.options.chart.containerHeight=t.height,this.options.chart.width=t.width-t.marginLeft-t.marginRight,this.options.chart.height=t.height-t.marginTop-t.marginBottom,this.createContainer(),this.createCanvas(),this.initSeries(),this.initScales(),this.initEvent(),\"line\"===this.options.type&&this.initLine(),\"bar\"===this.options.type&&this.initBar(),this.initLegend(),this.initTooltip(),this.initZoom(),this.initShapes(),this.draw()}},{key:\"clearRect\",value:function(e){var t=this.options.chart,i=t.containerWidth,n=t.containerHeight;e.clearRect(0,0,i,n)}},{key:\"draw\",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.transform;this.clearRect(this.backContext),this.options.xAxis.visible&&this.yAxis.drawGridLine(this.yScales),this.options.xAxis.visible&&this.xAxis.draw(this.xScales),\"line\"===this.options.type&&this.line.draw(this.xScales,this.yScales),\"bar\"===this.options.type&&this.bar.draw(this.xScales,this.yScales,t),this.xAxis.drawPlotLines(this.xScales),this.yAxis.drawPlotLines(this.yScales),this.options.yAxis.visible&&this.yAxis.draw(this.yScales),e&&this.legend.draw(),this.shapes.draw(this.xScales,this.yScales)}},{key:\"update\",value:function(e){var t=Object(d.assign)({},this.options,e);e.series&&(t.series=e.series),this.options=t,this.offEvents(),this.initSeries(),this.initScales(),this.initEvent(),\"line\"===this.options.type&&this.initLine(),\"bar\"===this.options.type&&this.initBar(),this.initTooltip(),this.initShapes(),this.legend.updateOptions(t),this.draw()}},{key:\"getSeries\",value:function(){return o()(this.options.series)}},{key:\"initEvent\",value:function(){var e,t=this.options.tooltip,i=t.cascade,n=t.cascadeScope,o=n?\"plotmove:\".concat(n):\"plotmove\",r=n?\"plotleave:\".concat(n):\"plotleave\",s=!1,a={},c={},l=!1,h=this,f=Object(d.debounce)((function(e){l&&(h.tooltip.draw(e,h),s&&h.zoom.drawMarker(a,e))}),5),p=Object(d.throttle)((function(){h.tooltip.clear()}),5),v=function(){if(\"function\"==typeof h.options.onClick){var e=h.options,t=e.xkey,i=e.ykey,n=e.ykey2,o=e.oykey,r=e.timestamp,s=e.series,a=e.fillNull,c=u.event.offsetX||u.event.layerX,l=u.event.offsetY||u.event.layerY,d=h.xScales.invert(c),f=h.yScales.invert(l),p=D({x:d,xkey:t,ykey:i,ykey2:n,oykey:o,timestamp:r,series:s,fillNull:a});h.options.onClick(u.event,d,f,p)}};u.select(this.eventCanvas).on(\"mousemove\",(function(){l=!0,f(u.event),i&&$.emit(o,u.event)})).on(\"mouseleave\",(function(){e=u.event,l=!1,p(),i&&$.emit(r)})).on(\"mousedown\",(function(){1===u.event.which&&(s=!0,a=u.event)})).on(\"mouseup\",(function(){u.event.stopPropagation();var e=u.event;a&&a.layerX!==e.layerX?(h.zoom.clearMarker(),h.zoom.onZoom(a,e,(function(t){h.handleZoom(t,[a,e])}))):v(),s=!1,a={}})).on(\"contextmenu\",(function(){h.options.onRightClick(u.event,h.xScales.invert(u.event.offsetX),h.yScales.invert(u.event.offsetY)),u.event.preventDefault()})).on(\"touchstart\",(function(){u.event.touches.length>1&&(s=!0)})).on(\"touchmove\",(function(){var e=z(h.eventCanvas,u.event);1===u.event.touches.length&&h.tooltip.draw(e,h),s&&(a=e,c=z(h.eventCanvas,u.event,1),h.zoom.drawMarker(a,c))})).on(\"touchend\",(function(){l=!1,p(),a&&a.layerX!==c.layerX?(h.zoom.clearMarker(),h.zoom.onZoom(a,c,(function(e){h.handleZoom(e,[a,c])}))):v(),s=!1,a={},c={}})),i&&($.on(o,this.showTooltip),$.on(r,this.hideTooltip)),window.addEventListener(\"mouseup\",(function(){if(!Object(d.isEmpty)(a)){var t=e;s=!1,h.zoom.clearMarker(),h.zoom.onZoom(a,t,(function(e){h.handleZoom(e,[a,t])})),a={}}})),x(this.options.chart.renderTo,this.handleResize)}},{key:\"retinaScaled\",value:function(e,t){var i=this.options,n=i.chart,o=i.ratio,r=e.getContext(\"2d\"),s=\"front\"===t?n.containerWidth:n.width,a=\"front\"===t?n.containerHeight:n.height,c=\"front\"===t?\"0px\":\"\".concat(n.marginLeft,\"px\"),l=\"front\"===t?\"0px\":\"\".concat(n.marginTop,\"px\");e.width=s*o,e.height=a*o,e.style.width=\"\".concat(s,\"px\"),e.style.height=\"\".concat(a,\"px\"),e.style.position=\"absolute\",e.style.left=c,e.style.top=l,\"front\"===t&&r.translate(n.marginLeft*o,n.marginTop*o),r.scale(o,o)}},{key:\"createContainer\",value:function(){var e=this.options.chart,t=document.createElement(\"div\");t.style.position=\"relative\",t.style.width=\"\".concat(e.containerWidth,\"px\"),t.style.height=\"\".concat(e.containerHeight,\"px\"),t.style.overflow=\"hidden\",t.className=\"d3-graph-container\",e.renderTo.appendChild(t),this.container=t}},{key:\"createCanvas\",value:function(){var e=this.options.chart.id;function t(t){var i=document.createElement(\"canvas\"),n=i.getContext(\"2d\");i.setAttribute(\"id\",\"\".concat(e,\"-\").concat(t,\"Canvas\")),this.container.appendChild(i),this[\"\".concat(t,\"Canvas\")]=i,this[\"\".concat(t,\"Context\")]=n,this.retinaScaled(i,t)}t.call(this,\"back\"),t.call(this,\"front\"),t.call(this,\"event\")}},{key:\"initSeries\",value:function(){var e=this.options,t=e.fillNull,i=e.series,n=e.xkey,o=e.ykey,r=e.ykey2,a=e.ykeyFormatter,c=e.oykey,l=e.xAxis,h=e.yAxis,u=e.stack,f=e.notDisplayedSeries,p=l.min||-1/0,v=l.max||1/0,y=h.min,m=h.max;if(Array.isArray(i)){var g=[];i.forEach((function(e,l){if(!(f.indexOf(e.name)>-1)){var h,b=Array.isArray(e.data)?e.data:[],x=[],_=!1,k=function(){var e,f=b[h][c]?b[h][c]:A(b[h][o],a),g=(e={},s()(e,n,b[h][n]),s()(e,o,f),s()(e,c,f),e);if(r&&r in b[h]&&(g[r]=A(b[h][r],a)),u.enabled){void 0===g[c]&&(g[c]=A(g[o],a));var k=l;if(k>0)for(;k>0;){var w=Array.isArray(i[k-1].data)?i[k-1].data:[],C=Object(d.find)(w,(function(e){return e[n]===g[n]}));if(C){var O=isNaN(g[c])?0:g[c],S=A(C[o],a);S=isNaN(S)?0:S,g[o]=S+O;break}1===k&&(g[o]=g[c]),k--}else g[o]=g[c]}b[h]=g;var L=g[n],E=g[o],z=void 0;r&&r in b[h]&&(z=g[r]),void 0===t?!isNaN(E)&&(0===h||h===b.length-1||h>0&&hv||v===1/0)&&(v=L),\"number\"!=typeof E||isNaN(E)?\"number\"==typeof t&&(tm&&(m=t)):((\"number\"!=typeof y||Em)&&(m=E),\"number\"==typeof z&&z>m&&(m=z))};for(h=0;h (\n \n \n \n);\n\nexport const AddPanelIcon = (props) => ;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nexport const utilValMap = {\n bitsSI: {\n type: 'si',\n base: 'bits',\n },\n bytesSI: {\n type: 'si',\n base: 'bytes',\n },\n bitsIEC: {\n type: 'iec',\n base: 'bits',\n },\n bytesIEC: {\n type: 'iec',\n base: 'bytes',\n },\n};","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n// wiki: https://en.wikipedia.org/wiki/Byte#Multiple-byte_units\nimport _ from 'lodash';\n\ninterface IOptions {\n type: 'si' | 'iec';\n base?: 'bits' | 'bytes';\n decimals: number;\n}\n\nconst defaultOptions: IOptions = {\n type: 'iec',\n base: 'bytes',\n decimals: 2,\n};\n\nconst valueMap = [\n { exp: 0, si: '', iec: '', iecExp: 1 },\n { exp: 3, si: 'k', iec: 'Ki', iecExp: 10 },\n { exp: 6, si: 'M', iec: 'Mi', iecExp: 20 },\n { exp: 9, si: 'G', iec: 'Gi', iecExp: 30 },\n { exp: 12, si: 'T', iec: 'Ti', iecExp: 40 },\n { exp: 15, si: 'P', iec: 'Pi', iecExp: 50 },\n { exp: 18, si: 'E', iec: 'Ei', iecExp: 60 },\n { exp: 21, si: 'Z', iec: 'Zi', iecExp: 70 },\n { exp: 24, si: 'Y', iec: 'Yi', iecExp: 80 },\n];\n\nconst baseUtilMap = {\n bits: 'b',\n bytes: 'B',\n};\n\nexport const config = [\n {\n name: 'Data(SI)',\n type: 'si',\n children: [\n {\n name: 'bits',\n },\n {\n name: 'bytes',\n },\n ],\n },\n {\n name: 'Data(IEC)',\n type: 'iec',\n children: [\n {\n name: 'bits',\n },\n {\n name: 'bytes',\n },\n ],\n },\n];\n\nexport function format(value: number, options = defaultOptions) {\n if (value === null || value === undefined)\n return {\n value: '',\n unit: '',\n text: '',\n };\n const baseUtil = options.base ? baseUtilMap[options.base] : ''; // 支持\n if ((options.type === 'si' && Math.abs(value) < 1000) || (options.type === 'iec' && Math.abs(value) < 1024)) {\n return {\n value: _.round(value, options.decimals),\n unit: baseUtil,\n text: _.round(value, options.decimals) + baseUtil,\n };\n }\n\n const baseNum = options.type === 'iec' ? 2 : 10;\n const autoDetectRegex = /(\\d.*\\+)(\\d{1,2})/;\n const autoDetect = value.toExponential();\n const expArray = autoDetect.match(autoDetectRegex);\n\n if (expArray) {\n const expVal = Math.floor(parseInt(_.get(expArray, '[2]')) / 3) * 3;\n const map = _.find(valueMap, { exp: expVal });\n\n if (!map) {\n return {\n value: NaN,\n unit: '',\n text: NaN,\n };\n }\n const unit = _.get(map, options.type);\n const exp = _.get(map, options.type === 'iec' ? 'iecExp' : 'exp');\n const divider = Math.pow(baseNum, exp);\n const newValue = _.round(value / divider, options.decimals);\n\n return {\n value: newValue,\n unit: unit + baseUtil,\n text: newValue + unit + baseUtil,\n };\n }\n return {\n value: _.round(value, options.decimals),\n unit: '',\n text: _.round(value, options.decimals),\n };\n}\n\nexport function parse(value: string, options = defaultOptions) {}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport _ from 'lodash';\nimport moment from 'moment';\nimport { utilValMap } from '../config';\nimport * as byteConverter from './byteConverter';\n\nfunction timeFormatter(val, type: 'seconds' | 'milliseconds', decimals) {\n if (typeof val !== 'number')\n return {\n value: val,\n unit: '',\n text: val,\n };\n const timeMap = [\n {\n unit: 'year',\n value: 31104000,\n },\n {\n unit: 'month',\n value: 2592000,\n },\n {\n unit: 'week',\n value: 604800,\n },\n {\n unit: 'day',\n value: 86400,\n },\n {\n unit: 'hour',\n value: 3600,\n },\n {\n unit: 'min',\n value: 60,\n },\n ];\n const shortTypeMap = {\n seconds: 's',\n milliseconds: 'ms',\n };\n let newVal = val;\n let unit = shortTypeMap[type];\n _.forEach(timeMap, (item) => {\n const _val = val / item.value / (type === 'milliseconds' ? 1000 : 1);\n if (_val >= 1) {\n newVal = _val;\n unit = item.unit;\n return false;\n }\n });\n if (type === 'milliseconds' && unit === 'ms') {\n const _val = newVal / 1000;\n if (_val >= 1) {\n newVal = _val;\n unit = 's';\n }\n }\n return {\n value: _.round(newVal, decimals),\n unit,\n text: _.round(newVal, decimals) + unit,\n };\n}\n\nconst valueFormatter = ({ unit, decimals = 3, dateFormat = 'YYYY-MM-DD HH:mm:ss' }, val) => {\n if (val === null || val === '' || val === undefined) {\n return {\n value: '',\n unit: '',\n text: '',\n };\n }\n if (typeof val !== 'number') {\n val = _.toNumber(val);\n }\n if (unit) {\n const utilValObj = utilValMap[unit];\n if (utilValObj) {\n const { type, base } = utilValObj;\n return byteConverter.format(val, {\n type,\n base,\n decimals,\n });\n }\n if (unit === 'none') {\n return {\n value: _.round(val, decimals),\n unit: '',\n text: _.round(val, decimals),\n };\n }\n if (unit === 'percent') {\n return {\n value: _.round(val, decimals),\n unit: '%',\n text: _.round(val, decimals) + '%',\n };\n }\n if (unit === 'percentUnit') {\n return {\n value: _.round(val * 100, decimals),\n unit: '%',\n text: _.round(val * 100, decimals) + '%',\n };\n }\n if (unit === 'humantimeSeconds') {\n return {\n value: moment.duration(val, 'seconds').humanize(),\n unit: '',\n text: moment.duration(val, 'seconds').humanize(),\n };\n }\n if (unit === 'humantimeMilliseconds') {\n return {\n value: moment.duration(val, 'milliseconds').humanize(),\n unit: '',\n text: moment.duration(val, 'milliseconds').humanize(),\n };\n }\n if (unit === 'seconds') {\n return timeFormatter(val, unit, decimals);\n }\n if (unit === 'milliseconds') {\n return timeFormatter(val, unit, decimals);\n }\n if (unit === 'datetimeSeconds') {\n return {\n value: moment.unix(val).format(dateFormat),\n unit: '',\n text: moment.unix(val).format(dateFormat),\n };\n }\n if (unit === 'datetimeMilliseconds') {\n return {\n value: moment(val).format(dateFormat),\n unit: '',\n text: moment(val).format(dateFormat),\n };\n }\n return {\n value: _.round(val, decimals),\n unit: '',\n text: _.round(val, decimals),\n };\n }\n // 默认返回 SI 不带基础单位\n return byteConverter.format(val, {\n type: 'si',\n decimals,\n });\n};\nexport default valueFormatter;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport _ from 'lodash';\nimport valueFormatter from './valueFormatter';\nimport { statHexPalette } from '../../config';\nimport { IValueMapping, IThresholds } from '../../types';\n\nconst getValueAndToNumber = (value: any[]) => {\n return _.toNumber(_.get(value, 1, NaN));\n};\n\nexport const getSerieTextObj = (value: number | string | null | undefined, standardOptions?: any, valueMappings?: IValueMapping[], thresholds?: IThresholds) => {\n const { unit, decimals, dateFormat } = standardOptions || {};\n const matchedValueMapping = _.find(valueMappings, (item) => {\n const { type, match } = item;\n if (value === null || value === '' || value === undefined) {\n if (type === 'specialValue') {\n if (match?.specialValue === 'empty') {\n return value === '';\n } else if (match?.specialValue === 'null') {\n return value === null || value === undefined;\n }\n }\n return false;\n } else {\n value = _.toNumber(value) as number;\n if (type === 'special') {\n return value === match?.special;\n } else if (type === 'range') {\n if (match?.from && match?.to) {\n return value >= match?.from && value <= match?.to;\n } else if (match?.from) {\n return value >= match?.from;\n } else if (match?.to) {\n return value <= match?.to;\n }\n return false;\n }\n return false;\n }\n });\n let matchedThresholdsColor;\n if (thresholds?.steps) {\n const baseColor = _.get(_.find(thresholds?.steps, { type: 'base' }), 'color');\n matchedThresholdsColor = baseColor;\n }\n _.forEach(\n _.sortBy(thresholds?.steps, (item) => {\n return Number(item.value);\n }),\n (item) => {\n if (item.value && value) {\n value = _.toNumber(value) as number;\n if (value >= item.value) {\n matchedThresholdsColor = item.color;\n }\n }\n },\n );\n const valueObj = valueFormatter({ unit, decimals, dateFormat }, value);\n const newValue = matchedValueMapping?.result?.text ? matchedValueMapping?.result?.text : valueObj.value;\n return {\n value: newValue,\n unit: valueObj.unit,\n color: matchedValueMapping?.result?.color || matchedThresholdsColor,\n text: newValue + valueObj.unit,\n };\n};\n\nconst getCalculatedValuesBySeries = (series: any[], calc: string, { unit, decimals, dateFormat }, valueMappings?: IValueMapping[], thresholds?: IThresholds) => {\n const values = _.map(series, (serie) => {\n const results = {\n lastNotNull: () => _.get(_.last(_.filter(serie.data, (item) => item[1] !== null)), 1),\n last: () => _.get(_.last(serie.data), 1),\n firstNotNull: () => _.get(_.first(_.filter(serie.data, (item) => item[1] !== null)), 1),\n first: () => _.get(_.first(serie.data), 1),\n min: () => getValueAndToNumber(_.minBy(serie.data, (item) => _.toNumber(item[1]))),\n max: () => getValueAndToNumber(_.maxBy(serie.data, (item) => _.toNumber(item[1]))),\n avg: () => _.meanBy(serie.data, (item) => _.toNumber(item[1])),\n sum: () => _.sumBy(serie.data, (item) => _.toNumber(item[1])),\n count: () => _.size(serie.data),\n };\n const stat = results[calc] ? results[calc]() : NaN;\n return {\n id: serie.id,\n name: serie.name,\n metric: serie.metric,\n fields: {\n ...serie.metric,\n refId: serie.refId,\n },\n stat: _.toNumber(stat),\n ...getSerieTextObj(stat, { unit, decimals, dateFormat }, valueMappings, thresholds),\n };\n });\n return values;\n};\n\nexport const getLegendValues = (series: any[], { unit, decimals, dateFormat }, hexPalette: string[]) => {\n const values = _.map(series, (serie, idx) => {\n const results = {\n max: getValueAndToNumber(_.maxBy(serie.data, (item) => _.toNumber(item[1]))),\n min: getValueAndToNumber(_.minBy(serie.data, (item) => _.toNumber(item[1]))),\n avg: _.meanBy(serie.data, (item) => _.toNumber(item[1])),\n sum: _.sumBy(serie.data, (item) => _.toNumber(item[1])),\n last: getValueAndToNumber(_.last(serie.data)),\n };\n return {\n id: serie.id,\n name: serie.name,\n metric: serie.metric,\n offset: serie.offset,\n color: hexPalette[idx % hexPalette.length],\n disabled: serie.visible === false ? true : undefined,\n max: valueFormatter({ unit, decimals, dateFormat }, results.max),\n min: valueFormatter({ unit, decimals, dateFormat }, results.min),\n avg: valueFormatter({ unit, decimals, dateFormat }, results.avg),\n sum: valueFormatter({ unit, decimals, dateFormat }, results.sum),\n last: valueFormatter({ unit, decimals, dateFormat }, results.last),\n };\n });\n return values;\n};\n\nexport default getCalculatedValuesBySeries;\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport React, { useRef, useEffect, useState } from 'react';\nimport _ from 'lodash';\nimport moment from 'moment';\nimport { Table, Tooltip } from 'antd';\nimport classNames from 'classnames';\nimport { VerticalRightOutlined, VerticalLeftOutlined } from '@ant-design/icons';\nimport { useSize } from 'ahooks';\nimport TsGraph from '@fc-plot/ts-graph';\nimport '@fc-plot/ts-graph/dist/index.css';\nimport { IRawTimeRange, parseRange } from '@/components/TimeRangePicker';\nimport { IPanel } from '../../../types';\nimport { hexPalette } from '../../../config';\nimport valueFormatter from '../../utils/valueFormatter';\nimport { getLegendValues } from '../../utils/getCalculatedValuesBySeries';\nimport './style.less';\n\ninterface IProps {\n time?: IRawTimeRange;\n inDashboard?: boolean;\n chartHeight?: string;\n tableHeight?: string;\n values: IPanel;\n series: any[];\n themeMode?: 'dark';\n onClick?: (event: any, datetime: Date, value: number, points: any[]) => void;\n}\n\nfunction getStartAndEndByTargets(targets: any[]) {\n let start = undefined as number | undefined;\n let end = undefined as number | undefined;\n _.forEach(targets, (target) => {\n if (target.time) {\n const { start: targetStart, end: targetEnd } = parseRange(target.time);\n if (!start || targetStart?.unix()! < start) {\n start = targetStart?.unix()!;\n }\n if (!end || targetEnd?.unix()! > end) {\n end = targetEnd?.unix()!;\n }\n }\n });\n return { start, end };\n}\n\nexport default function index(props: IProps) {\n const { time, values, series, inDashboard = true, chartHeight = '200px', tableHeight = '200px', themeMode = '', onClick } = props;\n const { custom, options = {}, targets } = values;\n const { lineWidth = 1, gradientMode = 'none', scaleDistribution } = custom;\n const [seriesData, setSeriesData] = useState(series);\n const [activeLegend, setActiveLegend] = useState('');\n const chartEleRef = useRef(null);\n const chartRef = useRef(null);\n const legendEleRef = useRef(null);\n const legendEleSize = useSize(legendEleRef);\n const displayMode = options.legend?.displayMode || 'table';\n const placement = options.legend?.placement || 'bottom';\n const hasLegend = displayMode !== 'hidden';\n const [legendData, setLegendData] = useState([]);\n const [isExpanded, setIsExpanded] = useState(false);\n let _chartHeight = hasLegend ? `calc(100% - ${legendEleSize?.height! + 16}px)` : '100%';\n let _tableHeight = hasLegend ? '30%' : '0px';\n\n if (!inDashboard) {\n _chartHeight = chartHeight;\n _tableHeight = tableHeight;\n }\n\n if (placement === 'right') {\n _chartHeight = '100%';\n _tableHeight = '100%';\n }\n\n useEffect(() => {\n if (chartEleRef.current) {\n if (chartRef.current) {\n chartRef.current.destroy();\n }\n chartRef.current = new TsGraph({\n timestamp: 'X',\n xkey: 0,\n ykey: 1,\n ykey2: 2,\n ykeyFormatter: (value) => Number(value),\n chart: {\n renderTo: chartEleRef.current,\n height: chartEleRef.current.clientHeight,\n colors: hexPalette,\n marginTop: 0,\n },\n series: [],\n onClick: (event, datetime, value, points) => {\n if (onClick) onClick(event, datetime, value, points);\n },\n });\n }\n if (hasLegend) {\n setLegendData(\n getLegendValues(\n seriesData,\n {\n unit: options?.standardOptions?.util,\n decimals: options?.standardOptions?.decimals,\n dateFormat: options?.standardOptions?.dateFormat,\n },\n hexPalette,\n ),\n );\n } else {\n setLegendData([]);\n }\n return () => {\n if (chartRef.current && typeof chartRef.current.destroy === 'function') {\n chartRef.current.destroy();\n }\n };\n }, [hasLegend]);\n\n useEffect(() => {\n setSeriesData(series);\n }, [JSON.stringify(series)]);\n\n useEffect(() => {\n let xAxisDamin = {};\n if (time) {\n const parsedRange = parseRange(time);\n const startAndEnd = getStartAndEndByTargets(targets);\n const start = startAndEnd.start || moment(parsedRange.start).unix();\n const end = startAndEnd.end || moment(parsedRange.end).unix();\n xAxisDamin = { min: start, max: end };\n }\n if (chartRef.current) {\n chartRef.current.update({\n type: custom.drawStyle === 'lines' ? 'line' : 'bar',\n series: seriesData,\n line: {\n width: lineWidth,\n },\n area: {\n ...chartRef.current.options.area,\n opacity: custom.fillOpacity,\n gradientMode,\n gradientOpacityStopColor: themeMode === 'dark' ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)',\n },\n stack: {\n enabled: custom.stack === 'noraml',\n },\n curve: {\n enabled: true,\n mode: custom.lineInterpolation,\n },\n tooltip: {\n ...chartRef.current.options.tooltip,\n shared: options.tooltip?.mode === 'all',\n sharedSortDirection: options.tooltip?.sort !== 'none' ? options.tooltip?.sort : undefined,\n pointValueformatter: (val) => {\n return valueFormatter(\n {\n unit: options?.standardOptions?.util,\n decimals: options?.standardOptions?.decimals,\n dateFormat: options?.standardOptions?.dateFormat,\n },\n val,\n ).text;\n },\n },\n xAxis: {\n ...chartRef.current.options.xAxis,\n ...xAxisDamin,\n plotLines: options?.xThresholds?.steps,\n lineColor: themeMode === 'dark' ? 'rgba(255,255,255,0.2)' : '#ccc',\n tickColor: themeMode === 'dark' ? 'rgba(255,255,255,0.2)' : '#ccc',\n },\n yAxis: {\n ...chartRef.current.options.yAxis,\n min: options?.standardOptions?.min,\n max: options?.standardOptions?.max,\n scale: scaleDistribution,\n plotLines: _.map(\n _.filter(options?.thresholds?.steps, (item) => {\n return item.value !== null; // 过滤掉 base 值\n }),\n (item) => {\n return {\n ...item,\n shadowColor: themeMode === 'dark' ? 'rgba(255,255,255,0.2)' : '#fff',\n };\n },\n ),\n backgroundColor: themeMode === 'dark' ? '#2A2D3C' : '#fff',\n gridLineColor: themeMode === 'dark' ? 'rgba(255,255,255,0.05)' : '#efefef',\n tickValueFormatter: (val) => {\n return valueFormatter(\n {\n unit: options?.standardOptions?.util,\n decimals: options?.standardOptions?.decimals,\n dateFormat: options?.standardOptions?.dateFormat,\n },\n val,\n ).text;\n },\n },\n });\n }\n if (hasLegend) {\n setLegendData(\n getLegendValues(\n seriesData,\n {\n unit: options?.standardOptions?.util,\n decimals: options?.standardOptions?.decimals,\n dateFormat: options?.standardOptions?.dateFormat,\n },\n hexPalette,\n ),\n );\n } else {\n setLegendData([]);\n }\n }, [JSON.stringify(seriesData), JSON.stringify(custom), JSON.stringify(options), themeMode]);\n\n useEffect(() => {\n // TODO: 这里布局变化了,但是 fc-plot 没有自动 resize,所以这里需要手动 resize\n if (chartRef.current) {\n chartRef.current.handleResize();\n }\n }, [placement]);\n\n return (\n \n
\n {hasLegend && (\n \n {displayMode === 'table' && (\n
\n {\n return (\n \n
{_.get(record, 'metric.__name__')}
\n
{record.offset && record.offset !== 'current' ? `offfset ${record.offset}` : ''}
\n {_.map(_.omit(record.metric, '__name__'), (val, key) => {\n return (\n
\n {key}={val}\n
\n );\n })}\n
\n }\n getTooltipContainer={() => document.body}\n >\n \n {record.offset && record.offset !== 'current' ? offfset {record.offset} : ''}\n {_text}\n \n );\n },\n },\n {\n title: 'Max',\n dataIndex: 'max',\n width: 100,\n sorter: (a, b) => a.max.value - b.max.value,\n render: (text) => {\n return text.text;\n },\n },\n {\n title: 'Min',\n dataIndex: 'min',\n width: 100,\n sorter: (a, b) => a.min.value - b.min.value,\n render: (text) => {\n return text.text;\n },\n },\n {\n title: 'Avg',\n dataIndex: 'avg',\n width: 100,\n sorter: (a, b) => a.avg.value - b.avg.value,\n render: (text) => {\n return text.text;\n },\n },\n {\n title: 'Sum',\n dataIndex: 'sum',\n width: 100,\n sorter: (a, b) => a.sum.value - b.sum.value,\n render: (text) => {\n return text.text;\n },\n },\n {\n title: 'Last',\n dataIndex: 'last',\n width: 100,\n sorter: (a, b) => a.last.value - b.last.value,\n render: (text) => {\n return text.text;\n },\n },\n ]}\n dataSource={legendData}\n locale={{\n emptyText: '暂无数据',\n }}\n pagination={false}\n rowClassName={(record) => {\n return record.disabled ? 'disabled' : '';\n }}\n onRow={(record) => {\n return {\n onClick: () => {\n setActiveLegend(activeLegend !== record.id ? record.id : '');\n setSeriesData(\n _.map(seriesData, (subItem) => {\n return {\n ...subItem,\n visible: activeLegend === record.id ? true : record.id === subItem.id,\n };\n }),\n );\n },\n };\n }}\n />\n
\n )}\n {displayMode === 'list' && !_.isEmpty(legendData) && (\n
\n \n {_.map(legendData, (item) => {\n return (\n {\n setActiveLegend(activeLegend !== item.id ? item.id : '');\n setSeriesData(\n _.map(seriesData, (subItem) => {\n return {\n ...subItem,\n visible: activeLegend === item.id ? true : item.id === subItem.id,\n };\n }),\n );\n }}\n className={item.disabled ? 'disabled' : ''}\n >\n \n {item.name}\n
\n );\n })}\n \n {placement === 'right' && (\n {\n setIsExpanded(!isExpanded);\n }}\n >\n {isExpanded ? : }\n \n )}\n \n )}\n \n )}\n \n );\n}\n","import _ from 'lodash';\nimport { mapOptionToRelativeTimeRange, mapRelativeTimeRangeToOption } from '@/components/TimeRangePicker';\n\nconst alphabet = 'ABCDEFGHIGKLMNOPQRSTUVWXYZ'.split('');\n\nexport const parseTimeToValueAndUnit = (value?: number) => {\n if (!value) {\n return {\n value: value,\n unit: 'min',\n };\n }\n let time = value / 60;\n if (time < 60) {\n return {\n value: time,\n unit: 'min',\n };\n }\n time = time / 60;\n if (time < 24) {\n return {\n value: time,\n unit: 'hour',\n };\n }\n time = time / 24;\n return {\n value: time,\n unit: 'day',\n };\n};\n\nexport const normalizeTime = (value?: number, unit?: 'second' | 'min' | 'hour') => {\n if (!value) {\n return value;\n }\n if (unit === 'second') {\n return value;\n }\n if (unit === 'min') {\n return value * 60;\n }\n if (unit === 'hour') {\n return value * 60 * 60;\n }\n if (unit === 'day') {\n return value * 60 * 60 * 24;\n }\n return value;\n};\n\n/**\n * es 的 query 和 rules 设置为了兼容开源接口,需要转换成 json string 放到 prom_ql 字段里\n * 这里需要把 prom_ql 转换成结构化的 query\n * 这里面还需要转换一些时间字段,这些时间字段默认是秒单位,需要转换成分钟或是小时,xxx_unit: 'min' | 'hour'\n * 1. interval 拆开成 interval 和 interval_unit\n * 2. rule.compare_time 拆开成 compare_time 和 compare_time_unit\n */\nexport const parseValues = (values: any = {}) => {\n const cloned = _.cloneDeep(values);\n const cate = cloned.cate || 'prometheus';\n if (cate === 'elasticsearch') {\n const queryString = cloned.prom_ql;\n let query: any = {};\n try {\n query = JSON.parse(queryString);\n } catch (e) {\n console.error(e);\n }\n if (query?.interval !== undefined) {\n // 第一版的结构,未来会废弃\n query.interval = parseTimeToValueAndUnit(query.interval).value;\n query.interval_unit = parseTimeToValueAndUnit(query.interval).unit;\n query.rules = _.map(query.rules, (rule: any) => {\n return {\n ...rule,\n rule: _.map(rule.rule, (item: any) => {\n return {\n ...item,\n compare_time: parseTimeToValueAndUnit(item.compare_time).value,\n compare_time_unit: parseTimeToValueAndUnit(item.compare_time).unit,\n };\n }),\n };\n });\n cloned.query = query;\n } else if (query?.queries && query?.triggers) {\n /**\n * 新版本结构跟 SLS 一致 Query {\n * queries: any[],\n * triggers: any[],\n * }\n */\n cloned.queries = _.map(query.queries, (item) => {\n return {\n ...item,\n interval: parseTimeToValueAndUnit(item.interval).value,\n interval_unit: parseTimeToValueAndUnit(item.interval).unit,\n };\n });\n cloned.triggers = query.triggers;\n }\n } else if (cate === 'aliyun-sls') {\n const queryString = cloned.prom_ql;\n let query: any = {};\n try {\n query = JSON.parse(queryString);\n } catch (e) {\n console.error(e);\n }\n cloned.queries = _.map(query.queries, (query) => {\n if (query?.keys?.valueKey) {\n query.keys.valueKey = _.split(query.keys.valueKey, ' ');\n } else {\n query.keys.valueKey = [];\n }\n if (query?.keys?.labelKey) {\n query.keys.labelKey = _.split(query.keys.labelKey, ' ');\n } else {\n query.keys.labelKey = [];\n }\n return {\n ..._.omit(query, ['from', 'to']),\n range: mapRelativeTimeRangeToOption({\n start: query.from,\n end: query.to,\n }),\n };\n });\n cloned.triggers = query.triggers;\n }\n cloned.cate = cate;\n return cloned;\n};\n\n/**\n * 同上,提交前需要把结构化的 query 转换成 prom_ql\n * 以及上面被转换的时间字段,也需要转换回秒\n */\nexport const stringifyValues = (values) => {\n const cloned = _.cloneDeep(values);\n const cate = cloned.cate || 'prometheus';\n if (cate === 'elasticsearch') {\n const query = cloned.query;\n if (query?.interval !== undefined) {\n // 第一版的结构,未来会废弃\n query.interval = normalizeTime(query.interval, query.interval_unit);\n delete query.interval_unit;\n query.rules = _.map(query.rules, (rule: any) => {\n return {\n ...rule,\n rule: _.map(rule.rule, (item: any) => {\n const compare_time = normalizeTime(item.compare_time, item.compare_time_unit);\n delete item.compare_time_unit;\n return {\n ...item,\n compare_time,\n };\n }),\n };\n });\n cloned.prom_ql = JSON.stringify(query);\n delete cloned.query;\n } else if (cloned?.queries && cloned?.triggers) {\n const prom_ql: any = {};\n prom_ql.queries = _.map(cloned.queries, (item) => {\n return {\n ..._.omit(item, 'interval_unit'),\n interval: normalizeTime(item.interval, item.interval_unit),\n };\n });\n prom_ql.triggers = _.map(cloned.triggers, (trigger) => {\n if (trigger.mode === 0) {\n return {\n ...trigger,\n exp: stringifyExpressions(trigger.expressions),\n };\n }\n return trigger;\n });\n cloned.prom_ql = JSON.stringify(prom_ql);\n delete cloned.queries;\n delete cloned.triggers;\n }\n } else if (cate === 'aliyun-sls') {\n const { queries, triggers } = cloned;\n const prom_ql: any = {};\n prom_ql.queries = _.map(queries, (query, index) => {\n const parsedRange = mapOptionToRelativeTimeRange(query.range);\n if (query?.keys?.valueKey) {\n query.keys.valueKey = _.join(query.keys.valueKey, ' ');\n }\n if (query?.keys?.labelKey) {\n query.keys.labelKey = _.join(query.keys.labelKey, ' ');\n }\n return {\n ..._.omit(query, 'range'),\n ref: alphabet[index],\n from: parsedRange?.start,\n to: parsedRange?.end,\n };\n });\n prom_ql.triggers = _.map(triggers, (trigger) => {\n if (trigger.mode === 0) {\n return {\n ...trigger,\n exp: stringifyExpressions(trigger.expressions),\n };\n }\n return trigger;\n });\n cloned.prom_ql = JSON.stringify(prom_ql);\n delete cloned.queries;\n delete cloned.triggers;\n }\n\n return cloned;\n};\n\nexport const stringifyExpressions = (\n expressions: {\n ref: string;\n label: string;\n comparisonOperator: string;\n value: string;\n logicalOperator?: string;\n }[],\n) => {\n const logicalOperator = _.get(expressions, '[0].logicalOperator');\n let exp = '';\n _.forEach(expressions, (expression, index) => {\n if (index !== 0) {\n exp += ` ${logicalOperator} `;\n }\n exp += `$${expression.ref}${expression.label ? `.${expression.label}` : ''} ${expression.comparisonOperator} ${expression.value}`;\n });\n return exp;\n};\n","import React, { useState, useRef, useEffect } from 'react';\nimport { Button, Popover } from 'antd';\nimport _ from 'lodash';\nimport moment from 'moment';\nimport TimeRangePicker, { IRawTimeRange, parseRange } from '@/components/TimeRangePicker';\nimport { getDsQuery } from '@/services/warning';\nimport Timeseries from '@/pages/dashboard/Renderer/Renderer/Timeseries';\nimport { normalizeTime } from '../utils';\n\nconst getSerieName = (metric: Object) => {\n let name = metric['__name__'] || '';\n _.forEach(_.omit(metric, '__name__'), (value, key) => {\n name += ` ${key}: ${value}`;\n });\n return _.trim(name);\n};\n\nexport default function GraphPreview({ form }) {\n const divRef = useRef(null);\n const [visible, setVisible] = useState(false);\n const [range, setRange] = useState({\n start: 'now-1h',\n end: 'now',\n });\n const [series, setSeries] = useState([]);\n const fetchSeries = () => {\n const queries = form.getFieldValue('queries');\n const parsedRange = parseRange(range);\n const start = moment(parsedRange.start).unix();\n const end = moment(parsedRange.end).unix();\n getDsQuery({\n cate: form.getFieldValue('cate'),\n cluster: _.join(form.getFieldValue('cluster'), ' '),\n query: _.map(queries, (item) => {\n return {\n index: item.index,\n filter: item.filter,\n value: item.value,\n group_by: item.group_by,\n date_field: item.date_field,\n interval: normalizeTime(item.interval, item.interval_unit),\n start,\n end,\n };\n }),\n }).then((res) => {\n setSeries(\n _.map(res.dat, (item) => {\n return {\n id: _.uniqueId('series_'),\n name: getSerieName(item.metric),\n metric: item.metric,\n data: item.values,\n };\n }),\n );\n });\n };\n\n useEffect(() => {\n if (visible) {\n fetchSeries();\n }\n }, [JSON.stringify(range)]);\n\n return (\n
\n {\n setVisible(visible);\n }}\n title={\n \n \n 数据预览\n
\n
\n \n
\n \n }\n content={\n
\n \n
\n }\n trigger='click'\n getPopupContainer={() => divRef.current || document.body}\n >\n {\n if (!visible) {\n fetchSeries();\n setVisible(true);\n }\n }}\n >\n 数据预览\n \n \n \n );\n}\n","import React, { useState, useEffect } from 'react';\nimport { Form, AutoComplete } from 'antd';\nimport _ from 'lodash';\nimport { getIndices } from '@/services/warning';\n\ninterface IProps {\n prefixField?: any;\n prefixName?: string[];\n cate: string;\n cluster: string[];\n name?: string | string[]; // 可自定义 name 或者 [...prefixName, 'query', 'index']\n}\n\nexport default function IndexSelect({ prefixField = {}, prefixName = [], cate, cluster, name }: IProps) {\n const [options, setOptions] = useState([]);\n const [search, setSearch] = useState('');\n\n useEffect(() => {\n if ((cate === 'elasticsearch' || cate === 'elasticsearch-log') && !_.isEmpty(cluster)) {\n getIndices({ cate, cluster: _.join(cluster, ' ') }).then((res) => {\n setOptions(\n _.map(res.dat, (item) => {\n return {\n value: item,\n };\n }),\n );\n });\n }\n }, [cate, _.join(cluster, ' ')]);\n\n return (\n \n 支持多种配置方式\n
\n 1. 指定单个索引 gb 在 gb 索引中搜索所有的文档\n
\n 2. 指定多个索引 gb,us 在 gb 和 us 索引中搜索所有的文档\n
\n 3. 指定索引前缀 g*,u* 在任何以 g 或者 u 开头的索引中搜索所有的文档\n
\n \n }\n {...prefixField}\n name={name || [...prefixName, 'query', 'index']}\n rules={[\n {\n required: true,\n message: '请输入索引',\n },\n ]}\n validateTrigger='onBlur'\n >\n {\n if (search) {\n return item.value.includes(search);\n }\n return true;\n })}\n onSearch={(val) => {\n setSearch(val);\n }}\n />\n \n );\n}\n","import React from 'react';\nimport { Form, Row, Col, Input } from 'antd';\nimport { QuestionCircleOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport Values from './Values';\nimport GroupBy from './GroupBy';\nimport Time from './Time';\nimport Rules from './Rules';\nimport GraphPreview from './GraphPreview';\nimport IndexSelect from './IndexSelect';\n\nexport default function index({ form }) {\n return (\n <>\n \n
\n _.isEqual(prevValues.cluster, curValues.cluster)} noStyle>\n {({ getFieldValue }) => {\n return ;\n }}\n \n \n \n \n 过滤条件{' '}\n \n \n \n \n }\n name={['query', 'filter']}\n >\n \n \n \n \n {\n return _.isEqual(prevValues.cluster, curValues.cluster) || _.isEqual(prevValues?.query?.index, curValues?.query?.index);\n }}\n noStyle\n >\n {({ getFieldValue }) => {\n return (\n <>\n \n \n \n );\n }}\n \n \n \n 数值提取{' '}\n \n \n \n \n }\n labelWidth={90}\n >\n \n \n \n \n \n {func !== 'count' && func !== 'rawData' && (\n \n \n \n {\n if (search) {\n return item.value.includes(search);\n }\n return true;\n })}\n style={{ width: '100%' }}\n onSearch={setSearch}\n />\n \n \n \n )}\n \n );\n }}\n \n );\n}\n","import React, { useState, useEffect } from 'react';\nimport { Form, Input, Row, Col, Tooltip, AutoComplete, InputNumber, Select } from 'antd';\nimport { PlusCircleOutlined, QuestionCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport { getIndices } from '@/services/warning';\nimport InputGroupWithFormItem from '@/components/InputGroupWithFormItem';\nimport Value from './Value';\nimport GroupBy from '../GroupBy';\n\ninterface IProps {\n form: any;\n cate: string;\n cluster: string[];\n}\n\nconst alphabet = 'ABCDEFGHIGKLMNOPQRSTUVWXYZ'.split('');\n\nexport default function index(props: IProps) {\n const { form, cate, cluster } = props;\n const [indexOptions, setIndexOptions] = useState([]);\n const [indexSearch, setIndexSearch] = useState('');\n\n useEffect(() => {\n if (!_.isEmpty(cluster)) {\n getIndices({ cate, cluster: _.join(cluster, ' ') }).then((res) => {\n setIndexOptions(\n _.map(res.dat, (item) => {\n return {\n value: item,\n };\n }),\n );\n });\n }\n }, [cate, _.join(cluster)]);\n\n return (\n \n {(fields, { add, remove }) => (\n <>\n
\n 查询统计{' '}\n {\n add({});\n }}\n />\n
\n {fields.map((field, index) => {\n return (\n
\n \n
\n \n \n \n \n \n \n \n \n 索引{' '}\n \n 支持多种配置方式\n
\n 1. 指定单个索引 gb 在 gb 索引中搜索所有的文档\n
\n 2. 指定多个索引 gb,us 在 gb 和 us 索引中搜索所有的文档\n
\n 3. 指定索引前缀 g*,u* 在任何以 g 或者 u 开头的索引中搜索所有的文档\n
\n \n }\n >\n \n \n \n }\n >\n \n {\n if (indexSearch) {\n return item.value.includes(indexSearch);\n }\n return true;\n })}\n onSearch={(val) => {\n setIndexSearch(val);\n }}\n />\n \n \n \n
\n \n 查询条件{' '}\n \n \n \n \n }\n labelWidth={90}\n >\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n 间隔\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n {({ getFieldValue }) => {\n const index = getFieldValue(['queries', field.name, 'index']);\n return (\n <>\n \n
\n \n
\n \n );\n }}\n
\n {fields.length > 1 && (\n {\n remove(field.name);\n }}\n />\n )}\n \n );\n })}\n \n )}\n \n );\n}\n","/**\n * 简单模式\n */\nimport React from 'react';\nimport { Form, Space, Input, Select, InputNumber } from 'antd';\nimport { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\n\ninterface IProps {\n prefixField?: any;\n fullPrefixName?: (string | number)[]; // 完整的前置字段名,用于 getFieldValue 获取指定字段的值\n prefixName?: (string | number)[]; // 列表字段名\n queries: any[];\n}\n\nconst alphabet = 'ABCDEFGHIGKLMNOPQRSTUVWXYZ'.split('');\n\nexport default function Builder(props: IProps) {\n const { prefixField = {}, fullPrefixName = [], prefixName = [], queries } = props;\n\n return (\n
\n \n {(fields, { add, remove }) => (\n
\n {fields.map((field) => {\n return (\n
\n \n \n \n \n {/* \n \n */}\n \n \n \n \n \n \n {field.name !== fields.length - 1 && (\n \n \n \n )}\n \n {\n add({\n ref: alphabet[fields.length],\n });\n }}\n />\n\n {fields.length > 1 && (\n {\n remove(field.name);\n }}\n />\n )}\n \n \n
\n );\n })}\n
\n )}\n \n
\n );\n}\n","/**\n * 表达式模式(代码模式)\n */\nimport React from 'react';\nimport { Form, Input } from 'antd';\n\ninterface IProps {\n prefixField?: any;\n fullPrefixName?: (string | number)[]; // 完整的前置字段名,用于 getFieldValue 获取指定字段的值\n prefixName?: (string | number)[]; // 列表字段名\n}\n\nexport default function Code(props: IProps) {\n const { prefixField = {}, fullPrefixName = [], prefixName = [] } = props;\n\n return (\n \n \n \n );\n}\n","import React from 'react';\nimport { Form, Radio, Space, Input, Select } from 'antd';\nimport { PlusCircleOutlined, MinusCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport InputGroupWithFormItem from '@/components/InputGroupWithFormItem';\nimport Builder from './Builder';\nimport Code from './Code';\n\ninterface IProps {\n prefixField?: any;\n fullPrefixName?: (string | number)[]; // 完整的前置字段名,用于 getFieldValue 获取指定字段的值\n prefixName?: (string | number)[]; // 列表字段名\n}\n\nexport default function Trigger(props: IProps) {\n const { prefixField = {}, fullPrefixName = [], prefixName = [] } = props;\n\n return (\n
\n \n \n 简单模式\n 表达式模式\n \n \n \n {({ getFieldValue }) => {\n const mode = getFieldValue([...fullPrefixName, 'mode']);\n const queries = getFieldValue(['queries']);\n if (mode == 0) {\n return ;\n }\n if (mode === 1) {\n return ;\n }\n }}\n \n \n {(fields, { add, remove }) => (\n
\n
\n 关联 Label:{' '}\n {\n add();\n }}\n />\n
\n {fields.map((field) => {\n return (\n \n \n \n \n \n \n \n \n \n \n \n {\n remove(field.name);\n }}\n />\n \n \n );\n })}\n
\n )}\n
\n \n \n \n \n \n
\n );\n}\n","import React from 'react';\nimport { Form } from 'antd';\nimport { PlusCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';\nimport Trigger from './Trigger';\n\ninterface IProps {\n prefixField?: any;\n fullPrefixName?: string[]; // 完整的前置字段名,用于 getFieldValue 获取指定字段的值\n prefixName?: string[]; // 列表字段名\n}\n\nexport default function index(props: IProps) {\n const { prefixField = {}, fullPrefixName = [], prefixName = [] } = props;\n return (\n \n {(fields, { add, remove }) => (\n
\n
\n 告警条件{' '}\n {\n add({});\n }}\n />\n
\n {fields.map((field) => {\n return (\n
\n \n {fields.length > 1 && (\n {\n remove(field.name);\n }}\n />\n )}\n
\n );\n })}\n
\n )}\n \n );\n}\n","import React from 'react';\nimport _ from 'lodash';\nimport { Form } from 'antd';\nimport Queries from './Queries';\nimport GraphPreview from './GraphPreview';\nimport Triggers from '../AliyunSLSSettings/Triggers';\n\nexport default function index({ form }) {\n return (\n _.isEqual(prevValues.cluster, curValues.cluster)} noStyle>\n {({ getFieldValue }) => {\n const cate = getFieldValue('cate');\n const cluster = getFieldValue('cluster');\n return (\n <>\n \n \n \n \n );\n }}\n \n );\n}\n","/*\n * Copyright 2022 Nightingale Team\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\nimport request from '@/utils/request';\nimport { RequestMethod } from '@/store/common';\nimport { N9EAPI } from '../../config/constant';\n\n// 获取节点key\nexport const GetTagPairs = function (data: object) {\n return request(`/api/n9e/tag-pairs`, {\n method: RequestMethod.Post,\n data,\n });\n};\n\n// 查询 Metrics\nexport const GetMetrics = function (data: object) {\n return request(`/api/n9e/tag-metrics`, {\n method: RequestMethod.Post,\n data,\n });\n};\n\n// 查询 上报数据\nexport const GetData = function (data: object) {\n return request(`/api/n9e/query`, {\n method: RequestMethod.Post,\n data,\n });\n};\n\nexport const getQueryBench = function (data?: { series_num: number; point_num: number }) {\n return request(`/api/n9e/query-bench`, {\n method: RequestMethod.Post,\n params: data,\n });\n};\n\n// 分享图表 存临时数据\nexport const SetTmpChartData = function (data: { configs: string }[]) {\n return request(`/api/n9e/share-charts`, {\n method: RequestMethod.Post,\n data,\n });\n};\n// 分享图表 读临时数据\nexport const GetTmpChartData = function (ids: string) {\n return request(`/api/n9e/share-charts?ids=${ids}`, {\n method: RequestMethod.Get,\n });\n};\n\nexport const prometheusAPI = function (path: string, params, options) {\n return request(`/api/n9e/prometheus/api/v1/${path}`, {\n method: RequestMethod.Get,\n params,\n ...options,\n });\n};\n\nexport const getSLSProject = function (data: { cate: string; cluster: string }): Promise {\n return request('/api/n9e-plus/sls-project', {\n method: RequestMethod.Post,\n data,\n }).then((res) => res.dat);\n};\n\nexport const getSLSLogstore = function (data: { cate: string; cluster: string; project: string }): Promise<{ dat: string[] }> {\n return request('/api/n9e-plus/sls-logstore', {\n method: RequestMethod.Post,\n data,\n }).then((res) => res.dat);\n};\n\nexport const getSLSFields = function (data: {\n cate: string;\n cluster: string;\n query: {\n project: string;\n logstore: string;\n from: number;\n to: number;\n lines: number;\n offset: number;\n reverse: boolean;\n power_sql: boolean;\n }[];\n}): Promise {\n return request('/api/n9e-plus/sls-fields', {\n method: RequestMethod.Post,\n data,\n }).then((res) => res.dat);\n};\n\nexport const getSLSLogs = function (data: {\n cate: string;\n cluster: string;\n query: {\n project: string;\n logstore: string;\n from: number;\n to: number;\n lines: number;\n offset: number;\n reverse: boolean;\n power_sql: boolean;\n }[];\n}): Promise<{\n total: number;\n list: {\n [index: string]: string;\n }[];\n}> {\n return request('/api/n9e-plus/logs-query', {\n method: RequestMethod.Post,\n data,\n }).then((res) => res.dat);\n};\n\nexport const getSLSMetrics = function (data: {\n cate: string;\n cluster: string;\n query: {\n project: string;\n logstore: string;\n from: number;\n to: number;\n lines: number;\n offset: number;\n reverse: boolean;\n power_sql: boolean;\n // keys?: {\n // valueKey: string;\n // labelKey: string;\n // timeKey: string;\n // timeFormat: string;\n // };\n };\n}): Promise<{ dat: any }> {\n return request('/api/n9e-plus/sls-fields', {\n method: RequestMethod.Post,\n data,\n });\n};\n\nexport const getHistogram = function (data: {\n cate: string;\n cluster: string;\n query: {\n project: string;\n logstore: string;\n from: number;\n to: number;\n lines: number;\n offset: number;\n reverse: boolean;\n power_sql: boolean;\n }[];\n}): Promise<{\n dat: {\n metric: string;\n values: [number, number][];\n }[];\n}> {\n return request('/api/n9e-plus/histogram', {\n method: RequestMethod.Post,\n data,\n }).then((res) => res.dat);\n};\n\nexport const getDsQuery = function (data: {\n cate: string;\n cluster: string;\n query: {\n project: string;\n logstore: string;\n from: number;\n to: number;\n lines: number;\n offset: number;\n reverse: boolean;\n power_sql: boolean;\n }[];\n}): Promise<{\n dat: {\n metric: string;\n values: [number, number][];\n }[];\n}> {\n return request('/api/n9e-plus/ds-query', {\n method: RequestMethod.Post,\n data,\n }).then((res) => res.dat);\n};\n","import React, { useEffect, useState } from 'react';\nimport { AutoComplete, Tooltip, Form } from 'antd';\nimport { QuestionCircleOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport { DatasourceCateEnum } from '@/utils/constant';\nimport { getSLSProject } from '@/services/metric';\nimport InputGroupWithFormItem from '@/components/InputGroupWithFormItem';\n\ninterface IProps {\n datasourceCate: DatasourceCateEnum.aliyunSLS;\n datasourceName: string;\n prefixField?: any;\n prefixName?: (string | number)[];\n width?: number | string;\n layout?: 'horizontal' | 'vertical';\n}\n\nexport default function ProjectSelect(props: IProps) {\n const { datasourceCate, datasourceName, prefixField = {}, prefixName = [], width = 180, layout = 'horizontal' } = props;\n const [options, setOptions] = useState<{ label; value }[]>([]);\n const label = (\n \n 项目{' '}\n \n 项目是日志服务的资源管理单元,是进行多用户隔离与访问控制的主要边界。更多信息,请参见\n \n 项目\n \n \n }\n >\n \n \n \n );\n\n useEffect(() => {\n if (datasourceName) {\n getSLSProject({\n cate: datasourceCate,\n cluster: datasourceName,\n }).then((res) => {\n setOptions(\n _.map(res, (item) => {\n return {\n label: item,\n value: item,\n };\n }),\n );\n });\n }\n }, [datasourceName]);\n\n if (layout === 'vertical') {\n return (\n \n \n \n );\n }\n return (\n \n \n \n \n \n );\n}\n","import React, { useEffect, useState } from 'react';\nimport { AutoComplete, Tooltip, Form } from 'antd';\nimport { QuestionCircleOutlined } from '@ant-design/icons';\nimport _ from 'lodash';\nimport { DatasourceCateEnum } from '@/utils/constant';\nimport { getSLSLogstore } from '@/services/metric';\nimport InputGroupWithFormItem from '@/components/InputGroupWithFormItem';\n\ninterface IProps {\n datasourceCate: DatasourceCateEnum.aliyunSLS;\n datasourceName: string;\n project?: string;\n prefixField?: any;\n prefixName?: (string | number)[];\n width?: number | string;\n layout?: 'horizontal' | 'vertical';\n}\n\nexport default function LogstoreSelect(props: IProps) {\n const { datasourceCate, datasourceName, project, prefixField = {}, prefixName = [], width = 190, layout = 'horizontal' } = props;\n const [options, setOptions] = useState<{ label; value }[]>([]);\n const label = (\n \n 日志库{' '}\n \n 日志库是日志服务中日志数据的采集、存储和查询单元。更多信息,请参见\n \n 日志库\n \n \n }\n >\n \n \n \n );\n\n useEffect(() => {\n if (datasourceName && project) {\n getSLSLogstore({\n cate: datasourceCate,\n cluster: datasourceName,\n project,\n }).then((res) => {\n setOptions(\n _.map(res, (item) => {\n return {\n label: item,\n value: item,\n };\n }),\n );\n });\n }\n }, [datasourceName, project]);\n\n if (layout === 'vertical') {\n return (\n \n \n \n );\n }\n\n return (\n \n \n \n \n \n );\n}\n","const protocols = ['http', 'https', 'mailto', 'tel']\n\n/**\n * @param {string} uri\n * @returns {string}\n */\nexport function uriTransformer(uri) {\n const url = (uri || '').trim()\n const first = url.charAt(0)\n\n if (first === '#' || first === '/') {\n return url\n }\n\n const colon = url.indexOf(':')\n if (colon === -1) {\n return url\n }\n\n let index = -1\n\n while (++index < protocols.length) {\n const protocol = protocols[index]\n\n if (\n colon === protocol.length &&\n url.slice(0, protocol.length).toLowerCase() === protocol\n ) {\n return url\n }\n }\n\n index = url.indexOf('?')\n if (index !== -1 && colon > index) {\n return url\n }\n\n index = url.indexOf('#')\n if (index !== -1 && colon > index) {\n return url\n }\n\n // eslint-disable-next-line no-script-url\n return 'javascript:void(0)'\n}\n","/**\n * @typedef {import('unist').Point} Point\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Position} Position\n * @typedef {object & {type: string, position?: Position|undefined}} NodeLike\n */\n\n/**\n * Stringify one point, a position (start and end points), or a node’s\n * positional information.\n *\n * @param {Node|NodeLike|Position|Point|null} [value]\n * @returns {string}\n */\nexport function stringifyPosition(value) {\n // Nothing.\n if (!value || typeof value !== 'object') {\n return ''\n }\n\n // Node.\n if ('position' in value || 'type' in value) {\n return position(value.position)\n }\n\n // Position.\n if ('start' in value || 'end' in value) {\n return position(value)\n }\n\n // Point.\n if ('line' in value || 'column' in value) {\n return point(value)\n }\n\n // ?\n return ''\n}\n\n/**\n * @param {Point|undefined} point\n * @returns {string}\n */\nfunction point(point) {\n return index(point && point.line) + ':' + index(point && point.column)\n}\n\n/**\n * @param {Position|undefined} pos\n * @returns {string}\n */\nfunction position(pos) {\n return point(pos && pos.start) + '-' + point(pos && pos.end)\n}\n\n/**\n * @param {number|undefined} value\n * @returns {number}\n */\nfunction index(value) {\n return value && typeof value === 'number' ? value : 1\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Position} Position\n * @typedef {import('unist').Point} Point\n * @typedef {object & {type: string, position?: Position|undefined}} NodeLike\n */\n\nimport {stringifyPosition} from 'unist-util-stringify-position'\n\nexport class VFileMessage extends Error {\n /**\n * Constructor of a message for `reason` at `place` from `origin`.\n * When an error is passed in as `reason`, copies the `stack`.\n *\n * @param {string|Error} reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given.\n * @param {Node|NodeLike|Position|Point} [place] Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional).\n * @param {string} [origin] Place in code the message originates from (`string`, optional).\n */\n constructor(reason, place, origin) {\n /** @type {[string|null, string|null]} */\n const parts = [null, null]\n /** @type {Position} */\n let position = {\n // @ts-expect-error: we always follows the structure of `position`.\n start: {line: null, column: null},\n // @ts-expect-error: \"\n end: {line: null, column: null}\n }\n\n super()\n\n if (typeof place === 'string') {\n origin = place\n place = undefined\n }\n\n if (typeof origin === 'string') {\n const index = origin.indexOf(':')\n\n if (index === -1) {\n parts[1] = origin\n } else {\n parts[0] = origin.slice(0, index)\n parts[1] = origin.slice(index + 1)\n }\n }\n\n if (place) {\n // Node.\n if ('type' in place || 'position' in place) {\n if (place.position) {\n position = place.position\n }\n }\n // Position.\n else if ('start' in place || 'end' in place) {\n position = place\n }\n // Point.\n else if ('line' in place || 'column' in place) {\n position.start = place\n }\n }\n\n // Fields from `Error`\n this.name = stringifyPosition(place) || '1:1'\n this.message = typeof reason === 'object' ? reason.message : reason\n this.stack = typeof reason === 'object' ? reason.stack : ''\n\n /**\n * Reason for message.\n * @type {string}\n */\n this.reason = this.message\n /**\n * If true, marks associated file as no longer processable.\n * @type {boolean?}\n */\n // eslint-disable-next-line no-unused-expressions\n this.fatal\n /**\n * Starting line of error.\n * @type {number?}\n */\n this.line = position.start.line\n /**\n * Starting column of error.\n * @type {number?}\n */\n this.column = position.start.column\n /**\n * Namespace of warning.\n * @type {string?}\n */\n this.source = parts[0]\n /**\n * Category of message.\n * @type {string?}\n */\n this.ruleId = parts[1]\n /**\n * Full range information, when available.\n * Has start and end properties, both set to an object with line and column, set to number?.\n * @type {Position?}\n */\n this.position = position\n\n // The following fields are “well known”.\n // Not standard.\n // Feel free to add other non-standard fields to your messages.\n\n /* eslint-disable no-unused-expressions */\n /**\n * You can use this to specify the source value that’s being reported, which\n * is deemed incorrect.\n * @type {string?}\n */\n this.actual\n /**\n * You can use this to suggest values that should be used instead of\n * `actual`, one or more values that are deemed as acceptable.\n * @type {Array?}\n */\n this.expected\n /**\n * You may add a file property with a path of a file (used throughout the VFile ecosystem).\n * @type {string?}\n */\n this.file\n /**\n * You may add a url property with a link to documentation for the message.\n * @type {string?}\n */\n this.url\n /**\n * You may add a note property with a long form description of the message (supported by vfile-reporter).\n * @type {string?}\n */\n this.note\n /* eslint-enable no-unused-expressions */\n }\n}\n\nVFileMessage.prototype.file = ''\nVFileMessage.prototype.name = ''\nVFileMessage.prototype.reason = ''\nVFileMessage.prototype.message = ''\nVFileMessage.prototype.stack = ''\nVFileMessage.prototype.fatal = null\nVFileMessage.prototype.column = null\nVFileMessage.prototype.line = null\nVFileMessage.prototype.source = null\nVFileMessage.prototype.ruleId = null\nVFileMessage.prototype.position = null\n","// A derivative work based on:\n// .\n// Which is licensed:\n//\n// MIT License\n//\n// Copyright (c) 2013 James Halliday\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of\n// this software and associated documentation files (the \"Software\"), to deal in\n// the Software without restriction, including without limitation the rights to\n// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n// the Software, and to permit persons to whom the Software is furnished to do so,\n// subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A derivative work based on:\n//\n// Parts of that are extracted from Node’s internal `path` module:\n// .\n// Which is licensed:\n//\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nexport const path = {basename, dirname, extname, join, sep: '/'}\n\n/* eslint-disable max-depth, complexity */\n\n/**\n * @param {string} path\n * @param {string} [ext]\n * @returns {string}\n */\nfunction basename(path, ext) {\n if (ext !== undefined && typeof ext !== 'string') {\n throw new TypeError('\"ext\" argument must be a string')\n }\n\n assertPath(path)\n let start = 0\n let end = -1\n let index = path.length\n /** @type {boolean|undefined} */\n let seenNonSlash\n\n if (ext === undefined || ext.length === 0 || ext.length > path.length) {\n while (index--) {\n if (path.charCodeAt(index) === 47 /* `/` */) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now.\n if (seenNonSlash) {\n start = index + 1\n break\n }\n } else if (end < 0) {\n // We saw the first non-path separator, mark this as the end of our\n // path component.\n seenNonSlash = true\n end = index + 1\n }\n }\n\n return end < 0 ? '' : path.slice(start, end)\n }\n\n if (ext === path) {\n return ''\n }\n\n let firstNonSlashEnd = -1\n let extIndex = ext.length - 1\n\n while (index--) {\n if (path.charCodeAt(index) === 47 /* `/` */) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now.\n if (seenNonSlash) {\n start = index + 1\n break\n }\n } else {\n if (firstNonSlashEnd < 0) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching.\n seenNonSlash = true\n firstNonSlashEnd = index + 1\n }\n\n if (extIndex > -1) {\n // Try to match the explicit extension.\n if (path.charCodeAt(index) === ext.charCodeAt(extIndex--)) {\n if (extIndex < 0) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = index\n }\n } else {\n // Extension does not match, so our result is the entire path\n // component\n extIndex = -1\n end = firstNonSlashEnd\n }\n }\n }\n }\n\n if (start === end) {\n end = firstNonSlashEnd\n } else if (end < 0) {\n end = path.length\n }\n\n return path.slice(start, end)\n}\n\n/**\n * @param {string} path\n * @returns {string}\n */\nfunction dirname(path) {\n assertPath(path)\n\n if (path.length === 0) {\n return '.'\n }\n\n let end = -1\n let index = path.length\n /** @type {boolean|undefined} */\n let unmatchedSlash\n\n // Prefix `--` is important to not run on `0`.\n while (--index) {\n if (path.charCodeAt(index) === 47 /* `/` */) {\n if (unmatchedSlash) {\n end = index\n break\n }\n } else if (!unmatchedSlash) {\n // We saw the first non-path separator\n unmatchedSlash = true\n }\n }\n\n return end < 0\n ? path.charCodeAt(0) === 47 /* `/` */\n ? '/'\n : '.'\n : end === 1 && path.charCodeAt(0) === 47 /* `/` */\n ? '//'\n : path.slice(0, end)\n}\n\n/**\n * @param {string} path\n * @returns {string}\n */\nfunction extname(path) {\n assertPath(path)\n\n let index = path.length\n\n let end = -1\n let startPart = 0\n let startDot = -1\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find.\n let preDotState = 0\n /** @type {boolean|undefined} */\n let unmatchedSlash\n\n while (index--) {\n const code = path.charCodeAt(index)\n\n if (code === 47 /* `/` */) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now.\n if (unmatchedSlash) {\n startPart = index + 1\n break\n }\n\n continue\n }\n\n if (end < 0) {\n // We saw the first non-path separator, mark this as the end of our\n // extension.\n unmatchedSlash = true\n end = index + 1\n }\n\n if (code === 46 /* `.` */) {\n // If this is our first dot, mark it as the start of our extension.\n if (startDot < 0) {\n startDot = index\n } else if (preDotState !== 1) {\n preDotState = 1\n }\n } else if (startDot > -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension.\n preDotState = -1\n }\n }\n\n if (\n startDot < 0 ||\n end < 0 ||\n // We saw a non-dot character immediately before the dot.\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly `..`.\n (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)\n ) {\n return ''\n }\n\n return path.slice(startDot, end)\n}\n\n/**\n * @param {Array} segments\n * @returns {string}\n */\nfunction join(...segments) {\n let index = -1\n /** @type {string|undefined} */\n let joined\n\n while (++index < segments.length) {\n assertPath(segments[index])\n\n if (segments[index]) {\n joined =\n joined === undefined ? segments[index] : joined + '/' + segments[index]\n }\n }\n\n return joined === undefined ? '.' : normalize(joined)\n}\n\n/**\n * Note: `normalize` is not exposed as `path.normalize`, so some code is\n * manually removed from it.\n *\n * @param {string} path\n * @returns {string}\n */\nfunction normalize(path) {\n assertPath(path)\n\n const absolute = path.charCodeAt(0) === 47 /* `/` */\n\n // Normalize the path according to POSIX rules.\n let value = normalizeString(path, !absolute)\n\n if (value.length === 0 && !absolute) {\n value = '.'\n }\n\n if (value.length > 0 && path.charCodeAt(path.length - 1) === 47 /* / */) {\n value += '/'\n }\n\n return absolute ? '/' + value : value\n}\n\n/**\n * Resolve `.` and `..` elements in a path with directory names.\n *\n * @param {string} path\n * @param {boolean} allowAboveRoot\n * @returns {string}\n */\nfunction normalizeString(path, allowAboveRoot) {\n let result = ''\n let lastSegmentLength = 0\n let lastSlash = -1\n let dots = 0\n let index = -1\n /** @type {number|undefined} */\n let code\n /** @type {number} */\n let lastSlashIndex\n\n while (++index <= path.length) {\n if (index < path.length) {\n code = path.charCodeAt(index)\n } else if (code === 47 /* `/` */) {\n break\n } else {\n code = 47 /* `/` */\n }\n\n if (code === 47 /* `/` */) {\n if (lastSlash === index - 1 || dots === 1) {\n // Empty.\n } else if (lastSlash !== index - 1 && dots === 2) {\n if (\n result.length < 2 ||\n lastSegmentLength !== 2 ||\n result.charCodeAt(result.length - 1) !== 46 /* `.` */ ||\n result.charCodeAt(result.length - 2) !== 46 /* `.` */\n ) {\n if (result.length > 2) {\n lastSlashIndex = result.lastIndexOf('/')\n\n if (lastSlashIndex !== result.length - 1) {\n if (lastSlashIndex < 0) {\n result = ''\n lastSegmentLength = 0\n } else {\n result = result.slice(0, lastSlashIndex)\n lastSegmentLength = result.length - 1 - result.lastIndexOf('/')\n }\n\n lastSlash = index\n dots = 0\n continue\n }\n } else if (result.length > 0) {\n result = ''\n lastSegmentLength = 0\n lastSlash = index\n dots = 0\n continue\n }\n }\n\n if (allowAboveRoot) {\n result = result.length > 0 ? result + '/..' : '..'\n lastSegmentLength = 2\n }\n } else {\n if (result.length > 0) {\n result += '/' + path.slice(lastSlash + 1, index)\n } else {\n result = path.slice(lastSlash + 1, index)\n }\n\n lastSegmentLength = index - lastSlash - 1\n }\n\n lastSlash = index\n dots = 0\n } else if (code === 46 /* `.` */ && dots > -1) {\n dots++\n } else {\n dots = -1\n }\n }\n\n return result\n}\n\n/**\n * @param {string} path\n */\nfunction assertPath(path) {\n if (typeof path !== 'string') {\n throw new TypeError(\n 'Path must be a string. Received ' + JSON.stringify(path)\n )\n }\n}\n\n/* eslint-enable max-depth, complexity */\n","// Somewhat based on:\n// .\n// But I don’t think one tiny line of code can be copyrighted. 😅\nexport const proc = {cwd}\n\nfunction cwd() {\n return '/'\n}\n","/**\n * @typedef URL\n * @property {string} hash\n * @property {string} host\n * @property {string} hostname\n * @property {string} href\n * @property {string} origin\n * @property {string} password\n * @property {string} pathname\n * @property {string} port\n * @property {string} protocol\n * @property {string} search\n * @property {any} searchParams\n * @property {string} username\n * @property {() => string} toString\n * @property {() => string} toJSON\n */\n\n/**\n * @param {unknown} fileURLOrPath\n * @returns {fileURLOrPath is URL}\n */\n// From: \nexport function isUrl(fileURLOrPath) {\n return (\n fileURLOrPath !== null &&\n typeof fileURLOrPath === 'object' &&\n // @ts-expect-error: indexable.\n fileURLOrPath.href &&\n // @ts-expect-error: indexable.\n fileURLOrPath.origin\n )\n}\n","/// \n\nimport {isUrl} from './minurl.shared.js'\n\n// See: \n\n/**\n * @param {string|URL} path\n */\nexport function urlToPath(path) {\n if (typeof path === 'string') {\n path = new URL(path)\n } else if (!isUrl(path)) {\n /** @type {NodeJS.ErrnoException} */\n const error = new TypeError(\n 'The \"path\" argument must be of type string or an instance of URL. Received `' +\n path +\n '`'\n )\n error.code = 'ERR_INVALID_ARG_TYPE'\n throw error\n }\n\n if (path.protocol !== 'file:') {\n /** @type {NodeJS.ErrnoException} */\n const error = new TypeError('The URL must be of scheme file')\n error.code = 'ERR_INVALID_URL_SCHEME'\n throw error\n }\n\n return getPathFromURLPosix(path)\n}\n\n/**\n * @param {URL} url\n */\nfunction getPathFromURLPosix(url) {\n if (url.hostname !== '') {\n /** @type {NodeJS.ErrnoException} */\n const error = new TypeError(\n 'File URL host must be \"localhost\" or empty on darwin'\n )\n error.code = 'ERR_INVALID_FILE_URL_HOST'\n throw error\n }\n\n const pathname = url.pathname\n let index = -1\n\n while (++index < pathname.length) {\n if (\n pathname.charCodeAt(index) === 37 /* `%` */ &&\n pathname.charCodeAt(index + 1) === 50 /* `2` */\n ) {\n const third = pathname.charCodeAt(index + 2)\n if (third === 70 /* `F` */ || third === 102 /* `f` */) {\n /** @type {NodeJS.ErrnoException} */\n const error = new TypeError(\n 'File URL path must not include encoded / characters'\n )\n error.code = 'ERR_INVALID_FILE_URL_PATH'\n throw error\n }\n }\n }\n\n return decodeURIComponent(pathname)\n}\n\nexport {isUrl} from './minurl.shared.js'\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Position} Position\n * @typedef {import('unist').Point} Point\n * @typedef {Record & {type: string, position?: Position|undefined}} NodeLike\n * @typedef {import('./minurl.shared.js').URL} URL\n * @typedef {import('..').VFileData} VFileData\n * @typedef {import('..').VFileValue} VFileValue\n *\n * @typedef {'ascii'|'utf8'|'utf-8'|'utf16le'|'ucs2'|'ucs-2'|'base64'|'base64url'|'latin1'|'binary'|'hex'} BufferEncoding\n * Encodings supported by the buffer class.\n * This is a copy of the typing from Node, copied to prevent Node globals from\n * being needed.\n * Copied from: \n *\n * @typedef {VFileValue|VFileOptions|VFile|URL} VFileCompatible\n * Things that can be passed to the constructor.\n *\n * @typedef VFileCoreOptions\n * @property {VFileValue} [value]\n * @property {string} [cwd]\n * @property {Array} [history]\n * @property {string|URL} [path]\n * @property {string} [basename]\n * @property {string} [stem]\n * @property {string} [extname]\n * @property {string} [dirname]\n * @property {VFileData} [data]\n *\n * @typedef Map\n * Raw source map, see:\n * .\n * @property {number} version\n * @property {Array} sources\n * @property {Array} names\n * @property {string|undefined} [sourceRoot]\n * @property {Array|undefined} [sourcesContent]\n * @property {string} mappings\n * @property {string} file\n *\n * @typedef {{[key: string]: unknown} & VFileCoreOptions} VFileOptions\n * Configuration: a bunch of keys that will be shallow copied over to the new\n * file.\n *\n * @typedef {Record} VFileReporterSettings\n * @typedef {(files: Array, options: T) => string} VFileReporter\n */\n\nimport buffer from 'is-buffer'\nimport {VFileMessage} from 'vfile-message'\nimport {path} from './minpath.js'\nimport {proc} from './minproc.js'\nimport {urlToPath, isUrl} from './minurl.js'\n\n// Order of setting (least specific to most), we need this because otherwise\n// `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a\n// stem can be set.\nconst order = ['history', 'path', 'basename', 'stem', 'extname', 'dirname']\n\nexport class VFile {\n /**\n * Create a new virtual file.\n *\n * If `options` is `string` or `Buffer`, treats it as `{value: options}`.\n * If `options` is a `VFile`, shallow copies its data over to the new file.\n * All other given fields are set on the newly created `VFile`.\n *\n * Path related properties are set in the following order (least specific to\n * most specific): `history`, `path`, `basename`, `stem`, `extname`,\n * `dirname`.\n *\n * It’s not possible to set either `dirname` or `extname` without setting\n * either `history`, `path`, `basename`, or `stem` as well.\n *\n * @param {VFileCompatible} [value]\n */\n constructor(value) {\n /** @type {VFileOptions} */\n let options\n\n if (!value) {\n options = {}\n } else if (typeof value === 'string' || buffer(value)) {\n // @ts-expect-error Looks like a buffer.\n options = {value}\n } else if (isUrl(value)) {\n options = {path: value}\n } else {\n // @ts-expect-error Looks like file or options.\n options = value\n }\n\n /**\n * Place to store custom information.\n * It’s OK to store custom data directly on the file, moving it to `data`\n * gives a little more privacy.\n * @type {VFileData}\n */\n this.data = {}\n\n /**\n * List of messages associated with the file.\n * @type {Array}\n */\n this.messages = []\n\n /**\n * List of file paths the file moved between.\n * @type {Array}\n */\n this.history = []\n\n /**\n * Base of `path`.\n * Defaults to `process.cwd()` (`/` in browsers).\n * @type {string}\n */\n this.cwd = proc.cwd()\n\n /* eslint-disable no-unused-expressions */\n /**\n * Raw value.\n * @type {VFileValue}\n */\n this.value\n\n // The below are non-standard, they are “well-known”.\n // As in, used in several tools.\n\n /**\n * Whether a file was saved to disk.\n * This is used by vfile reporters.\n * @type {boolean}\n */\n this.stored\n\n /**\n * Sometimes files have a non-string representation.\n * This can be stored in the `result` field.\n * One example is when turning markdown into React nodes.\n * This is used by unified to store non-string results.\n * @type {unknown}\n */\n this.result\n\n /**\n * Sometimes files have a source map associated with them.\n * This can be stored in the `map` field.\n * This should be a `RawSourceMap` type from the `source-map` module.\n * @type {Map|undefined}\n */\n this.map\n /* eslint-enable no-unused-expressions */\n\n // Set path related properties in the correct order.\n let index = -1\n\n while (++index < order.length) {\n const prop = order[index]\n\n // Note: we specifically use `in` instead of `hasOwnProperty` to accept\n // `vfile`s too.\n if (prop in options && options[prop] !== undefined) {\n // @ts-expect-error: TS is confused by the different types for `history`.\n this[prop] = prop === 'history' ? [...options[prop]] : options[prop]\n }\n }\n\n /** @type {string} */\n let prop\n\n // Set non-path related properties.\n for (prop in options) {\n // @ts-expect-error: fine to set other things.\n if (!order.includes(prop)) this[prop] = options[prop]\n }\n }\n\n /**\n * Access full path (`~/index.min.js`).\n *\n * @returns {string}\n */\n get path() {\n return this.history[this.history.length - 1]\n }\n\n /**\n * Set full path (`~/index.min.js`).\n * Cannot be nullified.\n *\n * @param {string|URL} path\n */\n set path(path) {\n if (isUrl(path)) {\n path = urlToPath(path)\n }\n\n assertNonEmpty(path, 'path')\n\n if (this.path !== path) {\n this.history.push(path)\n }\n }\n\n /**\n * Access parent path (`~`).\n */\n get dirname() {\n return typeof this.path === 'string' ? path.dirname(this.path) : undefined\n }\n\n /**\n * Set parent path (`~`).\n * Cannot be set if there's no `path` yet.\n */\n set dirname(dirname) {\n assertPath(this.basename, 'dirname')\n this.path = path.join(dirname || '', this.basename)\n }\n\n /**\n * Access basename (including extname) (`index.min.js`).\n */\n get basename() {\n return typeof this.path === 'string' ? path.basename(this.path) : undefined\n }\n\n /**\n * Set basename (`index.min.js`).\n * Cannot contain path separators.\n * Cannot be nullified either (use `file.path = file.dirname` instead).\n */\n set basename(basename) {\n assertNonEmpty(basename, 'basename')\n assertPart(basename, 'basename')\n this.path = path.join(this.dirname || '', basename)\n }\n\n /**\n * Access extname (including dot) (`.js`).\n */\n get extname() {\n return typeof this.path === 'string' ? path.extname(this.path) : undefined\n }\n\n /**\n * Set extname (including dot) (`.js`).\n * Cannot be set if there's no `path` yet and cannot contain path separators.\n */\n set extname(extname) {\n assertPart(extname, 'extname')\n assertPath(this.dirname, 'extname')\n\n if (extname) {\n if (extname.charCodeAt(0) !== 46 /* `.` */) {\n throw new Error('`extname` must start with `.`')\n }\n\n if (extname.includes('.', 1)) {\n throw new Error('`extname` cannot contain multiple dots')\n }\n }\n\n this.path = path.join(this.dirname, this.stem + (extname || ''))\n }\n\n /**\n * Access stem (w/o extname) (`index.min`).\n */\n get stem() {\n return typeof this.path === 'string'\n ? path.basename(this.path, this.extname)\n : undefined\n }\n\n /**\n * Set stem (w/o extname) (`index.min`).\n * Cannot be nullified, and cannot contain path separators.\n */\n set stem(stem) {\n assertNonEmpty(stem, 'stem')\n assertPart(stem, 'stem')\n this.path = path.join(this.dirname || '', stem + (this.extname || ''))\n }\n\n /**\n * Serialize the file.\n *\n * @param {BufferEncoding} [encoding='utf8'] If `file.value` is a buffer, `encoding` is used to serialize buffers.\n * @returns {string}\n */\n toString(encoding) {\n return (this.value || '').toString(encoding)\n }\n\n /**\n * Create a message and associates it w/ the file.\n *\n * @param {string|Error} reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given.\n * @param {Node|NodeLike|Position|Point} [place] Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional).\n * @param {string} [origin] Place in code the message originates from (`string`, optional).\n * @returns {VFileMessage}\n */\n message(reason, place, origin) {\n const message = new VFileMessage(reason, place, origin)\n\n if (this.path) {\n message.name = this.path + ':' + message.name\n message.file = this.path\n }\n\n message.fatal = false\n\n this.messages.push(message)\n\n return message\n }\n\n /**\n * Info: create a message, associate it with the file, and mark the fatality\n * as `null`.\n * Calls `message()` internally.\n *\n * @param {string|Error} reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given.\n * @param {Node|NodeLike|Position|Point} [place] Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional).\n * @param {string} [origin] Place in code the message originates from (`string`, optional).\n * @returns {VFileMessage}\n */\n info(reason, place, origin) {\n const message = this.message(reason, place, origin)\n\n message.fatal = null\n\n return message\n }\n\n /**\n * Fail: create a message, associate it with the file, mark the fatality as\n * `true`.\n * Note: fatal errors mean a file is no longer processable.\n * Calls `message()` internally.\n *\n * @param {string|Error} reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given.\n * @param {Node|NodeLike|Position|Point} [place] Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional).\n * @param {string} [origin] Place in code the message originates from (`string`, optional).\n * @returns {never}\n */\n fail(reason, place, origin) {\n const message = this.message(reason, place, origin)\n\n message.fatal = true\n\n throw message\n }\n}\n\n/**\n * Assert that `part` is not a path (as in, does not contain `path.sep`).\n *\n * @param {string|undefined} part\n * @param {string} name\n * @returns {void}\n */\nfunction assertPart(part, name) {\n if (part && part.includes(path.sep)) {\n throw new Error(\n '`' + name + '` cannot be a path: did not expect `' + path.sep + '`'\n )\n }\n}\n\n/**\n * Assert that `part` is not empty.\n *\n * @param {string|undefined} part\n * @param {string} name\n * @returns {asserts part is string}\n */\nfunction assertNonEmpty(part, name) {\n if (!part) {\n throw new Error('`' + name + '` cannot be empty')\n }\n}\n\n/**\n * Assert `path` exists.\n *\n * @param {string|undefined} path\n * @param {string} name\n * @returns {asserts path is string}\n */\nfunction assertPath(path, name) {\n if (!path) {\n throw new Error('Setting `' + name + '` requires `path` to be set too')\n }\n}\n","/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\nmodule.exports = function isBuffer (obj) {\n return obj != null && obj.constructor != null &&\n typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n","/**\n * Throw a given error.\n *\n * @param {Error|null|undefined} [error]\n * Maybe error.\n * @returns {asserts error is null|undefined}\n */\nexport function bail(error) {\n if (error) {\n throw error\n }\n}\n","'use strict';\n\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toStr = Object.prototype.toString;\nvar defineProperty = Object.defineProperty;\nvar gOPD = Object.getOwnPropertyDescriptor;\n\nvar isArray = function isArray(arr) {\n\tif (typeof Array.isArray === 'function') {\n\t\treturn Array.isArray(arr);\n\t}\n\n\treturn toStr.call(arr) === '[object Array]';\n};\n\nvar isPlainObject = function isPlainObject(obj) {\n\tif (!obj || toStr.call(obj) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tvar hasOwnConstructor = hasOwn.call(obj, 'constructor');\n\tvar hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {\n\t\treturn false;\n\t}\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor (key in obj) { /**/ }\n\n\treturn typeof key === 'undefined' || hasOwn.call(obj, key);\n};\n\n// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target\nvar setProperty = function setProperty(target, options) {\n\tif (defineProperty && options.name === '__proto__') {\n\t\tdefineProperty(target, options.name, {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\tvalue: options.newValue,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\ttarget[options.name] = options.newValue;\n\t}\n};\n\n// Return undefined instead of __proto__ if '__proto__' is not an own property\nvar getProperty = function getProperty(obj, name) {\n\tif (name === '__proto__') {\n\t\tif (!hasOwn.call(obj, name)) {\n\t\t\treturn void 0;\n\t\t} else if (gOPD) {\n\t\t\t// In early versions of node, obj['__proto__'] is buggy when obj has\n\t\t\t// __proto__ as an own property. Object.getOwnPropertyDescriptor() works.\n\t\t\treturn gOPD(obj, name).value;\n\t\t}\n\t}\n\n\treturn obj[name];\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone;\n\tvar target = arguments[0];\n\tvar i = 1;\n\tvar length = arguments.length;\n\tvar deep = false;\n\n\t// Handle a deep copy situation\n\tif (typeof target === 'boolean') {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\tif (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n\t\ttarget = {};\n\t}\n\n\tfor (; i < length; ++i) {\n\t\toptions = arguments[i];\n\t\t// Only deal with non-null/undefined values\n\t\tif (options != null) {\n\t\t\t// Extend the base object\n\t\t\tfor (name in options) {\n\t\t\t\tsrc = getProperty(target, name);\n\t\t\t\tcopy = getProperty(options, name);\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif (target !== copy) {\n\t\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\t\tif (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {\n\t\t\t\t\t\tif (copyIsArray) {\n\t\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\t\tclone = src && isArray(src) ? src : [];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: extend(deep, clone, copy) });\n\n\t\t\t\t\t// Don't bring in undefined values\n\t\t\t\t\t} else if (typeof copy !== 'undefined') {\n\t\t\t\t\t\tsetProperty(target, { name: name, newValue: copy });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n","export default function isPlainObject(value) {\n\tif (Object.prototype.toString.call(value) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || prototype === Object.prototype;\n}\n","/**\n * @typedef {(error?: Error|null|undefined, ...output: Array) => void} Callback\n * @typedef {(...input: Array) => any} Middleware\n *\n * @typedef {(...input: Array) => void} Run\n * Call all middleware.\n * @typedef {(fn: Middleware) => Pipeline} Use\n * Add `fn` (middleware) to the list.\n * @typedef {{run: Run, use: Use}} Pipeline\n * Middleware.\n */\n\n/**\n * Create new middleware.\n *\n * @returns {Pipeline}\n */\nexport function trough() {\n /** @type {Array} */\n const fns = []\n /** @type {Pipeline} */\n const pipeline = {run, use}\n\n return pipeline\n\n /** @type {Run} */\n function run(...values) {\n let middlewareIndex = -1\n /** @type {Callback} */\n const callback = values.pop()\n\n if (typeof callback !== 'function') {\n throw new TypeError('Expected function as last argument, not ' + callback)\n }\n\n next(null, ...values)\n\n /**\n * Run the next `fn`, or we’re done.\n *\n * @param {Error|null|undefined} error\n * @param {Array} output\n */\n function next(error, ...output) {\n const fn = fns[++middlewareIndex]\n let index = -1\n\n if (error) {\n callback(error)\n return\n }\n\n // Copy non-nullish input into values.\n while (++index < values.length) {\n if (output[index] === null || output[index] === undefined) {\n output[index] = values[index]\n }\n }\n\n // Save the newly created `output` for the next call.\n values = output\n\n // Next or done.\n if (fn) {\n wrap(fn, next)(...output)\n } else {\n callback(null, ...output)\n }\n }\n }\n\n /** @type {Use} */\n function use(middelware) {\n if (typeof middelware !== 'function') {\n throw new TypeError(\n 'Expected `middelware` to be a function, not ' + middelware\n )\n }\n\n fns.push(middelware)\n return pipeline\n }\n}\n\n/**\n * Wrap `middleware`.\n * Can be sync or async; return a promise, receive a callback, or return new\n * values and errors.\n *\n * @param {Middleware} middleware\n * @param {Callback} callback\n */\nexport function wrap(middleware, callback) {\n /** @type {boolean} */\n let called\n\n return wrapped\n\n /**\n * Call `middleware`.\n * @this {any}\n * @param {Array} parameters\n * @returns {void}\n */\n function wrapped(...parameters) {\n const fnExpectsCallback = middleware.length > parameters.length\n /** @type {any} */\n let result\n\n if (fnExpectsCallback) {\n parameters.push(done)\n }\n\n try {\n result = middleware.apply(this, parameters)\n } catch (error) {\n const exception = /** @type {Error} */ (error)\n\n // Well, this is quite the pickle.\n // `middleware` received a callback and called it synchronously, but that\n // threw an error.\n // The only thing left to do is to throw the thing instead.\n if (fnExpectsCallback && called) {\n throw exception\n }\n\n return done(exception)\n }\n\n if (!fnExpectsCallback) {\n if (result instanceof Promise) {\n result.then(then, done)\n } else if (result instanceof Error) {\n done(result)\n } else {\n then(result)\n }\n }\n }\n\n /**\n * Call `callback`, only once.\n * @type {Callback}\n */\n function done(error, ...output) {\n if (!called) {\n called = true\n callback(error, ...output)\n }\n }\n\n /**\n * Call `done` with one value.\n *\n * @param {any} [value]\n */\n function then(value) {\n done(null, value)\n }\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('vfile').VFileCompatible} VFileCompatible\n * @typedef {import('vfile').VFileValue} VFileValue\n * @typedef {import('..').Processor} Processor\n * @typedef {import('..').Plugin} Plugin\n * @typedef {import('..').Preset} Preset\n * @typedef {import('..').Pluggable} Pluggable\n * @typedef {import('..').PluggableList} PluggableList\n * @typedef {import('..').Transformer} Transformer\n * @typedef {import('..').Parser} Parser\n * @typedef {import('..').Compiler} Compiler\n * @typedef {import('..').RunCallback} RunCallback\n * @typedef {import('..').ProcessCallback} ProcessCallback\n *\n * @typedef Context\n * @property {Node} tree\n * @property {VFile} file\n */\n\nimport {bail} from 'bail'\nimport isBuffer from 'is-buffer'\nimport extend from 'extend'\nimport isPlainObj from 'is-plain-obj'\nimport {trough} from 'trough'\nimport {VFile} from 'vfile'\n\n// Expose a frozen processor.\nexport const unified = base().freeze()\n\nconst own = {}.hasOwnProperty\n\n// Function to create the first processor.\n/**\n * @returns {Processor}\n */\nfunction base() {\n const transformers = trough()\n /** @type {Processor['attachers']} */\n const attachers = []\n /** @type {Record} */\n let namespace = {}\n /** @type {boolean|undefined} */\n let frozen\n let freezeIndex = -1\n\n // Data management.\n // @ts-expect-error: overloads are handled.\n processor.data = data\n processor.Parser = undefined\n processor.Compiler = undefined\n\n // Lock.\n processor.freeze = freeze\n\n // Plugins.\n processor.attachers = attachers\n // @ts-expect-error: overloads are handled.\n processor.use = use\n\n // API.\n processor.parse = parse\n processor.stringify = stringify\n // @ts-expect-error: overloads are handled.\n processor.run = run\n processor.runSync = runSync\n // @ts-expect-error: overloads are handled.\n processor.process = process\n processor.processSync = processSync\n\n // Expose.\n return processor\n\n // Create a new processor based on the processor in the current scope.\n /** @type {Processor} */\n function processor() {\n const destination = base()\n let index = -1\n\n while (++index < attachers.length) {\n destination.use(...attachers[index])\n }\n\n destination.data(extend(true, {}, namespace))\n\n return destination\n }\n\n /**\n * @param {string|Record} [key]\n * @param {unknown} [value]\n * @returns {unknown}\n */\n function data(key, value) {\n if (typeof key === 'string') {\n // Set `key`.\n if (arguments.length === 2) {\n assertUnfrozen('data', frozen)\n namespace[key] = value\n return processor\n }\n\n // Get `key`.\n return (own.call(namespace, key) && namespace[key]) || null\n }\n\n // Set space.\n if (key) {\n assertUnfrozen('data', frozen)\n namespace = key\n return processor\n }\n\n // Get space.\n return namespace\n }\n\n /** @type {Processor['freeze']} */\n function freeze() {\n if (frozen) {\n return processor\n }\n\n while (++freezeIndex < attachers.length) {\n const [attacher, ...options] = attachers[freezeIndex]\n\n if (options[0] === false) {\n continue\n }\n\n if (options[0] === true) {\n options[0] = undefined\n }\n\n /** @type {Transformer|void} */\n const transformer = attacher.call(processor, ...options)\n\n if (typeof transformer === 'function') {\n transformers.use(transformer)\n }\n }\n\n frozen = true\n freezeIndex = Number.POSITIVE_INFINITY\n\n return processor\n }\n\n /**\n * @param {Pluggable|null|undefined} [value]\n * @param {...unknown} options\n * @returns {Processor}\n */\n function use(value, ...options) {\n /** @type {Record|undefined} */\n let settings\n\n assertUnfrozen('use', frozen)\n\n if (value === null || value === undefined) {\n // Empty.\n } else if (typeof value === 'function') {\n addPlugin(value, ...options)\n } else if (typeof value === 'object') {\n if (Array.isArray(value)) {\n addList(value)\n } else {\n addPreset(value)\n }\n } else {\n throw new TypeError('Expected usable value, not `' + value + '`')\n }\n\n if (settings) {\n namespace.settings = Object.assign(namespace.settings || {}, settings)\n }\n\n return processor\n\n /**\n * @param {import('..').Pluggable} value\n * @returns {void}\n */\n function add(value) {\n if (typeof value === 'function') {\n addPlugin(value)\n } else if (typeof value === 'object') {\n if (Array.isArray(value)) {\n const [plugin, ...options] = value\n addPlugin(plugin, ...options)\n } else {\n addPreset(value)\n }\n } else {\n throw new TypeError('Expected usable value, not `' + value + '`')\n }\n }\n\n /**\n * @param {Preset} result\n * @returns {void}\n */\n function addPreset(result) {\n addList(result.plugins)\n\n if (result.settings) {\n settings = Object.assign(settings || {}, result.settings)\n }\n }\n\n /**\n * @param {PluggableList|null|undefined} [plugins]\n * @returns {void}\n */\n function addList(plugins) {\n let index = -1\n\n if (plugins === null || plugins === undefined) {\n // Empty.\n } else if (Array.isArray(plugins)) {\n while (++index < plugins.length) {\n const thing = plugins[index]\n add(thing)\n }\n } else {\n throw new TypeError('Expected a list of plugins, not `' + plugins + '`')\n }\n }\n\n /**\n * @param {Plugin} plugin\n * @param {...unknown} [value]\n * @returns {void}\n */\n function addPlugin(plugin, value) {\n let index = -1\n /** @type {Processor['attachers'][number]|undefined} */\n let entry\n\n while (++index < attachers.length) {\n if (attachers[index][0] === plugin) {\n entry = attachers[index]\n break\n }\n }\n\n if (entry) {\n if (isPlainObj(entry[1]) && isPlainObj(value)) {\n value = extend(true, entry[1], value)\n }\n\n entry[1] = value\n } else {\n // @ts-expect-error: fine.\n attachers.push([...arguments])\n }\n }\n }\n\n /** @type {Processor['parse']} */\n function parse(doc) {\n processor.freeze()\n const file = vfile(doc)\n const Parser = processor.Parser\n assertParser('parse', Parser)\n\n if (newable(Parser, 'parse')) {\n // @ts-expect-error: `newable` checks this.\n return new Parser(String(file), file).parse()\n }\n\n // @ts-expect-error: `newable` checks this.\n return Parser(String(file), file) // eslint-disable-line new-cap\n }\n\n /** @type {Processor['stringify']} */\n function stringify(node, doc) {\n processor.freeze()\n const file = vfile(doc)\n const Compiler = processor.Compiler\n assertCompiler('stringify', Compiler)\n assertNode(node)\n\n if (newable(Compiler, 'compile')) {\n // @ts-expect-error: `newable` checks this.\n return new Compiler(node, file).compile()\n }\n\n // @ts-expect-error: `newable` checks this.\n return Compiler(node, file) // eslint-disable-line new-cap\n }\n\n /**\n * @param {Node} node\n * @param {VFileCompatible|RunCallback} [doc]\n * @param {RunCallback} [callback]\n * @returns {Promise|void}\n */\n function run(node, doc, callback) {\n assertNode(node)\n processor.freeze()\n\n if (!callback && typeof doc === 'function') {\n callback = doc\n doc = undefined\n }\n\n if (!callback) {\n return new Promise(executor)\n }\n\n executor(null, callback)\n\n /**\n * @param {null|((node: Node) => void)} resolve\n * @param {(error: Error) => void} reject\n * @returns {void}\n */\n function executor(resolve, reject) {\n // @ts-expect-error: `doc` can’t be a callback anymore, we checked.\n transformers.run(node, vfile(doc), done)\n\n /**\n * @param {Error|null} error\n * @param {Node} tree\n * @param {VFile} file\n * @returns {void}\n */\n function done(error, tree, file) {\n tree = tree || node\n if (error) {\n reject(error)\n } else if (resolve) {\n resolve(tree)\n } else {\n // @ts-expect-error: `callback` is defined if `resolve` is not.\n callback(null, tree, file)\n }\n }\n }\n }\n\n /** @type {Processor['runSync']} */\n function runSync(node, file) {\n /** @type {Node|undefined} */\n let result\n /** @type {boolean|undefined} */\n let complete\n\n processor.run(node, file, done)\n\n assertDone('runSync', 'run', complete)\n\n // @ts-expect-error: we either bailed on an error or have a tree.\n return result\n\n /**\n * @param {Error|null} [error]\n * @param {Node} [tree]\n * @returns {void}\n */\n function done(error, tree) {\n bail(error)\n result = tree\n complete = true\n }\n }\n\n /**\n * @param {VFileCompatible} doc\n * @param {ProcessCallback} [callback]\n * @returns {Promise|undefined}\n */\n function process(doc, callback) {\n processor.freeze()\n assertParser('process', processor.Parser)\n assertCompiler('process', processor.Compiler)\n\n if (!callback) {\n return new Promise(executor)\n }\n\n executor(null, callback)\n\n /**\n * @param {null|((file: VFile) => void)} resolve\n * @param {(error?: Error|null|undefined) => void} reject\n * @returns {void}\n */\n function executor(resolve, reject) {\n const file = vfile(doc)\n\n processor.run(processor.parse(file), file, (error, tree, file) => {\n if (error || !tree || !file) {\n done(error)\n } else {\n /** @type {unknown} */\n const result = processor.stringify(tree, file)\n\n if (result === undefined || result === null) {\n // Empty.\n } else if (looksLikeAVFileValue(result)) {\n file.value = result\n } else {\n file.result = result\n }\n\n done(error, file)\n }\n })\n\n /**\n * @param {Error|null|undefined} [error]\n * @param {VFile|undefined} [file]\n * @returns {void}\n */\n function done(error, file) {\n if (error || !file) {\n reject(error)\n } else if (resolve) {\n resolve(file)\n } else {\n // @ts-expect-error: `callback` is defined if `resolve` is not.\n callback(null, file)\n }\n }\n }\n }\n\n /** @type {Processor['processSync']} */\n function processSync(doc) {\n /** @type {boolean|undefined} */\n let complete\n\n processor.freeze()\n assertParser('processSync', processor.Parser)\n assertCompiler('processSync', processor.Compiler)\n\n const file = vfile(doc)\n\n processor.process(file, done)\n\n assertDone('processSync', 'process', complete)\n\n return file\n\n /**\n * @param {Error|null|undefined} [error]\n * @returns {void}\n */\n function done(error) {\n complete = true\n bail(error)\n }\n }\n}\n\n/**\n * Check if `value` is a constructor.\n *\n * @param {unknown} value\n * @param {string} name\n * @returns {boolean}\n */\nfunction newable(value, name) {\n return (\n typeof value === 'function' &&\n // Prototypes do exist.\n // type-coverage:ignore-next-line\n value.prototype &&\n // A function with keys in its prototype is probably a constructor.\n // Classes’ prototype methods are not enumerable, so we check if some value\n // exists in the prototype.\n // type-coverage:ignore-next-line\n (keys(value.prototype) || name in value.prototype)\n )\n}\n\n/**\n * Check if `value` is an object with keys.\n *\n * @param {Record} value\n * @returns {boolean}\n */\nfunction keys(value) {\n /** @type {string} */\n let key\n\n for (key in value) {\n if (own.call(value, key)) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Assert a parser is available.\n *\n * @param {string} name\n * @param {unknown} value\n * @returns {asserts value is Parser}\n */\nfunction assertParser(name, value) {\n if (typeof value !== 'function') {\n throw new TypeError('Cannot `' + name + '` without `Parser`')\n }\n}\n\n/**\n * Assert a compiler is available.\n *\n * @param {string} name\n * @param {unknown} value\n * @returns {asserts value is Compiler}\n */\nfunction assertCompiler(name, value) {\n if (typeof value !== 'function') {\n throw new TypeError('Cannot `' + name + '` without `Compiler`')\n }\n}\n\n/**\n * Assert the processor is not frozen.\n *\n * @param {string} name\n * @param {unknown} frozen\n * @returns {asserts frozen is false}\n */\nfunction assertUnfrozen(name, frozen) {\n if (frozen) {\n throw new Error(\n 'Cannot call `' +\n name +\n '` on a frozen processor.\\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.'\n )\n }\n}\n\n/**\n * Assert `node` is a unist node.\n *\n * @param {unknown} node\n * @returns {asserts node is Node}\n */\nfunction assertNode(node) {\n // `isPlainObj` unfortunately uses `any` instead of `unknown`.\n // type-coverage:ignore-next-line\n if (!isPlainObj(node) || typeof node.type !== 'string') {\n throw new TypeError('Expected node, got `' + node + '`')\n // Fine.\n }\n}\n\n/**\n * Assert that `complete` is `true`.\n *\n * @param {string} name\n * @param {string} asyncName\n * @param {unknown} complete\n * @returns {asserts complete is true}\n */\nfunction assertDone(name, asyncName, complete) {\n if (!complete) {\n throw new Error(\n '`' + name + '` finished async. Use `' + asyncName + '` instead'\n )\n }\n}\n\n/**\n * @param {VFileCompatible} [value]\n * @returns {VFile}\n */\nfunction vfile(value) {\n return looksLikeAVFile(value) ? value : new VFile(value)\n}\n\n/**\n * @param {VFileCompatible} [value]\n * @returns {value is VFile}\n */\nfunction looksLikeAVFile(value) {\n return Boolean(\n value &&\n typeof value === 'object' &&\n 'message' in value &&\n 'messages' in value\n )\n}\n\n/**\n * @param {unknown} [value]\n * @returns {value is VFileValue}\n */\nfunction looksLikeAVFileValue(value) {\n return typeof value === 'string' || isBuffer(value)\n}\n","/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\nmodule.exports = function isBuffer (obj) {\n return obj != null && obj.constructor != null &&\n typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n","/**\n * @typedef Options\n * @property {boolean} [includeImageAlt=true]\n */\n\n/**\n * Get the text content of a node.\n * Prefer the node’s plain-text fields, otherwise serialize its children,\n * and if the given value is an array, serialize the nodes in it.\n *\n * @param {unknown} node\n * @param {Options} [options]\n * @returns {string}\n */\nexport function toString(node, options) {\n var {includeImageAlt = true} = options || {}\n return one(node, includeImageAlt)\n}\n\n/**\n * @param {unknown} node\n * @param {boolean} includeImageAlt\n * @returns {string}\n */\nfunction one(node, includeImageAlt) {\n return (\n (node &&\n typeof node === 'object' &&\n // @ts-ignore looks like a literal.\n (node.value ||\n // @ts-ignore looks like an image.\n (includeImageAlt ? node.alt : '') ||\n // @ts-ignore looks like a parent.\n ('children' in node && all(node.children, includeImageAlt)) ||\n (Array.isArray(node) && all(node, includeImageAlt)))) ||\n ''\n )\n}\n\n/**\n * @param {Array.} values\n * @param {boolean} includeImageAlt\n * @returns {string}\n */\nfunction all(values, includeImageAlt) {\n /** @type {Array.} */\n var result = []\n var index = -1\n\n while (++index < values.length) {\n result[index] = one(values[index], includeImageAlt)\n }\n\n return result.join('')\n}\n","/**\n * Like `Array#splice`, but smarter for giant arrays.\n *\n * `Array#splice` takes all items to be inserted as individual argument which\n * causes a stack overflow in V8 when trying to insert 100k items for instance.\n *\n * Otherwise, this does not return the removed items, and takes `items` as an\n * array instead of rest parameters.\n *\n * @template {unknown} T\n * @param {T[]} list\n * @param {number} start\n * @param {number} remove\n * @param {T[]} items\n * @returns {void}\n */\nexport function splice(list, start, remove, items) {\n const end = list.length\n let chunkStart = 0\n /** @type {unknown[]} */\n\n let parameters // Make start between zero and `end` (included).\n\n if (start < 0) {\n start = -start > end ? 0 : end + start\n } else {\n start = start > end ? end : start\n }\n\n remove = remove > 0 ? remove : 0 // No need to chunk the items if there’s only a couple (10k) items.\n\n if (items.length < 10000) {\n parameters = Array.from(items)\n parameters.unshift(start, remove) // @ts-expect-error Hush, it’s fine.\n ;[].splice.apply(list, parameters)\n } else {\n // Delete `remove` items starting from `start`\n if (remove) [].splice.apply(list, [start, remove]) // Insert the items in chunks to not cause stack overflows.\n\n while (chunkStart < items.length) {\n parameters = items.slice(chunkStart, chunkStart + 10000)\n parameters.unshift(start, 0) // @ts-expect-error Hush, it’s fine.\n ;[].splice.apply(list, parameters)\n chunkStart += 10000\n start += 10000\n }\n }\n}\n/**\n * Append `items` (an array) at the end of `list` (another array).\n * When `list` was empty, returns `items` instead.\n *\n * This prevents a potentially expensive operation when `list` is empty,\n * and adds items in batches to prevent V8 from hanging.\n *\n * @template {unknown} T\n * @param {T[]} list\n * @param {T[]} items\n * @returns {T[]}\n */\n\nexport function push(list, items) {\n if (list.length > 0) {\n splice(list, list.length, 0, items)\n return list\n }\n\n return items\n}\n","/**\n * @typedef {import('micromark-util-types').NormalizedExtension} NormalizedExtension\n * @typedef {import('micromark-util-types').Extension} Extension\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').HtmlExtension} HtmlExtension\n */\n\nimport {splice} from 'micromark-util-chunked'\n\nconst hasOwnProperty = {}.hasOwnProperty\n\n/**\n * Combine several syntax extensions into one.\n *\n * @param {Extension[]} extensions List of syntax extensions.\n * @returns {NormalizedExtension} A single combined extension.\n */\nexport function combineExtensions(extensions) {\n /** @type {NormalizedExtension} */\n const all = {}\n let index = -1\n\n while (++index < extensions.length) {\n syntaxExtension(all, extensions[index])\n }\n\n return all\n}\n\n/**\n * Merge `extension` into `all`.\n *\n * @param {NormalizedExtension} all Extension to merge into.\n * @param {Extension} extension Extension to merge.\n * @returns {void}\n */\nfunction syntaxExtension(all, extension) {\n /** @type {string} */\n let hook\n\n for (hook in extension) {\n const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined\n const left = maybe || (all[hook] = {})\n const right = extension[hook]\n /** @type {string} */\n let code\n\n for (code in right) {\n if (!hasOwnProperty.call(left, code)) left[code] = []\n const value = right[code]\n constructs(\n // @ts-expect-error Looks like a list.\n left[code],\n Array.isArray(value) ? value : value ? [value] : []\n )\n }\n }\n}\n\n/**\n * Merge `list` into `existing` (both lists of constructs).\n * Mutates `existing`.\n *\n * @param {unknown[]} existing\n * @param {unknown[]} list\n * @returns {void}\n */\nfunction constructs(existing, list) {\n let index = -1\n /** @type {unknown[]} */\n const before = []\n\n while (++index < list.length) {\n // @ts-expect-error Looks like an object.\n ;(list[index].add === 'after' ? existing : before).push(list[index])\n }\n\n splice(existing, 0, 0, before)\n}\n\n/**\n * Combine several HTML extensions into one.\n *\n * @param {HtmlExtension[]} htmlExtensions List of HTML extensions.\n * @returns {HtmlExtension} A single combined extension.\n */\nexport function combineHtmlExtensions(htmlExtensions) {\n /** @type {HtmlExtension} */\n const handlers = {}\n let index = -1\n\n while (++index < htmlExtensions.length) {\n htmlExtension(handlers, htmlExtensions[index])\n }\n\n return handlers\n}\n\n/**\n * Merge `extension` into `all`.\n *\n * @param {HtmlExtension} all Extension to merge into.\n * @param {HtmlExtension} extension Extension to merge.\n * @returns {void}\n */\nfunction htmlExtension(all, extension) {\n /** @type {string} */\n let hook\n\n for (hook in extension) {\n const maybe = hasOwnProperty.call(all, hook) ? all[hook] : undefined\n const left = maybe || (all[hook] = {})\n const right = extension[hook]\n /** @type {string} */\n let type\n\n if (right) {\n for (type in right) {\n left[type] = right[type]\n }\n }\n }\n}\n","// This module is generated by `script/`.\n//\n// CommonMark handles attention (emphasis, strong) markers based on what comes\n// before or after them.\n// One such difference is if those characters are Unicode punctuation.\n// This script is generated from the Unicode data.\nexport const unicodePunctuationRegex =\n /[!-/:-@[-`{-~\\u00A1\\u00A7\\u00AB\\u00B6\\u00B7\\u00BB\\u00BF\\u037E\\u0387\\u055A-\\u055F\\u0589\\u058A\\u05BE\\u05C0\\u05C3\\u05C6\\u05F3\\u05F4\\u0609\\u060A\\u060C\\u060D\\u061B\\u061E\\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\\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\\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]/\n","/**\n * @typedef {import('micromark-util-types').Code} Code\n */\nimport {unicodePunctuationRegex} from './lib/unicode-punctuation-regex.js'\n/**\n * Check whether the character code represents an ASCII alpha (`a` through `z`,\n * case insensitive).\n *\n * An **ASCII alpha** is an ASCII upper alpha or ASCII lower alpha.\n *\n * An **ASCII upper alpha** is a character in the inclusive range U+0041 (`A`)\n * to U+005A (`Z`).\n *\n * An **ASCII lower alpha** is a character in the inclusive range U+0061 (`a`)\n * to U+007A (`z`).\n */\n\nexport const asciiAlpha = regexCheck(/[A-Za-z]/)\n/**\n * Check whether the character code represents an ASCII digit (`0` through `9`).\n *\n * An **ASCII digit** is a character in the inclusive range U+0030 (`0`) to\n * U+0039 (`9`).\n */\n\nexport const asciiDigit = regexCheck(/\\d/)\n/**\n * Check whether the character code represents an ASCII hex digit (`a` through\n * `f`, case insensitive, or `0` through `9`).\n *\n * An **ASCII hex digit** is an ASCII digit (see `asciiDigit`), ASCII upper hex\n * digit, or an ASCII lower hex digit.\n *\n * An **ASCII upper hex digit** is a character in the inclusive range U+0041\n * (`A`) to U+0046 (`F`).\n *\n * An **ASCII lower hex digit** is a character in the inclusive range U+0061\n * (`a`) to U+0066 (`f`).\n */\n\nexport const asciiHexDigit = regexCheck(/[\\dA-Fa-f]/)\n/**\n * Check whether the character code represents an ASCII alphanumeric (`a`\n * through `z`, case insensitive, or `0` through `9`).\n *\n * An **ASCII alphanumeric** is an ASCII digit (see `asciiDigit`) or ASCII alpha\n * (see `asciiAlpha`).\n */\n\nexport const asciiAlphanumeric = regexCheck(/[\\dA-Za-z]/)\n/**\n * Check whether the character code represents ASCII punctuation.\n *\n * An **ASCII punctuation** is a character in the inclusive ranges U+0021\n * EXCLAMATION MARK (`!`) to U+002F SLASH (`/`), U+003A COLON (`:`) to U+0040 AT\n * SIGN (`@`), U+005B LEFT SQUARE BRACKET (`[`) to U+0060 GRAVE ACCENT\n * (`` ` ``), or U+007B LEFT CURLY BRACE (`{`) to U+007E TILDE (`~`).\n */\n\nexport const asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/)\n/**\n * Check whether the character code represents an ASCII atext.\n *\n * atext is an ASCII alphanumeric (see `asciiAlphanumeric`), or a character in\n * the inclusive ranges U+0023 NUMBER SIGN (`#`) to U+0027 APOSTROPHE (`'`),\n * U+002A ASTERISK (`*`), U+002B PLUS SIGN (`+`), U+002D DASH (`-`), U+002F\n * SLASH (`/`), U+003D EQUALS TO (`=`), U+003F QUESTION MARK (`?`), U+005E\n * CARET (`^`) to U+0060 GRAVE ACCENT (`` ` ``), or U+007B LEFT CURLY BRACE\n * (`{`) to U+007E TILDE (`~`).\n *\n * See:\n * **\\[RFC5322]**:\n * [Internet Message Format](https://tools.ietf.org/html/rfc5322).\n * P. Resnick.\n * IETF.\n */\n\nexport const asciiAtext = regexCheck(/[#-'*+\\--9=?A-Z^-~]/)\n/**\n * Check whether a character code is an ASCII control character.\n *\n * An **ASCII control** is a character in the inclusive range U+0000 NULL (NUL)\n * to U+001F (US), or U+007F (DEL).\n *\n * @param {Code} code\n * @returns {code is number}\n */\n\nexport function asciiControl(code) {\n return (\n // Special whitespace codes (which have negative values), C0 and Control\n // character DEL\n code !== null && (code < 32 || code === 127)\n )\n}\n/**\n * Check whether a character code is a markdown line ending (see\n * `markdownLineEnding`) or markdown space (see `markdownSpace`).\n *\n * @param {Code} code\n * @returns {code is number}\n */\n\nexport function markdownLineEndingOrSpace(code) {\n return code !== null && (code < 0 || code === 32)\n}\n/**\n * Check whether a character code is a markdown line ending.\n *\n * A **markdown line ending** is the virtual characters M-0003 CARRIAGE RETURN\n * LINE FEED (CRLF), M-0004 LINE FEED (LF) and M-0005 CARRIAGE RETURN (CR).\n *\n * In micromark, the actual character U+000A LINE FEED (LF) and U+000D CARRIAGE\n * RETURN (CR) are replaced by these virtual characters depending on whether\n * they occurred together.\n *\n * @param {Code} code\n * @returns {code is number}\n */\n\nexport function markdownLineEnding(code) {\n return code !== null && code < -2\n}\n/**\n * Check whether a character code is a markdown space.\n *\n * A **markdown space** is the concrete character U+0020 SPACE (SP) and the\n * virtual characters M-0001 VIRTUAL SPACE (VS) and M-0002 HORIZONTAL TAB (HT).\n *\n * In micromark, the actual character U+0009 CHARACTER TABULATION (HT) is\n * replaced by one M-0002 HORIZONTAL TAB (HT) and between 0 and 3 M-0001 VIRTUAL\n * SPACE (VS) characters, depending on the column at which the tab occurred.\n *\n * @param {Code} code\n * @returns {code is number}\n */\n\nexport function markdownSpace(code) {\n return code === -2 || code === -1 || code === 32\n}\n/**\n * Check whether the character code represents Unicode whitespace.\n *\n * Note that this does handle micromark specific markdown whitespace characters.\n * See `markdownLineEndingOrSpace` to check that.\n *\n * A **Unicode whitespace** is a character in the Unicode `Zs` (Separator,\n * Space) category, or U+0009 CHARACTER TABULATION (HT), U+000A LINE FEED (LF),\n * U+000C (FF), or U+000D CARRIAGE RETURN (CR) (**\\[UNICODE]**).\n *\n * See:\n * **\\[UNICODE]**:\n * [The Unicode Standard](https://www.unicode.org/versions/).\n * Unicode Consortium.\n */\n\nexport const unicodeWhitespace = regexCheck(/\\s/)\n/**\n * Check whether the character code represents Unicode punctuation.\n *\n * A **Unicode punctuation** is a character in the Unicode `Pc` (Punctuation,\n * Connector), `Pd` (Punctuation, Dash), `Pe` (Punctuation, Close), `Pf`\n * (Punctuation, Final quote), `Pi` (Punctuation, Initial quote), `Po`\n * (Punctuation, Other), or `Ps` (Punctuation, Open) categories, or an ASCII\n * punctuation (see `asciiPunctuation`).\n *\n * See:\n * **\\[UNICODE]**:\n * [The Unicode Standard](https://www.unicode.org/versions/).\n * Unicode Consortium.\n */\n// Size note: removing ASCII from the regex and using `asciiPunctuation` here\n// In fact adds to the bundle size.\n\nexport const unicodePunctuation = regexCheck(unicodePunctuationRegex)\n/**\n * Create a code check from a regex.\n *\n * @param {RegExp} regex\n * @returns {(code: Code) => code is number}\n */\n\nfunction regexCheck(regex) {\n return check\n /**\n * Check whether a code matches the bound regex.\n *\n * @param {Code} code Character code\n * @returns {code is number} Whether the character code matches the bound regex\n */\n\n function check(code) {\n return code !== null && regex.test(String.fromCharCode(code))\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Effects} Effects\n * @typedef {import('micromark-util-types').State} State\n */\nimport {markdownSpace} from 'micromark-util-character'\n/**\n * @param {Effects} effects\n * @param {State} ok\n * @param {string} type\n * @param {number} [max=Infinity]\n * @returns {State}\n */\n\nexport function factorySpace(effects, ok, type, max) {\n const limit = max ? max - 1 : Number.POSITIVE_INFINITY\n let size = 0\n return start\n /** @type {State} */\n\n function start(code) {\n if (markdownSpace(code)) {\n effects.enter(type)\n return prefix(code)\n }\n\n return ok(code)\n }\n /** @type {State} */\n\n function prefix(code) {\n if (markdownSpace(code) && size++ < limit) {\n effects.consume(code)\n return prefix\n }\n\n effects.exit(type)\n return ok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct\n * @typedef {import('micromark-util-types').Initializer} Initializer\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').State} State\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownLineEnding} from 'micromark-util-character'\n\n/** @type {InitialConstruct} */\nexport const content = {\n tokenize: initializeContent\n}\n/** @type {Initializer} */\n\nfunction initializeContent(effects) {\n const contentStart = effects.attempt(\n this.parser.constructs.contentInitial,\n afterContentStartConstruct,\n paragraphInitial\n )\n /** @type {Token} */\n\n let previous\n return contentStart\n /** @type {State} */\n\n function afterContentStartConstruct(code) {\n if (code === null) {\n effects.consume(code)\n return\n }\n\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n return factorySpace(effects, contentStart, 'linePrefix')\n }\n /** @type {State} */\n\n function paragraphInitial(code) {\n effects.enter('paragraph')\n return lineStart(code)\n }\n /** @type {State} */\n\n function lineStart(code) {\n const token = effects.enter('chunkText', {\n contentType: 'text',\n previous\n })\n\n if (previous) {\n previous.next = token\n }\n\n previous = token\n return data(code)\n }\n /** @type {State} */\n\n function data(code) {\n if (code === null) {\n effects.exit('chunkText')\n effects.exit('paragraph')\n effects.consume(code)\n return\n }\n\n if (markdownLineEnding(code)) {\n effects.consume(code)\n effects.exit('chunkText')\n return lineStart\n } // Data.\n\n effects.consume(code)\n return data\n }\n}\n","/**\n * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct\n * @typedef {import('micromark-util-types').Initializer} Initializer\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Point} Point\n */\n\n/**\n * @typedef {Record} StackState\n * @typedef {[Construct, StackState]} StackItem\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownLineEnding} from 'micromark-util-character'\nimport {splice} from 'micromark-util-chunked'\n/** @type {InitialConstruct} */\n\nexport const document = {\n tokenize: initializeDocument\n}\n/** @type {Construct} */\n\nconst containerConstruct = {\n tokenize: tokenizeContainer\n}\n/** @type {Initializer} */\n\nfunction initializeDocument(effects) {\n const self = this\n /** @type {StackItem[]} */\n\n const stack = []\n let continued = 0\n /** @type {TokenizeContext|undefined} */\n\n let childFlow\n /** @type {Token|undefined} */\n\n let childToken\n /** @type {number} */\n\n let lineStartOffset\n return start\n /** @type {State} */\n\n function start(code) {\n // First we iterate through the open blocks, starting with the root\n // document, and descending through last children down to the last open\n // block.\n // Each block imposes a condition that the line must satisfy if the block is\n // to remain open.\n // For example, a block quote requires a `>` character.\n // A paragraph requires a non-blank line.\n // In this phase we may match all or just some of the open blocks.\n // But we cannot close unmatched blocks yet, because we may have a lazy\n // continuation line.\n if (continued < stack.length) {\n const item = stack[continued]\n self.containerState = item[1]\n return effects.attempt(\n item[0].continuation,\n documentContinue,\n checkNewContainers\n )(code)\n } // Done.\n\n return checkNewContainers(code)\n }\n /** @type {State} */\n\n function documentContinue(code) {\n continued++ // Note: this field is called `_closeFlow` but it also closes containers.\n // Perhaps a good idea to rename it but it’s already used in the wild by\n // extensions.\n\n if (self.containerState._closeFlow) {\n self.containerState._closeFlow = undefined\n\n if (childFlow) {\n closeFlow()\n } // Note: this algorithm for moving events around is similar to the\n // algorithm when dealing with lazy lines in `writeToChild`.\n\n const indexBeforeExits = self.events.length\n let indexBeforeFlow = indexBeforeExits\n /** @type {Point|undefined} */\n\n let point // Find the flow chunk.\n\n while (indexBeforeFlow--) {\n if (\n self.events[indexBeforeFlow][0] === 'exit' &&\n self.events[indexBeforeFlow][1].type === 'chunkFlow'\n ) {\n point = self.events[indexBeforeFlow][1].end\n break\n }\n }\n\n exitContainers(continued) // Fix positions.\n\n let index = indexBeforeExits\n\n while (index < self.events.length) {\n self.events[index][1].end = Object.assign({}, point)\n index++\n } // Inject the exits earlier (they’re still also at the end).\n\n splice(\n self.events,\n indexBeforeFlow + 1,\n 0,\n self.events.slice(indexBeforeExits)\n ) // Discard the duplicate exits.\n\n self.events.length = index\n return checkNewContainers(code)\n }\n\n return start(code)\n }\n /** @type {State} */\n\n function checkNewContainers(code) {\n // Next, after consuming the continuation markers for existing blocks, we\n // look for new block starts (e.g. `>` for a block quote).\n // If we encounter a new block start, we close any blocks unmatched in\n // step 1 before creating the new block as a child of the last matched\n // block.\n if (continued === stack.length) {\n // No need to `check` whether there’s a container, of `exitContainers`\n // would be moot.\n // We can instead immediately `attempt` to parse one.\n if (!childFlow) {\n return documentContinued(code)\n } // If we have concrete content, such as block HTML or fenced code,\n // we can’t have containers “pierce” into them, so we can immediately\n // start.\n\n if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) {\n return flowStart(code)\n } // If we do have flow, it could still be a blank line,\n // but we’d be interrupting it w/ a new container if there’s a current\n // construct.\n\n self.interrupt = Boolean(\n childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack\n )\n } // Check if there is a new container.\n\n self.containerState = {}\n return effects.check(\n containerConstruct,\n thereIsANewContainer,\n thereIsNoNewContainer\n )(code)\n }\n /** @type {State} */\n\n function thereIsANewContainer(code) {\n if (childFlow) closeFlow()\n exitContainers(continued)\n return documentContinued(code)\n }\n /** @type {State} */\n\n function thereIsNoNewContainer(code) {\n self.parser.lazy[self.now().line] = continued !== stack.length\n lineStartOffset = self.now().offset\n return flowStart(code)\n }\n /** @type {State} */\n\n function documentContinued(code) {\n // Try new containers.\n self.containerState = {}\n return effects.attempt(\n containerConstruct,\n containerContinue,\n flowStart\n )(code)\n }\n /** @type {State} */\n\n function containerContinue(code) {\n continued++\n stack.push([self.currentConstruct, self.containerState]) // Try another.\n\n return documentContinued(code)\n }\n /** @type {State} */\n\n function flowStart(code) {\n if (code === null) {\n if (childFlow) closeFlow()\n exitContainers(0)\n effects.consume(code)\n return\n }\n\n childFlow = childFlow || self.parser.flow(self.now())\n effects.enter('chunkFlow', {\n contentType: 'flow',\n previous: childToken,\n _tokenizer: childFlow\n })\n return flowContinue(code)\n }\n /** @type {State} */\n\n function flowContinue(code) {\n if (code === null) {\n writeToChild(effects.exit('chunkFlow'), true)\n exitContainers(0)\n effects.consume(code)\n return\n }\n\n if (markdownLineEnding(code)) {\n effects.consume(code)\n writeToChild(effects.exit('chunkFlow')) // Get ready for the next line.\n\n continued = 0\n self.interrupt = undefined\n return start\n }\n\n effects.consume(code)\n return flowContinue\n }\n /**\n * @param {Token} token\n * @param {boolean} [eof]\n * @returns {void}\n */\n\n function writeToChild(token, eof) {\n const stream = self.sliceStream(token)\n if (eof) stream.push(null)\n token.previous = childToken\n if (childToken) childToken.next = token\n childToken = token\n childFlow.defineSkip(token.start)\n childFlow.write(stream) // Alright, so we just added a lazy line:\n //\n // ```markdown\n // > a\n // b.\n //\n // Or:\n //\n // > ~~~c\n // d\n //\n // Or:\n //\n // > | e |\n // f\n // ```\n //\n // The construct in the second example (fenced code) does not accept lazy\n // lines, so it marked itself as done at the end of its first line, and\n // then the content construct parses `d`.\n // Most constructs in markdown match on the first line: if the first line\n // forms a construct, a non-lazy line can’t “unmake” it.\n //\n // The construct in the third example is potentially a GFM table, and\n // those are *weird*.\n // It *could* be a table, from the first line, if the following line\n // matches a condition.\n // In this case, that second line is lazy, which “unmakes” the first line\n // and turns the whole into one content block.\n //\n // We’ve now parsed the non-lazy and the lazy line, and can figure out\n // whether the lazy line started a new flow block.\n // If it did, we exit the current containers between the two flow blocks.\n\n if (self.parser.lazy[token.start.line]) {\n let index = childFlow.events.length\n\n while (index--) {\n if (\n // The token starts before the line ending…\n childFlow.events[index][1].start.offset < lineStartOffset && // …and either is not ended yet…\n (!childFlow.events[index][1].end || // …or ends after it.\n childFlow.events[index][1].end.offset > lineStartOffset)\n ) {\n // Exit: there’s still something open, which means it’s a lazy line\n // part of something.\n return\n }\n } // Note: this algorithm for moving events around is similar to the\n // algorithm when closing flow in `documentContinue`.\n\n const indexBeforeExits = self.events.length\n let indexBeforeFlow = indexBeforeExits\n /** @type {boolean|undefined} */\n\n let seen\n /** @type {Point|undefined} */\n\n let point // Find the previous chunk (the one before the lazy line).\n\n while (indexBeforeFlow--) {\n if (\n self.events[indexBeforeFlow][0] === 'exit' &&\n self.events[indexBeforeFlow][1].type === 'chunkFlow'\n ) {\n if (seen) {\n point = self.events[indexBeforeFlow][1].end\n break\n }\n\n seen = true\n }\n }\n\n exitContainers(continued) // Fix positions.\n\n index = indexBeforeExits\n\n while (index < self.events.length) {\n self.events[index][1].end = Object.assign({}, point)\n index++\n } // Inject the exits earlier (they’re still also at the end).\n\n splice(\n self.events,\n indexBeforeFlow + 1,\n 0,\n self.events.slice(indexBeforeExits)\n ) // Discard the duplicate exits.\n\n self.events.length = index\n }\n }\n /**\n * @param {number} size\n * @returns {void}\n */\n\n function exitContainers(size) {\n let index = stack.length // Exit open containers.\n\n while (index-- > size) {\n const entry = stack[index]\n self.containerState = entry[1]\n entry[0].exit.call(self, effects)\n }\n\n stack.length = size\n }\n\n function closeFlow() {\n childFlow.write([null])\n childToken = undefined\n childFlow = undefined\n self.containerState._closeFlow = undefined\n }\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeContainer(effects, ok, nok) {\n return factorySpace(\n effects,\n effects.attempt(this.parser.constructs.document, ok, nok),\n 'linePrefix',\n this.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4\n )\n}\n","/**\n * @typedef {import('micromark-util-types').Code} Code\n */\nimport {\n markdownLineEndingOrSpace,\n unicodePunctuation,\n unicodeWhitespace\n} from 'micromark-util-character'\n\n/**\n * Classify whether a character code represents whitespace, punctuation, or\n * something else.\n *\n * Used for attention (emphasis, strong), whose sequences can open or close\n * based on the class of surrounding characters.\n *\n * Note that eof (`null`) is seen as whitespace.\n *\n * @param {Code} code\n * @returns {number|undefined}\n */\nexport function classifyCharacter(code) {\n if (\n code === null ||\n markdownLineEndingOrSpace(code) ||\n unicodeWhitespace(code)\n ) {\n return 1\n }\n\n if (unicodePunctuation(code)) {\n return 2\n }\n}\n","/**\n * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext\n * @typedef {import('micromark-util-types').Event} Event\n * @typedef {import('micromark-util-types').Resolver} Resolver\n */\n\n/**\n * Call all `resolveAll`s.\n *\n * @param {{resolveAll?: Resolver}[]} constructs\n * @param {Event[]} events\n * @param {TokenizeContext} context\n * @returns {Event[]}\n */\nexport function resolveAll(constructs, events, context) {\n /** @type {Resolver[]} */\n const called = []\n let index = -1\n\n while (++index < constructs.length) {\n const resolve = constructs[index].resolveAll\n\n if (resolve && !called.includes(resolve)) {\n events = resolve(events, context)\n called.push(resolve)\n }\n }\n\n return events\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').Resolver} Resolver\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').Event} Event\n * @typedef {import('micromark-util-types').Code} Code\n * @typedef {import('micromark-util-types').Point} Point\n */\nimport {push, splice} from 'micromark-util-chunked'\nimport {classifyCharacter} from 'micromark-util-classify-character'\nimport {resolveAll} from 'micromark-util-resolve-all'\n\n/** @type {Construct} */\nexport const attention = {\n name: 'attention',\n tokenize: tokenizeAttention,\n resolveAll: resolveAllAttention\n}\n/**\n * Take all events and resolve attention to emphasis or strong.\n *\n * @type {Resolver}\n */\n\nfunction resolveAllAttention(events, context) {\n let index = -1\n /** @type {number} */\n\n let open\n /** @type {Token} */\n\n let group\n /** @type {Token} */\n\n let text\n /** @type {Token} */\n\n let openingSequence\n /** @type {Token} */\n\n let closingSequence\n /** @type {number} */\n\n let use\n /** @type {Event[]} */\n\n let nextEvents\n /** @type {number} */\n\n let offset // Walk through all events.\n //\n // Note: performance of this is fine on an mb of normal markdown, but it’s\n // a bottleneck for malicious stuff.\n\n while (++index < events.length) {\n // Find a token that can close.\n if (\n events[index][0] === 'enter' &&\n events[index][1].type === 'attentionSequence' &&\n events[index][1]._close\n ) {\n open = index // Now walk back to find an opener.\n\n while (open--) {\n // Find a token that can open the closer.\n if (\n events[open][0] === 'exit' &&\n events[open][1].type === 'attentionSequence' &&\n events[open][1]._open && // If the markers are the same:\n context.sliceSerialize(events[open][1]).charCodeAt(0) ===\n context.sliceSerialize(events[index][1]).charCodeAt(0)\n ) {\n // If the opening can close or the closing can open,\n // and the close size *is not* a multiple of three,\n // but the sum of the opening and closing size *is* multiple of three,\n // then don’t match.\n if (\n (events[open][1]._close || events[index][1]._open) &&\n (events[index][1].end.offset - events[index][1].start.offset) % 3 &&\n !(\n (events[open][1].end.offset -\n events[open][1].start.offset +\n events[index][1].end.offset -\n events[index][1].start.offset) %\n 3\n )\n ) {\n continue\n } // Number of markers to use from the sequence.\n\n use =\n events[open][1].end.offset - events[open][1].start.offset > 1 &&\n events[index][1].end.offset - events[index][1].start.offset > 1\n ? 2\n : 1\n const start = Object.assign({}, events[open][1].end)\n const end = Object.assign({}, events[index][1].start)\n movePoint(start, -use)\n movePoint(end, use)\n openingSequence = {\n type: use > 1 ? 'strongSequence' : 'emphasisSequence',\n start,\n end: Object.assign({}, events[open][1].end)\n }\n closingSequence = {\n type: use > 1 ? 'strongSequence' : 'emphasisSequence',\n start: Object.assign({}, events[index][1].start),\n end\n }\n text = {\n type: use > 1 ? 'strongText' : 'emphasisText',\n start: Object.assign({}, events[open][1].end),\n end: Object.assign({}, events[index][1].start)\n }\n group = {\n type: use > 1 ? 'strong' : 'emphasis',\n start: Object.assign({}, openingSequence.start),\n end: Object.assign({}, closingSequence.end)\n }\n events[open][1].end = Object.assign({}, openingSequence.start)\n events[index][1].start = Object.assign({}, closingSequence.end)\n nextEvents = [] // If there are more markers in the opening, add them before.\n\n if (events[open][1].end.offset - events[open][1].start.offset) {\n nextEvents = push(nextEvents, [\n ['enter', events[open][1], context],\n ['exit', events[open][1], context]\n ])\n } // Opening.\n\n nextEvents = push(nextEvents, [\n ['enter', group, context],\n ['enter', openingSequence, context],\n ['exit', openingSequence, context],\n ['enter', text, context]\n ]) // Between.\n\n nextEvents = push(\n nextEvents,\n resolveAll(\n context.parser.constructs.insideSpan.null,\n events.slice(open + 1, index),\n context\n )\n ) // Closing.\n\n nextEvents = push(nextEvents, [\n ['exit', text, context],\n ['enter', closingSequence, context],\n ['exit', closingSequence, context],\n ['exit', group, context]\n ]) // If there are more markers in the closing, add them after.\n\n if (events[index][1].end.offset - events[index][1].start.offset) {\n offset = 2\n nextEvents = push(nextEvents, [\n ['enter', events[index][1], context],\n ['exit', events[index][1], context]\n ])\n } else {\n offset = 0\n }\n\n splice(events, open - 1, index - open + 3, nextEvents)\n index = open + nextEvents.length - offset - 2\n break\n }\n }\n }\n } // Remove remaining sequences.\n\n index = -1\n\n while (++index < events.length) {\n if (events[index][1].type === 'attentionSequence') {\n events[index][1].type = 'data'\n }\n }\n\n return events\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeAttention(effects, ok) {\n const attentionMarkers = this.parser.constructs.attentionMarkers.null\n const previous = this.previous\n const before = classifyCharacter(previous)\n /** @type {NonNullable} */\n\n let marker\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('attentionSequence')\n marker = code\n return sequence(code)\n }\n /** @type {State} */\n\n function sequence(code) {\n if (code === marker) {\n effects.consume(code)\n return sequence\n }\n\n const token = effects.exit('attentionSequence')\n const after = classifyCharacter(code)\n const open =\n !after || (after === 2 && before) || attentionMarkers.includes(code)\n const close =\n !before || (before === 2 && after) || attentionMarkers.includes(previous)\n token._open = Boolean(marker === 42 ? open : open && (before || !close))\n token._close = Boolean(marker === 42 ? close : close && (after || !open))\n return ok(code)\n }\n}\n/**\n * Move a point a bit.\n *\n * Note: `move` only works inside lines! It’s not possible to move past other\n * chunks (replacement characters, tabs, or line endings).\n *\n * @param {Point} point\n * @param {number} offset\n * @returns {void}\n */\n\nfunction movePoint(point, offset) {\n point.column += offset\n point.offset += offset\n point._bufferIndex += offset\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n */\nimport {\n asciiAlpha,\n asciiAlphanumeric,\n asciiAtext,\n asciiControl\n} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const autolink = {\n name: 'autolink',\n tokenize: tokenizeAutolink\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeAutolink(effects, ok, nok) {\n let size = 1\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('autolink')\n effects.enter('autolinkMarker')\n effects.consume(code)\n effects.exit('autolinkMarker')\n effects.enter('autolinkProtocol')\n return open\n }\n /** @type {State} */\n\n function open(code) {\n if (asciiAlpha(code)) {\n effects.consume(code)\n return schemeOrEmailAtext\n }\n\n return asciiAtext(code) ? emailAtext(code) : nok(code)\n }\n /** @type {State} */\n\n function schemeOrEmailAtext(code) {\n return code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)\n ? schemeInsideOrEmailAtext(code)\n : emailAtext(code)\n }\n /** @type {State} */\n\n function schemeInsideOrEmailAtext(code) {\n if (code === 58) {\n effects.consume(code)\n return urlInside\n }\n\n if (\n (code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) &&\n size++ < 32\n ) {\n effects.consume(code)\n return schemeInsideOrEmailAtext\n }\n\n return emailAtext(code)\n }\n /** @type {State} */\n\n function urlInside(code) {\n if (code === 62) {\n effects.exit('autolinkProtocol')\n return end(code)\n }\n\n if (code === null || code === 32 || code === 60 || asciiControl(code)) {\n return nok(code)\n }\n\n effects.consume(code)\n return urlInside\n }\n /** @type {State} */\n\n function emailAtext(code) {\n if (code === 64) {\n effects.consume(code)\n size = 0\n return emailAtSignOrDot\n }\n\n if (asciiAtext(code)) {\n effects.consume(code)\n return emailAtext\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function emailAtSignOrDot(code) {\n return asciiAlphanumeric(code) ? emailLabel(code) : nok(code)\n }\n /** @type {State} */\n\n function emailLabel(code) {\n if (code === 46) {\n effects.consume(code)\n size = 0\n return emailAtSignOrDot\n }\n\n if (code === 62) {\n // Exit, then change the type.\n effects.exit('autolinkProtocol').type = 'autolinkEmail'\n return end(code)\n }\n\n return emailValue(code)\n }\n /** @type {State} */\n\n function emailValue(code) {\n if ((code === 45 || asciiAlphanumeric(code)) && size++ < 63) {\n effects.consume(code)\n return code === 45 ? emailValue : emailLabel\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function end(code) {\n effects.enter('autolinkMarker')\n effects.consume(code)\n effects.exit('autolinkMarker')\n effects.exit('autolink')\n return ok\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownLineEnding} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const blankLine = {\n tokenize: tokenizeBlankLine,\n partial: true\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeBlankLine(effects, ok, nok) {\n return factorySpace(effects, afterWhitespace, 'linePrefix')\n /** @type {State} */\n\n function afterWhitespace(code) {\n return code === null || markdownLineEnding(code) ? ok(code) : nok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').Exiter} Exiter\n * @typedef {import('micromark-util-types').State} State\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownSpace} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const blockQuote = {\n name: 'blockQuote',\n tokenize: tokenizeBlockQuoteStart,\n continuation: {\n tokenize: tokenizeBlockQuoteContinuation\n },\n exit\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeBlockQuoteStart(effects, ok, nok) {\n const self = this\n return start\n /** @type {State} */\n\n function start(code) {\n if (code === 62) {\n const state = self.containerState\n\n if (!state.open) {\n effects.enter('blockQuote', {\n _container: true\n })\n state.open = true\n }\n\n effects.enter('blockQuotePrefix')\n effects.enter('blockQuoteMarker')\n effects.consume(code)\n effects.exit('blockQuoteMarker')\n return after\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function after(code) {\n if (markdownSpace(code)) {\n effects.enter('blockQuotePrefixWhitespace')\n effects.consume(code)\n effects.exit('blockQuotePrefixWhitespace')\n effects.exit('blockQuotePrefix')\n return ok\n }\n\n effects.exit('blockQuotePrefix')\n return ok(code)\n }\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeBlockQuoteContinuation(effects, ok, nok) {\n return factorySpace(\n effects,\n effects.attempt(blockQuote, ok, nok),\n 'linePrefix',\n this.parser.constructs.disable.null.includes('codeIndented') ? undefined : 4\n )\n}\n/** @type {Exiter} */\n\nfunction exit(effects) {\n effects.exit('blockQuote')\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n */\nimport {asciiPunctuation} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const characterEscape = {\n name: 'characterEscape',\n tokenize: tokenizeCharacterEscape\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeCharacterEscape(effects, ok, nok) {\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('characterEscape')\n effects.enter('escapeMarker')\n effects.consume(code)\n effects.exit('escapeMarker')\n return open\n }\n /** @type {State} */\n\n function open(code) {\n if (asciiPunctuation(code)) {\n effects.enter('characterEscapeValue')\n effects.consume(code)\n effects.exit('characterEscapeValue')\n effects.exit('characterEscape')\n return ok\n }\n\n return nok(code)\n }\n}\n","/// \n\n/* eslint-env browser */\n\nconst element = document.createElement('i')\n\n/**\n * @param {string} value\n * @returns {string|false}\n */\nexport function decodeNamedCharacterReference(value) {\n const characterReference = '&' + value + ';'\n element.innerHTML = characterReference\n const char = element.textContent\n\n // Some named character references do not require the closing semicolon\n // (`¬`, for instance), which leads to situations where parsing the assumed\n // named reference of `¬it;` will result in the string `¬it;`.\n // When we encounter a trailing semicolon after parsing, and the character\n // reference to decode was not a semicolon (`;`), we can assume that the\n // matching was not complete.\n // @ts-expect-error: TypeScript is wrong that `textContent` on elements can\n // yield `null`.\n if (char.charCodeAt(char.length - 1) === 59 /* `;` */ && value !== 'semi') {\n return false\n }\n\n // If the decoded string is equal to the input, the character reference was\n // not valid.\n // @ts-expect-error: TypeScript is wrong that `textContent` on elements can\n // yield `null`.\n return char === characterReference ? false : char\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Code} Code\n */\nimport {decodeNamedCharacterReference} from 'decode-named-character-reference'\nimport {\n asciiAlphanumeric,\n asciiDigit,\n asciiHexDigit\n} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const characterReference = {\n name: 'characterReference',\n tokenize: tokenizeCharacterReference\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeCharacterReference(effects, ok, nok) {\n const self = this\n let size = 0\n /** @type {number} */\n\n let max\n /** @type {(code: Code) => code is number} */\n\n let test\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('characterReference')\n effects.enter('characterReferenceMarker')\n effects.consume(code)\n effects.exit('characterReferenceMarker')\n return open\n }\n /** @type {State} */\n\n function open(code) {\n if (code === 35) {\n effects.enter('characterReferenceMarkerNumeric')\n effects.consume(code)\n effects.exit('characterReferenceMarkerNumeric')\n return numeric\n }\n\n effects.enter('characterReferenceValue')\n max = 31\n test = asciiAlphanumeric\n return value(code)\n }\n /** @type {State} */\n\n function numeric(code) {\n if (code === 88 || code === 120) {\n effects.enter('characterReferenceMarkerHexadecimal')\n effects.consume(code)\n effects.exit('characterReferenceMarkerHexadecimal')\n effects.enter('characterReferenceValue')\n max = 6\n test = asciiHexDigit\n return value\n }\n\n effects.enter('characterReferenceValue')\n max = 7\n test = asciiDigit\n return value(code)\n }\n /** @type {State} */\n\n function value(code) {\n /** @type {Token} */\n let token\n\n if (code === 59 && size) {\n token = effects.exit('characterReferenceValue')\n\n if (\n test === asciiAlphanumeric &&\n !decodeNamedCharacterReference(self.sliceSerialize(token))\n ) {\n return nok(code)\n }\n\n effects.enter('characterReferenceMarker')\n effects.consume(code)\n effects.exit('characterReferenceMarker')\n effects.exit('characterReference')\n return ok\n }\n\n if (test(code) && size++ < max) {\n effects.consume(code)\n return value\n }\n\n return nok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Code} Code\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {\n markdownLineEnding,\n markdownLineEndingOrSpace\n} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const codeFenced = {\n name: 'codeFenced',\n tokenize: tokenizeCodeFenced,\n concrete: true\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeCodeFenced(effects, ok, nok) {\n const self = this\n /** @type {Construct} */\n\n const closingFenceConstruct = {\n tokenize: tokenizeClosingFence,\n partial: true\n }\n /** @type {Construct} */\n\n const nonLazyLine = {\n tokenize: tokenizeNonLazyLine,\n partial: true\n }\n const tail = this.events[this.events.length - 1]\n const initialPrefix =\n tail && tail[1].type === 'linePrefix'\n ? tail[2].sliceSerialize(tail[1], true).length\n : 0\n let sizeOpen = 0\n /** @type {NonNullable} */\n\n let marker\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('codeFenced')\n effects.enter('codeFencedFence')\n effects.enter('codeFencedFenceSequence')\n marker = code\n return sequenceOpen(code)\n }\n /** @type {State} */\n\n function sequenceOpen(code) {\n if (code === marker) {\n effects.consume(code)\n sizeOpen++\n return sequenceOpen\n }\n\n effects.exit('codeFencedFenceSequence')\n return sizeOpen < 3\n ? nok(code)\n : factorySpace(effects, infoOpen, 'whitespace')(code)\n }\n /** @type {State} */\n\n function infoOpen(code) {\n if (code === null || markdownLineEnding(code)) {\n return openAfter(code)\n }\n\n effects.enter('codeFencedFenceInfo')\n effects.enter('chunkString', {\n contentType: 'string'\n })\n return info(code)\n }\n /** @type {State} */\n\n function info(code) {\n if (code === null || markdownLineEndingOrSpace(code)) {\n effects.exit('chunkString')\n effects.exit('codeFencedFenceInfo')\n return factorySpace(effects, infoAfter, 'whitespace')(code)\n }\n\n if (code === 96 && code === marker) return nok(code)\n effects.consume(code)\n return info\n }\n /** @type {State} */\n\n function infoAfter(code) {\n if (code === null || markdownLineEnding(code)) {\n return openAfter(code)\n }\n\n effects.enter('codeFencedFenceMeta')\n effects.enter('chunkString', {\n contentType: 'string'\n })\n return meta(code)\n }\n /** @type {State} */\n\n function meta(code) {\n if (code === null || markdownLineEnding(code)) {\n effects.exit('chunkString')\n effects.exit('codeFencedFenceMeta')\n return openAfter(code)\n }\n\n if (code === 96 && code === marker) return nok(code)\n effects.consume(code)\n return meta\n }\n /** @type {State} */\n\n function openAfter(code) {\n effects.exit('codeFencedFence')\n return self.interrupt ? ok(code) : contentStart(code)\n }\n /** @type {State} */\n\n function contentStart(code) {\n if (code === null) {\n return after(code)\n }\n\n if (markdownLineEnding(code)) {\n return effects.attempt(\n nonLazyLine,\n effects.attempt(\n closingFenceConstruct,\n after,\n initialPrefix\n ? factorySpace(\n effects,\n contentStart,\n 'linePrefix',\n initialPrefix + 1\n )\n : contentStart\n ),\n after\n )(code)\n }\n\n effects.enter('codeFlowValue')\n return contentContinue(code)\n }\n /** @type {State} */\n\n function contentContinue(code) {\n if (code === null || markdownLineEnding(code)) {\n effects.exit('codeFlowValue')\n return contentStart(code)\n }\n\n effects.consume(code)\n return contentContinue\n }\n /** @type {State} */\n\n function after(code) {\n effects.exit('codeFenced')\n return ok(code)\n }\n /** @type {Tokenizer} */\n\n function tokenizeNonLazyLine(effects, ok, nok) {\n const self = this\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n return lineStart\n }\n /** @type {State} */\n\n function lineStart(code) {\n return self.parser.lazy[self.now().line] ? nok(code) : ok(code)\n }\n }\n /** @type {Tokenizer} */\n\n function tokenizeClosingFence(effects, ok, nok) {\n let size = 0\n return factorySpace(\n effects,\n closingSequenceStart,\n 'linePrefix',\n this.parser.constructs.disable.null.includes('codeIndented')\n ? undefined\n : 4\n )\n /** @type {State} */\n\n function closingSequenceStart(code) {\n effects.enter('codeFencedFence')\n effects.enter('codeFencedFenceSequence')\n return closingSequence(code)\n }\n /** @type {State} */\n\n function closingSequence(code) {\n if (code === marker) {\n effects.consume(code)\n size++\n return closingSequence\n }\n\n if (size < sizeOpen) return nok(code)\n effects.exit('codeFencedFenceSequence')\n return factorySpace(effects, closingSequenceEnd, 'whitespace')(code)\n }\n /** @type {State} */\n\n function closingSequenceEnd(code) {\n if (code === null || markdownLineEnding(code)) {\n effects.exit('codeFencedFence')\n return ok(code)\n }\n\n return nok(code)\n }\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').Resolver} Resolver\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').State} State\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownLineEnding} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const codeIndented = {\n name: 'codeIndented',\n tokenize: tokenizeCodeIndented\n}\n/** @type {Construct} */\n\nconst indentedContent = {\n tokenize: tokenizeIndentedContent,\n partial: true\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeCodeIndented(effects, ok, nok) {\n const self = this\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('codeIndented')\n return factorySpace(effects, afterStartPrefix, 'linePrefix', 4 + 1)(code)\n }\n /** @type {State} */\n\n function afterStartPrefix(code) {\n const tail = self.events[self.events.length - 1]\n return tail &&\n tail[1].type === 'linePrefix' &&\n tail[2].sliceSerialize(tail[1], true).length >= 4\n ? afterPrefix(code)\n : nok(code)\n }\n /** @type {State} */\n\n function afterPrefix(code) {\n if (code === null) {\n return after(code)\n }\n\n if (markdownLineEnding(code)) {\n return effects.attempt(indentedContent, afterPrefix, after)(code)\n }\n\n effects.enter('codeFlowValue')\n return content(code)\n }\n /** @type {State} */\n\n function content(code) {\n if (code === null || markdownLineEnding(code)) {\n effects.exit('codeFlowValue')\n return afterPrefix(code)\n }\n\n effects.consume(code)\n return content\n }\n /** @type {State} */\n\n function after(code) {\n effects.exit('codeIndented')\n return ok(code)\n }\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeIndentedContent(effects, ok, nok) {\n const self = this\n return start\n /** @type {State} */\n\n function start(code) {\n // If this is a lazy line, it can’t be code.\n if (self.parser.lazy[self.now().line]) {\n return nok(code)\n }\n\n if (markdownLineEnding(code)) {\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n return start\n }\n\n return factorySpace(effects, afterPrefix, 'linePrefix', 4 + 1)(code)\n }\n /** @type {State} */\n\n function afterPrefix(code) {\n const tail = self.events[self.events.length - 1]\n return tail &&\n tail[1].type === 'linePrefix' &&\n tail[2].sliceSerialize(tail[1], true).length >= 4\n ? ok(code)\n : markdownLineEnding(code)\n ? start(code)\n : nok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Resolver} Resolver\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').Previous} Previous\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').State} State\n */\nimport {markdownLineEnding} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const codeText = {\n name: 'codeText',\n tokenize: tokenizeCodeText,\n resolve: resolveCodeText,\n previous\n}\n/** @type {Resolver} */\n\nfunction resolveCodeText(events) {\n let tailExitIndex = events.length - 4\n let headEnterIndex = 3\n /** @type {number} */\n\n let index\n /** @type {number|undefined} */\n\n let enter // If we start and end with an EOL or a space.\n\n if (\n (events[headEnterIndex][1].type === 'lineEnding' ||\n events[headEnterIndex][1].type === 'space') &&\n (events[tailExitIndex][1].type === 'lineEnding' ||\n events[tailExitIndex][1].type === 'space')\n ) {\n index = headEnterIndex // And we have data.\n\n while (++index < tailExitIndex) {\n if (events[index][1].type === 'codeTextData') {\n // Then we have padding.\n events[headEnterIndex][1].type = 'codeTextPadding'\n events[tailExitIndex][1].type = 'codeTextPadding'\n headEnterIndex += 2\n tailExitIndex -= 2\n break\n }\n }\n } // Merge adjacent spaces and data.\n\n index = headEnterIndex - 1\n tailExitIndex++\n\n while (++index <= tailExitIndex) {\n if (enter === undefined) {\n if (index !== tailExitIndex && events[index][1].type !== 'lineEnding') {\n enter = index\n }\n } else if (\n index === tailExitIndex ||\n events[index][1].type === 'lineEnding'\n ) {\n events[enter][1].type = 'codeTextData'\n\n if (index !== enter + 2) {\n events[enter][1].end = events[index - 1][1].end\n events.splice(enter + 2, index - enter - 2)\n tailExitIndex -= index - enter - 2\n index = enter + 2\n }\n\n enter = undefined\n }\n }\n\n return events\n}\n/** @type {Previous} */\n\nfunction previous(code) {\n // If there is a previous code, there will always be a tail.\n return (\n code !== 96 ||\n this.events[this.events.length - 1][1].type === 'characterEscape'\n )\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeCodeText(effects, ok, nok) {\n const self = this\n let sizeOpen = 0\n /** @type {number} */\n\n let size\n /** @type {Token} */\n\n let token\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('codeText')\n effects.enter('codeTextSequence')\n return openingSequence(code)\n }\n /** @type {State} */\n\n function openingSequence(code) {\n if (code === 96) {\n effects.consume(code)\n sizeOpen++\n return openingSequence\n }\n\n effects.exit('codeTextSequence')\n return gap(code)\n }\n /** @type {State} */\n\n function gap(code) {\n // EOF.\n if (code === null) {\n return nok(code)\n } // Closing fence?\n // Could also be data.\n\n if (code === 96) {\n token = effects.enter('codeTextSequence')\n size = 0\n return closingSequence(code)\n } // Tabs don’t work, and virtual spaces don’t make sense.\n\n if (code === 32) {\n effects.enter('space')\n effects.consume(code)\n effects.exit('space')\n return gap\n }\n\n if (markdownLineEnding(code)) {\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n return gap\n } // Data.\n\n effects.enter('codeTextData')\n return data(code)\n } // In code.\n\n /** @type {State} */\n\n function data(code) {\n if (\n code === null ||\n code === 32 ||\n code === 96 ||\n markdownLineEnding(code)\n ) {\n effects.exit('codeTextData')\n return gap(code)\n }\n\n effects.consume(code)\n return data\n } // Closing fence.\n\n /** @type {State} */\n\n function closingSequence(code) {\n // More.\n if (code === 96) {\n effects.consume(code)\n size++\n return closingSequence\n } // Done!\n\n if (size === sizeOpen) {\n effects.exit('codeTextSequence')\n effects.exit('codeText')\n return ok(code)\n } // More or less accents: mark as data.\n\n token.type = 'codeTextData'\n return data(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').Chunk} Chunk\n * @typedef {import('micromark-util-types').Event} Event\n */\nimport {splice} from 'micromark-util-chunked'\n\n/**\n * Tokenize subcontent.\n *\n * @param {Event[]} events\n * @returns {boolean}\n */\nexport function subtokenize(events) {\n /** @type {Record} */\n const jumps = {}\n let index = -1\n /** @type {Event} */\n\n let event\n /** @type {number|undefined} */\n\n let lineIndex\n /** @type {number} */\n\n let otherIndex\n /** @type {Event} */\n\n let otherEvent\n /** @type {Event[]} */\n\n let parameters\n /** @type {Event[]} */\n\n let subevents\n /** @type {boolean|undefined} */\n\n let more\n\n while (++index < events.length) {\n while (index in jumps) {\n index = jumps[index]\n }\n\n event = events[index] // Add a hook for the GFM tasklist extension, which needs to know if text\n // is in the first content of a list item.\n\n if (\n index &&\n event[1].type === 'chunkFlow' &&\n events[index - 1][1].type === 'listItemPrefix'\n ) {\n subevents = event[1]._tokenizer.events\n otherIndex = 0\n\n if (\n otherIndex < subevents.length &&\n subevents[otherIndex][1].type === 'lineEndingBlank'\n ) {\n otherIndex += 2\n }\n\n if (\n otherIndex < subevents.length &&\n subevents[otherIndex][1].type === 'content'\n ) {\n while (++otherIndex < subevents.length) {\n if (subevents[otherIndex][1].type === 'content') {\n break\n }\n\n if (subevents[otherIndex][1].type === 'chunkText') {\n subevents[otherIndex][1]._isInFirstContentOfListItem = true\n otherIndex++\n }\n }\n }\n } // Enter.\n\n if (event[0] === 'enter') {\n if (event[1].contentType) {\n Object.assign(jumps, subcontent(events, index))\n index = jumps[index]\n more = true\n }\n } // Exit.\n else if (event[1]._container) {\n otherIndex = index\n lineIndex = undefined\n\n while (otherIndex--) {\n otherEvent = events[otherIndex]\n\n if (\n otherEvent[1].type === 'lineEnding' ||\n otherEvent[1].type === 'lineEndingBlank'\n ) {\n if (otherEvent[0] === 'enter') {\n if (lineIndex) {\n events[lineIndex][1].type = 'lineEndingBlank'\n }\n\n otherEvent[1].type = 'lineEnding'\n lineIndex = otherIndex\n }\n } else {\n break\n }\n }\n\n if (lineIndex) {\n // Fix position.\n event[1].end = Object.assign({}, events[lineIndex][1].start) // Switch container exit w/ line endings.\n\n parameters = events.slice(lineIndex, index)\n parameters.unshift(event)\n splice(events, lineIndex, index - lineIndex + 1, parameters)\n }\n }\n }\n\n return !more\n}\n/**\n * Tokenize embedded tokens.\n *\n * @param {Event[]} events\n * @param {number} eventIndex\n * @returns {Record}\n */\n\nfunction subcontent(events, eventIndex) {\n const token = events[eventIndex][1]\n const context = events[eventIndex][2]\n let startPosition = eventIndex - 1\n /** @type {number[]} */\n\n const startPositions = []\n const tokenizer =\n token._tokenizer || context.parser[token.contentType](token.start)\n const childEvents = tokenizer.events\n /** @type {[number, number][]} */\n\n const jumps = []\n /** @type {Record} */\n\n const gaps = {}\n /** @type {Chunk[]} */\n\n let stream\n /** @type {Token|undefined} */\n\n let previous\n let index = -1\n /** @type {Token|undefined} */\n\n let current = token\n let adjust = 0\n let start = 0\n const breaks = [start] // Loop forward through the linked tokens to pass them in order to the\n // subtokenizer.\n\n while (current) {\n // Find the position of the event for this token.\n while (events[++startPosition][1] !== current) {\n // Empty.\n }\n\n startPositions.push(startPosition)\n\n if (!current._tokenizer) {\n stream = context.sliceStream(current)\n\n if (!current.next) {\n stream.push(null)\n }\n\n if (previous) {\n tokenizer.defineSkip(current.start)\n }\n\n if (current._isInFirstContentOfListItem) {\n tokenizer._gfmTasklistFirstContentOfListItem = true\n }\n\n tokenizer.write(stream)\n\n if (current._isInFirstContentOfListItem) {\n tokenizer._gfmTasklistFirstContentOfListItem = undefined\n }\n } // Unravel the next token.\n\n previous = current\n current = current.next\n } // Now, loop back through all events (and linked tokens), to figure out which\n // parts belong where.\n\n current = token\n\n while (++index < childEvents.length) {\n if (\n // Find a void token that includes a break.\n childEvents[index][0] === 'exit' &&\n childEvents[index - 1][0] === 'enter' &&\n childEvents[index][1].type === childEvents[index - 1][1].type &&\n childEvents[index][1].start.line !== childEvents[index][1].end.line\n ) {\n start = index + 1\n breaks.push(start) // Help GC.\n\n current._tokenizer = undefined\n current.previous = undefined\n current = current.next\n }\n } // Help GC.\n\n tokenizer.events = [] // If there’s one more token (which is the cases for lines that end in an\n // EOF), that’s perfect: the last point we found starts it.\n // If there isn’t then make sure any remaining content is added to it.\n\n if (current) {\n // Help GC.\n current._tokenizer = undefined\n current.previous = undefined\n } else {\n breaks.pop()\n } // Now splice the events from the subtokenizer into the current events,\n // moving back to front so that splice indices aren’t affected.\n\n index = breaks.length\n\n while (index--) {\n const slice = childEvents.slice(breaks[index], breaks[index + 1])\n const start = startPositions.pop()\n jumps.unshift([start, start + slice.length - 1])\n splice(events, start, 2, slice)\n }\n\n index = -1\n\n while (++index < jumps.length) {\n gaps[adjust + jumps[index][0]] = adjust + jumps[index][1]\n adjust += jumps[index][1] - jumps[index][0] - 1\n }\n\n return gaps\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Resolver} Resolver\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').State} State\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownLineEnding} from 'micromark-util-character'\nimport {subtokenize} from 'micromark-util-subtokenize'\n\n/**\n * No name because it must not be turned off.\n * @type {Construct}\n */\nexport const content = {\n tokenize: tokenizeContent,\n resolve: resolveContent\n}\n/** @type {Construct} */\n\nconst continuationConstruct = {\n tokenize: tokenizeContinuation,\n partial: true\n}\n/**\n * Content is transparent: it’s parsed right now. That way, definitions are also\n * parsed right now: before text in paragraphs (specifically, media) are parsed.\n *\n * @type {Resolver}\n */\n\nfunction resolveContent(events) {\n subtokenize(events)\n return events\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeContent(effects, ok) {\n /** @type {Token} */\n let previous\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('content')\n previous = effects.enter('chunkContent', {\n contentType: 'content'\n })\n return data(code)\n }\n /** @type {State} */\n\n function data(code) {\n if (code === null) {\n return contentEnd(code)\n }\n\n if (markdownLineEnding(code)) {\n return effects.check(\n continuationConstruct,\n contentContinue,\n contentEnd\n )(code)\n } // Data.\n\n effects.consume(code)\n return data\n }\n /** @type {State} */\n\n function contentEnd(code) {\n effects.exit('chunkContent')\n effects.exit('content')\n return ok(code)\n }\n /** @type {State} */\n\n function contentContinue(code) {\n effects.consume(code)\n effects.exit('chunkContent')\n previous.next = effects.enter('chunkContent', {\n contentType: 'content',\n previous\n })\n previous = previous.next\n return data\n }\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeContinuation(effects, ok, nok) {\n const self = this\n return startLookahead\n /** @type {State} */\n\n function startLookahead(code) {\n effects.exit('chunkContent')\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n return factorySpace(effects, prefixed, 'linePrefix')\n }\n /** @type {State} */\n\n function prefixed(code) {\n if (code === null || markdownLineEnding(code)) {\n return nok(code)\n }\n\n const tail = self.events[self.events.length - 1]\n\n if (\n !self.parser.constructs.disable.null.includes('codeIndented') &&\n tail &&\n tail[1].type === 'linePrefix' &&\n tail[2].sliceSerialize(tail[1], true).length >= 4\n ) {\n return ok(code)\n }\n\n return effects.interrupt(self.parser.constructs.flow, nok, ok)(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Effects} Effects\n * @typedef {import('micromark-util-types').State} State\n */\nimport {\n asciiControl,\n markdownLineEndingOrSpace,\n markdownLineEnding\n} from 'micromark-util-character'\n\n/**\n * @param {Effects} effects\n * @param {State} ok\n * @param {State} nok\n * @param {string} type\n * @param {string} literalType\n * @param {string} literalMarkerType\n * @param {string} rawType\n * @param {string} stringType\n * @param {number} [max=Infinity]\n * @returns {State}\n */\n// eslint-disable-next-line max-params\nexport function factoryDestination(\n effects,\n ok,\n nok,\n type,\n literalType,\n literalMarkerType,\n rawType,\n stringType,\n max\n) {\n const limit = max || Number.POSITIVE_INFINITY\n let balance = 0\n return start\n /** @type {State} */\n\n function start(code) {\n if (code === 60) {\n effects.enter(type)\n effects.enter(literalType)\n effects.enter(literalMarkerType)\n effects.consume(code)\n effects.exit(literalMarkerType)\n return destinationEnclosedBefore\n }\n\n if (code === null || code === 41 || asciiControl(code)) {\n return nok(code)\n }\n\n effects.enter(type)\n effects.enter(rawType)\n effects.enter(stringType)\n effects.enter('chunkString', {\n contentType: 'string'\n })\n return destinationRaw(code)\n }\n /** @type {State} */\n\n function destinationEnclosedBefore(code) {\n if (code === 62) {\n effects.enter(literalMarkerType)\n effects.consume(code)\n effects.exit(literalMarkerType)\n effects.exit(literalType)\n effects.exit(type)\n return ok\n }\n\n effects.enter(stringType)\n effects.enter('chunkString', {\n contentType: 'string'\n })\n return destinationEnclosed(code)\n }\n /** @type {State} */\n\n function destinationEnclosed(code) {\n if (code === 62) {\n effects.exit('chunkString')\n effects.exit(stringType)\n return destinationEnclosedBefore(code)\n }\n\n if (code === null || code === 60 || markdownLineEnding(code)) {\n return nok(code)\n }\n\n effects.consume(code)\n return code === 92 ? destinationEnclosedEscape : destinationEnclosed\n }\n /** @type {State} */\n\n function destinationEnclosedEscape(code) {\n if (code === 60 || code === 62 || code === 92) {\n effects.consume(code)\n return destinationEnclosed\n }\n\n return destinationEnclosed(code)\n }\n /** @type {State} */\n\n function destinationRaw(code) {\n if (code === 40) {\n if (++balance > limit) return nok(code)\n effects.consume(code)\n return destinationRaw\n }\n\n if (code === 41) {\n if (!balance--) {\n effects.exit('chunkString')\n effects.exit(stringType)\n effects.exit(rawType)\n effects.exit(type)\n return ok(code)\n }\n\n effects.consume(code)\n return destinationRaw\n }\n\n if (code === null || markdownLineEndingOrSpace(code)) {\n if (balance) return nok(code)\n effects.exit('chunkString')\n effects.exit(stringType)\n effects.exit(rawType)\n effects.exit(type)\n return ok(code)\n }\n\n if (asciiControl(code)) return nok(code)\n effects.consume(code)\n return code === 92 ? destinationRawEscape : destinationRaw\n }\n /** @type {State} */\n\n function destinationRawEscape(code) {\n if (code === 40 || code === 41 || code === 92) {\n effects.consume(code)\n return destinationRaw\n }\n\n return destinationRaw(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Effects} Effects\n * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext\n * @typedef {import('micromark-util-types').State} State\n */\nimport {markdownLineEnding, markdownSpace} from 'micromark-util-character'\n\n/**\n * @this {TokenizeContext}\n * @param {Effects} effects\n * @param {State} ok\n * @param {State} nok\n * @param {string} type\n * @param {string} markerType\n * @param {string} stringType\n * @returns {State}\n */\n// eslint-disable-next-line max-params\nexport function factoryLabel(effects, ok, nok, type, markerType, stringType) {\n const self = this\n let size = 0\n /** @type {boolean} */\n\n let data\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter(type)\n effects.enter(markerType)\n effects.consume(code)\n effects.exit(markerType)\n effects.enter(stringType)\n return atBreak\n }\n /** @type {State} */\n\n function atBreak(code) {\n if (\n code === null ||\n code === 91 ||\n (code === 93 && !data) ||\n /* To do: remove in the future once we’ve switched from\n * `micromark-extension-footnote` to `micromark-extension-gfm-footnote`,\n * which doesn’t need this */\n\n /* Hidden footnotes hook */\n\n /* c8 ignore next 3 */\n (code === 94 &&\n !size &&\n '_hiddenFootnoteSupport' in self.parser.constructs) ||\n size > 999\n ) {\n return nok(code)\n }\n\n if (code === 93) {\n effects.exit(stringType)\n effects.enter(markerType)\n effects.consume(code)\n effects.exit(markerType)\n effects.exit(type)\n return ok\n }\n\n if (markdownLineEnding(code)) {\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n return atBreak\n }\n\n effects.enter('chunkString', {\n contentType: 'string'\n })\n return label(code)\n }\n /** @type {State} */\n\n function label(code) {\n if (\n code === null ||\n code === 91 ||\n code === 93 ||\n markdownLineEnding(code) ||\n size++ > 999\n ) {\n effects.exit('chunkString')\n return atBreak(code)\n }\n\n effects.consume(code)\n data = data || !markdownSpace(code)\n return code === 92 ? labelEscape : label\n }\n /** @type {State} */\n\n function labelEscape(code) {\n if (code === 91 || code === 92 || code === 93) {\n effects.consume(code)\n size++\n return label\n }\n\n return label(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Effects} Effects\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Code} Code\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownLineEnding} from 'micromark-util-character'\n\n/**\n * @param {Effects} effects\n * @param {State} ok\n * @param {State} nok\n * @param {string} type\n * @param {string} markerType\n * @param {string} stringType\n * @returns {State}\n */\n// eslint-disable-next-line max-params\nexport function factoryTitle(effects, ok, nok, type, markerType, stringType) {\n /** @type {NonNullable} */\n let marker\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter(type)\n effects.enter(markerType)\n effects.consume(code)\n effects.exit(markerType)\n marker = code === 40 ? 41 : code\n return atFirstTitleBreak\n }\n /** @type {State} */\n\n function atFirstTitleBreak(code) {\n if (code === marker) {\n effects.enter(markerType)\n effects.consume(code)\n effects.exit(markerType)\n effects.exit(type)\n return ok\n }\n\n effects.enter(stringType)\n return atTitleBreak(code)\n }\n /** @type {State} */\n\n function atTitleBreak(code) {\n if (code === marker) {\n effects.exit(stringType)\n return atFirstTitleBreak(marker)\n }\n\n if (code === null) {\n return nok(code)\n } // Note: blank lines can’t exist in content.\n\n if (markdownLineEnding(code)) {\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n return factorySpace(effects, atTitleBreak, 'linePrefix')\n }\n\n effects.enter('chunkString', {\n contentType: 'string'\n })\n return title(code)\n }\n /** @type {State} */\n\n function title(code) {\n if (code === marker || code === null || markdownLineEnding(code)) {\n effects.exit('chunkString')\n return atTitleBreak(code)\n }\n\n effects.consume(code)\n return code === 92 ? titleEscape : title\n }\n /** @type {State} */\n\n function titleEscape(code) {\n if (code === marker || code === 92) {\n effects.consume(code)\n return title\n }\n\n return title(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Effects} Effects\n * @typedef {import('micromark-util-types').State} State\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownLineEnding, markdownSpace} from 'micromark-util-character'\n\n/**\n * @param {Effects} effects\n * @param {State} ok\n */\nexport function factoryWhitespace(effects, ok) {\n /** @type {boolean} */\n let seen\n return start\n /** @type {State} */\n\n function start(code) {\n if (markdownLineEnding(code)) {\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n seen = true\n return start\n }\n\n if (markdownSpace(code)) {\n return factorySpace(\n effects,\n start,\n seen ? 'linePrefix' : 'lineSuffix'\n )(code)\n }\n\n return ok(code)\n }\n}\n","/**\n * Normalize an identifier (such as used in definitions).\n *\n * @param {string} value\n * @returns {string}\n */\nexport function normalizeIdentifier(value) {\n return (\n value // Collapse Markdown whitespace.\n .replace(/[\\t\\n\\r ]+/g, ' ') // Trim.\n .replace(/^ | $/g, '') // Some characters are considered “uppercase”, but if their lowercase\n // counterpart is uppercased will result in a different uppercase\n // character.\n // Hence, to get that form, we perform both lower- and uppercase.\n // Upper case makes sure keys will not interact with default prototypal\n // methods: no method is uppercase.\n .toLowerCase()\n .toUpperCase()\n )\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n */\nimport {factoryDestination} from 'micromark-factory-destination'\nimport {factoryLabel} from 'micromark-factory-label'\nimport {factorySpace} from 'micromark-factory-space'\nimport {factoryTitle} from 'micromark-factory-title'\nimport {factoryWhitespace} from 'micromark-factory-whitespace'\nimport {normalizeIdentifier} from 'micromark-util-normalize-identifier'\nimport {\n markdownLineEnding,\n markdownLineEndingOrSpace\n} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const definition = {\n name: 'definition',\n tokenize: tokenizeDefinition\n}\n/** @type {Construct} */\n\nconst titleConstruct = {\n tokenize: tokenizeTitle,\n partial: true\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeDefinition(effects, ok, nok) {\n const self = this\n /** @type {string} */\n\n let identifier\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('definition')\n return factoryLabel.call(\n self,\n effects,\n labelAfter,\n nok,\n 'definitionLabel',\n 'definitionLabelMarker',\n 'definitionLabelString'\n )(code)\n }\n /** @type {State} */\n\n function labelAfter(code) {\n identifier = normalizeIdentifier(\n self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1)\n )\n\n if (code === 58) {\n effects.enter('definitionMarker')\n effects.consume(code)\n effects.exit('definitionMarker') // Note: blank lines can’t exist in content.\n\n return factoryWhitespace(\n effects,\n factoryDestination(\n effects,\n effects.attempt(\n titleConstruct,\n factorySpace(effects, after, 'whitespace'),\n factorySpace(effects, after, 'whitespace')\n ),\n nok,\n 'definitionDestination',\n 'definitionDestinationLiteral',\n 'definitionDestinationLiteralMarker',\n 'definitionDestinationRaw',\n 'definitionDestinationString'\n )\n )\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function after(code) {\n if (code === null || markdownLineEnding(code)) {\n effects.exit('definition')\n\n if (!self.parser.defined.includes(identifier)) {\n self.parser.defined.push(identifier)\n }\n\n return ok(code)\n }\n\n return nok(code)\n }\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeTitle(effects, ok, nok) {\n return start\n /** @type {State} */\n\n function start(code) {\n return markdownLineEndingOrSpace(code)\n ? factoryWhitespace(effects, before)(code)\n : nok(code)\n }\n /** @type {State} */\n\n function before(code) {\n if (code === 34 || code === 39 || code === 40) {\n return factoryTitle(\n effects,\n factorySpace(effects, after, 'whitespace'),\n nok,\n 'definitionTitle',\n 'definitionTitleMarker',\n 'definitionTitleString'\n )(code)\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function after(code) {\n return code === null || markdownLineEnding(code) ? ok(code) : nok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n */\nimport {markdownLineEnding} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const hardBreakEscape = {\n name: 'hardBreakEscape',\n tokenize: tokenizeHardBreakEscape\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeHardBreakEscape(effects, ok, nok) {\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('hardBreakEscape')\n effects.enter('escapeMarker')\n effects.consume(code)\n return open\n }\n /** @type {State} */\n\n function open(code) {\n if (markdownLineEnding(code)) {\n effects.exit('escapeMarker')\n effects.exit('hardBreakEscape')\n return ok(code)\n }\n\n return nok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Resolver} Resolver\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').State} State\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {\n markdownLineEnding,\n markdownLineEndingOrSpace,\n markdownSpace\n} from 'micromark-util-character'\nimport {splice} from 'micromark-util-chunked'\n\n/** @type {Construct} */\nexport const headingAtx = {\n name: 'headingAtx',\n tokenize: tokenizeHeadingAtx,\n resolve: resolveHeadingAtx\n}\n/** @type {Resolver} */\n\nfunction resolveHeadingAtx(events, context) {\n let contentEnd = events.length - 2\n let contentStart = 3\n /** @type {Token} */\n\n let content\n /** @type {Token} */\n\n let text // Prefix whitespace, part of the opening.\n\n if (events[contentStart][1].type === 'whitespace') {\n contentStart += 2\n } // Suffix whitespace, part of the closing.\n\n if (\n contentEnd - 2 > contentStart &&\n events[contentEnd][1].type === 'whitespace'\n ) {\n contentEnd -= 2\n }\n\n if (\n events[contentEnd][1].type === 'atxHeadingSequence' &&\n (contentStart === contentEnd - 1 ||\n (contentEnd - 4 > contentStart &&\n events[contentEnd - 2][1].type === 'whitespace'))\n ) {\n contentEnd -= contentStart + 1 === contentEnd ? 2 : 4\n }\n\n if (contentEnd > contentStart) {\n content = {\n type: 'atxHeadingText',\n start: events[contentStart][1].start,\n end: events[contentEnd][1].end\n }\n text = {\n type: 'chunkText',\n start: events[contentStart][1].start,\n end: events[contentEnd][1].end,\n // @ts-expect-error Constants are fine to assign.\n contentType: 'text'\n }\n splice(events, contentStart, contentEnd - contentStart + 1, [\n ['enter', content, context],\n ['enter', text, context],\n ['exit', text, context],\n ['exit', content, context]\n ])\n }\n\n return events\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeHeadingAtx(effects, ok, nok) {\n const self = this\n let size = 0\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('atxHeading')\n effects.enter('atxHeadingSequence')\n return fenceOpenInside(code)\n }\n /** @type {State} */\n\n function fenceOpenInside(code) {\n if (code === 35 && size++ < 6) {\n effects.consume(code)\n return fenceOpenInside\n }\n\n if (code === null || markdownLineEndingOrSpace(code)) {\n effects.exit('atxHeadingSequence')\n return self.interrupt ? ok(code) : headingBreak(code)\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function headingBreak(code) {\n if (code === 35) {\n effects.enter('atxHeadingSequence')\n return sequence(code)\n }\n\n if (code === null || markdownLineEnding(code)) {\n effects.exit('atxHeading')\n return ok(code)\n }\n\n if (markdownSpace(code)) {\n return factorySpace(effects, headingBreak, 'whitespace')(code)\n }\n\n effects.enter('atxHeadingText')\n return data(code)\n }\n /** @type {State} */\n\n function sequence(code) {\n if (code === 35) {\n effects.consume(code)\n return sequence\n }\n\n effects.exit('atxHeadingSequence')\n return headingBreak(code)\n }\n /** @type {State} */\n\n function data(code) {\n if (code === null || code === 35 || markdownLineEndingOrSpace(code)) {\n effects.exit('atxHeadingText')\n return headingBreak(code)\n }\n\n effects.consume(code)\n return data\n }\n}\n","/**\n * List of lowercase HTML tag names which when parsing HTML (flow), result\n * in more relaxed rules (condition 6): because they are known blocks, the\n * HTML-like syntax doesn’t have to be strictly parsed.\n * For tag names not in this list, a more strict algorithm (condition 7) is used\n * to detect whether the HTML-like syntax is seen as HTML (flow) or not.\n *\n * This is copied from:\n * .\n */\nexport const htmlBlockNames = [\n 'address',\n 'article',\n 'aside',\n 'base',\n 'basefont',\n 'blockquote',\n 'body',\n 'caption',\n 'center',\n 'col',\n 'colgroup',\n 'dd',\n 'details',\n 'dialog',\n 'dir',\n 'div',\n 'dl',\n 'dt',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'frame',\n 'frameset',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'head',\n 'header',\n 'hr',\n 'html',\n 'iframe',\n 'legend',\n 'li',\n 'link',\n 'main',\n 'menu',\n 'menuitem',\n 'nav',\n 'noframes',\n 'ol',\n 'optgroup',\n 'option',\n 'p',\n 'param',\n 'section',\n 'source',\n 'summary',\n 'table',\n 'tbody',\n 'td',\n 'tfoot',\n 'th',\n 'thead',\n 'title',\n 'tr',\n 'track',\n 'ul'\n]\n\n/**\n * List of lowercase HTML tag names which when parsing HTML (flow), result in\n * HTML that can include lines w/o exiting, until a closing tag also in this\n * list is found (condition 1).\n *\n * This module is copied from:\n * .\n *\n * Note that `textarea` is not available in `CommonMark@0.29` but has been\n * merged to the primary branch and is slated to be released in the next release\n * of CommonMark.\n */\nexport const htmlRawNames = ['pre', 'script', 'style', 'textarea']\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Resolver} Resolver\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Code} Code\n */\nimport {\n asciiAlpha,\n asciiAlphanumeric,\n markdownLineEnding,\n markdownLineEndingOrSpace,\n markdownSpace\n} from 'micromark-util-character'\nimport {htmlBlockNames, htmlRawNames} from 'micromark-util-html-tag-name'\nimport {blankLine} from './blank-line.js'\n/** @type {Construct} */\n\nexport const htmlFlow = {\n name: 'htmlFlow',\n tokenize: tokenizeHtmlFlow,\n resolveTo: resolveToHtmlFlow,\n concrete: true\n}\n/** @type {Construct} */\n\nconst nextBlankConstruct = {\n tokenize: tokenizeNextBlank,\n partial: true\n}\n/** @type {Resolver} */\n\nfunction resolveToHtmlFlow(events) {\n let index = events.length\n\n while (index--) {\n if (events[index][0] === 'enter' && events[index][1].type === 'htmlFlow') {\n break\n }\n }\n\n if (index > 1 && events[index - 2][1].type === 'linePrefix') {\n // Add the prefix start to the HTML token.\n events[index][1].start = events[index - 2][1].start // Add the prefix start to the HTML line token.\n\n events[index + 1][1].start = events[index - 2][1].start // Remove the line prefix.\n\n events.splice(index - 2, 2)\n }\n\n return events\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeHtmlFlow(effects, ok, nok) {\n const self = this\n /** @type {number} */\n\n let kind\n /** @type {boolean} */\n\n let startTag\n /** @type {string} */\n\n let buffer\n /** @type {number} */\n\n let index\n /** @type {Code} */\n\n let marker\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('htmlFlow')\n effects.enter('htmlFlowData')\n effects.consume(code)\n return open\n }\n /** @type {State} */\n\n function open(code) {\n if (code === 33) {\n effects.consume(code)\n return declarationStart\n }\n\n if (code === 47) {\n effects.consume(code)\n return tagCloseStart\n }\n\n if (code === 63) {\n effects.consume(code)\n kind = 3 // While we’re in an instruction instead of a declaration, we’re on a `?`\n // right now, so we do need to search for `>`, similar to declarations.\n\n return self.interrupt ? ok : continuationDeclarationInside\n }\n\n if (asciiAlpha(code)) {\n effects.consume(code)\n buffer = String.fromCharCode(code)\n startTag = true\n return tagName\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function declarationStart(code) {\n if (code === 45) {\n effects.consume(code)\n kind = 2\n return commentOpenInside\n }\n\n if (code === 91) {\n effects.consume(code)\n kind = 5\n buffer = 'CDATA['\n index = 0\n return cdataOpenInside\n }\n\n if (asciiAlpha(code)) {\n effects.consume(code)\n kind = 4\n return self.interrupt ? ok : continuationDeclarationInside\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function commentOpenInside(code) {\n if (code === 45) {\n effects.consume(code)\n return self.interrupt ? ok : continuationDeclarationInside\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function cdataOpenInside(code) {\n if (code === buffer.charCodeAt(index++)) {\n effects.consume(code)\n return index === buffer.length\n ? self.interrupt\n ? ok\n : continuation\n : cdataOpenInside\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function tagCloseStart(code) {\n if (asciiAlpha(code)) {\n effects.consume(code)\n buffer = String.fromCharCode(code)\n return tagName\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function tagName(code) {\n if (\n code === null ||\n code === 47 ||\n code === 62 ||\n markdownLineEndingOrSpace(code)\n ) {\n if (\n code !== 47 &&\n startTag &&\n htmlRawNames.includes(buffer.toLowerCase())\n ) {\n kind = 1\n return self.interrupt ? ok(code) : continuation(code)\n }\n\n if (htmlBlockNames.includes(buffer.toLowerCase())) {\n kind = 6\n\n if (code === 47) {\n effects.consume(code)\n return basicSelfClosing\n }\n\n return self.interrupt ? ok(code) : continuation(code)\n }\n\n kind = 7 // Do not support complete HTML when interrupting\n\n return self.interrupt && !self.parser.lazy[self.now().line]\n ? nok(code)\n : startTag\n ? completeAttributeNameBefore(code)\n : completeClosingTagAfter(code)\n }\n\n if (code === 45 || asciiAlphanumeric(code)) {\n effects.consume(code)\n buffer += String.fromCharCode(code)\n return tagName\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function basicSelfClosing(code) {\n if (code === 62) {\n effects.consume(code)\n return self.interrupt ? ok : continuation\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function completeClosingTagAfter(code) {\n if (markdownSpace(code)) {\n effects.consume(code)\n return completeClosingTagAfter\n }\n\n return completeEnd(code)\n }\n /** @type {State} */\n\n function completeAttributeNameBefore(code) {\n if (code === 47) {\n effects.consume(code)\n return completeEnd\n }\n\n if (code === 58 || code === 95 || asciiAlpha(code)) {\n effects.consume(code)\n return completeAttributeName\n }\n\n if (markdownSpace(code)) {\n effects.consume(code)\n return completeAttributeNameBefore\n }\n\n return completeEnd(code)\n }\n /** @type {State} */\n\n function completeAttributeName(code) {\n if (\n code === 45 ||\n code === 46 ||\n code === 58 ||\n code === 95 ||\n asciiAlphanumeric(code)\n ) {\n effects.consume(code)\n return completeAttributeName\n }\n\n return completeAttributeNameAfter(code)\n }\n /** @type {State} */\n\n function completeAttributeNameAfter(code) {\n if (code === 61) {\n effects.consume(code)\n return completeAttributeValueBefore\n }\n\n if (markdownSpace(code)) {\n effects.consume(code)\n return completeAttributeNameAfter\n }\n\n return completeAttributeNameBefore(code)\n }\n /** @type {State} */\n\n function completeAttributeValueBefore(code) {\n if (\n code === null ||\n code === 60 ||\n code === 61 ||\n code === 62 ||\n code === 96\n ) {\n return nok(code)\n }\n\n if (code === 34 || code === 39) {\n effects.consume(code)\n marker = code\n return completeAttributeValueQuoted\n }\n\n if (markdownSpace(code)) {\n effects.consume(code)\n return completeAttributeValueBefore\n }\n\n marker = null\n return completeAttributeValueUnquoted(code)\n }\n /** @type {State} */\n\n function completeAttributeValueQuoted(code) {\n if (code === null || markdownLineEnding(code)) {\n return nok(code)\n }\n\n if (code === marker) {\n effects.consume(code)\n return completeAttributeValueQuotedAfter\n }\n\n effects.consume(code)\n return completeAttributeValueQuoted\n }\n /** @type {State} */\n\n function completeAttributeValueUnquoted(code) {\n if (\n code === null ||\n code === 34 ||\n code === 39 ||\n code === 60 ||\n code === 61 ||\n code === 62 ||\n code === 96 ||\n markdownLineEndingOrSpace(code)\n ) {\n return completeAttributeNameAfter(code)\n }\n\n effects.consume(code)\n return completeAttributeValueUnquoted\n }\n /** @type {State} */\n\n function completeAttributeValueQuotedAfter(code) {\n if (code === 47 || code === 62 || markdownSpace(code)) {\n return completeAttributeNameBefore(code)\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function completeEnd(code) {\n if (code === 62) {\n effects.consume(code)\n return completeAfter\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function completeAfter(code) {\n if (markdownSpace(code)) {\n effects.consume(code)\n return completeAfter\n }\n\n return code === null || markdownLineEnding(code)\n ? continuation(code)\n : nok(code)\n }\n /** @type {State} */\n\n function continuation(code) {\n if (code === 45 && kind === 2) {\n effects.consume(code)\n return continuationCommentInside\n }\n\n if (code === 60 && kind === 1) {\n effects.consume(code)\n return continuationRawTagOpen\n }\n\n if (code === 62 && kind === 4) {\n effects.consume(code)\n return continuationClose\n }\n\n if (code === 63 && kind === 3) {\n effects.consume(code)\n return continuationDeclarationInside\n }\n\n if (code === 93 && kind === 5) {\n effects.consume(code)\n return continuationCharacterDataInside\n }\n\n if (markdownLineEnding(code) && (kind === 6 || kind === 7)) {\n return effects.check(\n nextBlankConstruct,\n continuationClose,\n continuationAtLineEnding\n )(code)\n }\n\n if (code === null || markdownLineEnding(code)) {\n return continuationAtLineEnding(code)\n }\n\n effects.consume(code)\n return continuation\n }\n /** @type {State} */\n\n function continuationAtLineEnding(code) {\n effects.exit('htmlFlowData')\n return htmlContinueStart(code)\n }\n /** @type {State} */\n\n function htmlContinueStart(code) {\n if (code === null) {\n return done(code)\n }\n\n if (markdownLineEnding(code)) {\n return effects.attempt(\n {\n tokenize: htmlLineEnd,\n partial: true\n },\n htmlContinueStart,\n done\n )(code)\n }\n\n effects.enter('htmlFlowData')\n return continuation(code)\n }\n /** @type {Tokenizer} */\n\n function htmlLineEnd(effects, ok, nok) {\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n return lineStart\n }\n /** @type {State} */\n\n function lineStart(code) {\n return self.parser.lazy[self.now().line] ? nok(code) : ok(code)\n }\n }\n /** @type {State} */\n\n function continuationCommentInside(code) {\n if (code === 45) {\n effects.consume(code)\n return continuationDeclarationInside\n }\n\n return continuation(code)\n }\n /** @type {State} */\n\n function continuationRawTagOpen(code) {\n if (code === 47) {\n effects.consume(code)\n buffer = ''\n return continuationRawEndTag\n }\n\n return continuation(code)\n }\n /** @type {State} */\n\n function continuationRawEndTag(code) {\n if (code === 62 && htmlRawNames.includes(buffer.toLowerCase())) {\n effects.consume(code)\n return continuationClose\n }\n\n if (asciiAlpha(code) && buffer.length < 8) {\n effects.consume(code)\n buffer += String.fromCharCode(code)\n return continuationRawEndTag\n }\n\n return continuation(code)\n }\n /** @type {State} */\n\n function continuationCharacterDataInside(code) {\n if (code === 93) {\n effects.consume(code)\n return continuationDeclarationInside\n }\n\n return continuation(code)\n }\n /** @type {State} */\n\n function continuationDeclarationInside(code) {\n if (code === 62) {\n effects.consume(code)\n return continuationClose\n } // More dashes.\n\n if (code === 45 && kind === 2) {\n effects.consume(code)\n return continuationDeclarationInside\n }\n\n return continuation(code)\n }\n /** @type {State} */\n\n function continuationClose(code) {\n if (code === null || markdownLineEnding(code)) {\n effects.exit('htmlFlowData')\n return done(code)\n }\n\n effects.consume(code)\n return continuationClose\n }\n /** @type {State} */\n\n function done(code) {\n effects.exit('htmlFlow')\n return ok(code)\n }\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeNextBlank(effects, ok, nok) {\n return start\n /** @type {State} */\n\n function start(code) {\n effects.exit('htmlFlowData')\n effects.enter('lineEndingBlank')\n effects.consume(code)\n effects.exit('lineEndingBlank')\n return effects.attempt(blankLine, ok, nok)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Code} Code\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {\n asciiAlpha,\n asciiAlphanumeric,\n markdownLineEnding,\n markdownLineEndingOrSpace,\n markdownSpace\n} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const htmlText = {\n name: 'htmlText',\n tokenize: tokenizeHtmlText\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeHtmlText(effects, ok, nok) {\n const self = this\n /** @type {NonNullable|undefined} */\n\n let marker\n /** @type {string} */\n\n let buffer\n /** @type {number} */\n\n let index\n /** @type {State} */\n\n let returnState\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('htmlText')\n effects.enter('htmlTextData')\n effects.consume(code)\n return open\n }\n /** @type {State} */\n\n function open(code) {\n if (code === 33) {\n effects.consume(code)\n return declarationOpen\n }\n\n if (code === 47) {\n effects.consume(code)\n return tagCloseStart\n }\n\n if (code === 63) {\n effects.consume(code)\n return instruction\n }\n\n if (asciiAlpha(code)) {\n effects.consume(code)\n return tagOpen\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function declarationOpen(code) {\n if (code === 45) {\n effects.consume(code)\n return commentOpen\n }\n\n if (code === 91) {\n effects.consume(code)\n buffer = 'CDATA['\n index = 0\n return cdataOpen\n }\n\n if (asciiAlpha(code)) {\n effects.consume(code)\n return declaration\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function commentOpen(code) {\n if (code === 45) {\n effects.consume(code)\n return commentStart\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function commentStart(code) {\n if (code === null || code === 62) {\n return nok(code)\n }\n\n if (code === 45) {\n effects.consume(code)\n return commentStartDash\n }\n\n return comment(code)\n }\n /** @type {State} */\n\n function commentStartDash(code) {\n if (code === null || code === 62) {\n return nok(code)\n }\n\n return comment(code)\n }\n /** @type {State} */\n\n function comment(code) {\n if (code === null) {\n return nok(code)\n }\n\n if (code === 45) {\n effects.consume(code)\n return commentClose\n }\n\n if (markdownLineEnding(code)) {\n returnState = comment\n return atLineEnding(code)\n }\n\n effects.consume(code)\n return comment\n }\n /** @type {State} */\n\n function commentClose(code) {\n if (code === 45) {\n effects.consume(code)\n return end\n }\n\n return comment(code)\n }\n /** @type {State} */\n\n function cdataOpen(code) {\n if (code === buffer.charCodeAt(index++)) {\n effects.consume(code)\n return index === buffer.length ? cdata : cdataOpen\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function cdata(code) {\n if (code === null) {\n return nok(code)\n }\n\n if (code === 93) {\n effects.consume(code)\n return cdataClose\n }\n\n if (markdownLineEnding(code)) {\n returnState = cdata\n return atLineEnding(code)\n }\n\n effects.consume(code)\n return cdata\n }\n /** @type {State} */\n\n function cdataClose(code) {\n if (code === 93) {\n effects.consume(code)\n return cdataEnd\n }\n\n return cdata(code)\n }\n /** @type {State} */\n\n function cdataEnd(code) {\n if (code === 62) {\n return end(code)\n }\n\n if (code === 93) {\n effects.consume(code)\n return cdataEnd\n }\n\n return cdata(code)\n }\n /** @type {State} */\n\n function declaration(code) {\n if (code === null || code === 62) {\n return end(code)\n }\n\n if (markdownLineEnding(code)) {\n returnState = declaration\n return atLineEnding(code)\n }\n\n effects.consume(code)\n return declaration\n }\n /** @type {State} */\n\n function instruction(code) {\n if (code === null) {\n return nok(code)\n }\n\n if (code === 63) {\n effects.consume(code)\n return instructionClose\n }\n\n if (markdownLineEnding(code)) {\n returnState = instruction\n return atLineEnding(code)\n }\n\n effects.consume(code)\n return instruction\n }\n /** @type {State} */\n\n function instructionClose(code) {\n return code === 62 ? end(code) : instruction(code)\n }\n /** @type {State} */\n\n function tagCloseStart(code) {\n if (asciiAlpha(code)) {\n effects.consume(code)\n return tagClose\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function tagClose(code) {\n if (code === 45 || asciiAlphanumeric(code)) {\n effects.consume(code)\n return tagClose\n }\n\n return tagCloseBetween(code)\n }\n /** @type {State} */\n\n function tagCloseBetween(code) {\n if (markdownLineEnding(code)) {\n returnState = tagCloseBetween\n return atLineEnding(code)\n }\n\n if (markdownSpace(code)) {\n effects.consume(code)\n return tagCloseBetween\n }\n\n return end(code)\n }\n /** @type {State} */\n\n function tagOpen(code) {\n if (code === 45 || asciiAlphanumeric(code)) {\n effects.consume(code)\n return tagOpen\n }\n\n if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) {\n return tagOpenBetween(code)\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function tagOpenBetween(code) {\n if (code === 47) {\n effects.consume(code)\n return end\n }\n\n if (code === 58 || code === 95 || asciiAlpha(code)) {\n effects.consume(code)\n return tagOpenAttributeName\n }\n\n if (markdownLineEnding(code)) {\n returnState = tagOpenBetween\n return atLineEnding(code)\n }\n\n if (markdownSpace(code)) {\n effects.consume(code)\n return tagOpenBetween\n }\n\n return end(code)\n }\n /** @type {State} */\n\n function tagOpenAttributeName(code) {\n if (\n code === 45 ||\n code === 46 ||\n code === 58 ||\n code === 95 ||\n asciiAlphanumeric(code)\n ) {\n effects.consume(code)\n return tagOpenAttributeName\n }\n\n return tagOpenAttributeNameAfter(code)\n }\n /** @type {State} */\n\n function tagOpenAttributeNameAfter(code) {\n if (code === 61) {\n effects.consume(code)\n return tagOpenAttributeValueBefore\n }\n\n if (markdownLineEnding(code)) {\n returnState = tagOpenAttributeNameAfter\n return atLineEnding(code)\n }\n\n if (markdownSpace(code)) {\n effects.consume(code)\n return tagOpenAttributeNameAfter\n }\n\n return tagOpenBetween(code)\n }\n /** @type {State} */\n\n function tagOpenAttributeValueBefore(code) {\n if (\n code === null ||\n code === 60 ||\n code === 61 ||\n code === 62 ||\n code === 96\n ) {\n return nok(code)\n }\n\n if (code === 34 || code === 39) {\n effects.consume(code)\n marker = code\n return tagOpenAttributeValueQuoted\n }\n\n if (markdownLineEnding(code)) {\n returnState = tagOpenAttributeValueBefore\n return atLineEnding(code)\n }\n\n if (markdownSpace(code)) {\n effects.consume(code)\n return tagOpenAttributeValueBefore\n }\n\n effects.consume(code)\n marker = undefined\n return tagOpenAttributeValueUnquoted\n }\n /** @type {State} */\n\n function tagOpenAttributeValueQuoted(code) {\n if (code === marker) {\n effects.consume(code)\n return tagOpenAttributeValueQuotedAfter\n }\n\n if (code === null) {\n return nok(code)\n }\n\n if (markdownLineEnding(code)) {\n returnState = tagOpenAttributeValueQuoted\n return atLineEnding(code)\n }\n\n effects.consume(code)\n return tagOpenAttributeValueQuoted\n }\n /** @type {State} */\n\n function tagOpenAttributeValueQuotedAfter(code) {\n if (code === 62 || code === 47 || markdownLineEndingOrSpace(code)) {\n return tagOpenBetween(code)\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function tagOpenAttributeValueUnquoted(code) {\n if (\n code === null ||\n code === 34 ||\n code === 39 ||\n code === 60 ||\n code === 61 ||\n code === 96\n ) {\n return nok(code)\n }\n\n if (code === 62 || markdownLineEndingOrSpace(code)) {\n return tagOpenBetween(code)\n }\n\n effects.consume(code)\n return tagOpenAttributeValueUnquoted\n } // We can’t have blank lines in content, so no need to worry about empty\n // tokens.\n\n /** @type {State} */\n\n function atLineEnding(code) {\n effects.exit('htmlTextData')\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n return factorySpace(\n effects,\n afterPrefix,\n 'linePrefix',\n self.parser.constructs.disable.null.includes('codeIndented')\n ? undefined\n : 4\n )\n }\n /** @type {State} */\n\n function afterPrefix(code) {\n effects.enter('htmlTextData')\n return returnState(code)\n }\n /** @type {State} */\n\n function end(code) {\n if (code === 62) {\n effects.consume(code)\n effects.exit('htmlTextData')\n effects.exit('htmlText')\n return ok\n }\n\n return nok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Resolver} Resolver\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').Event} Event\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Code} Code\n */\nimport {factoryDestination} from 'micromark-factory-destination'\nimport {factoryLabel} from 'micromark-factory-label'\nimport {factoryTitle} from 'micromark-factory-title'\nimport {factoryWhitespace} from 'micromark-factory-whitespace'\nimport {markdownLineEndingOrSpace} from 'micromark-util-character'\nimport {push, splice} from 'micromark-util-chunked'\nimport {normalizeIdentifier} from 'micromark-util-normalize-identifier'\nimport {resolveAll} from 'micromark-util-resolve-all'\n\n/** @type {Construct} */\nexport const labelEnd = {\n name: 'labelEnd',\n tokenize: tokenizeLabelEnd,\n resolveTo: resolveToLabelEnd,\n resolveAll: resolveAllLabelEnd\n}\n/** @type {Construct} */\n\nconst resourceConstruct = {\n tokenize: tokenizeResource\n}\n/** @type {Construct} */\n\nconst fullReferenceConstruct = {\n tokenize: tokenizeFullReference\n}\n/** @type {Construct} */\n\nconst collapsedReferenceConstruct = {\n tokenize: tokenizeCollapsedReference\n}\n/** @type {Resolver} */\n\nfunction resolveAllLabelEnd(events) {\n let index = -1\n /** @type {Token} */\n\n let token\n\n while (++index < events.length) {\n token = events[index][1]\n\n if (\n token.type === 'labelImage' ||\n token.type === 'labelLink' ||\n token.type === 'labelEnd'\n ) {\n // Remove the marker.\n events.splice(index + 1, token.type === 'labelImage' ? 4 : 2)\n token.type = 'data'\n index++\n }\n }\n\n return events\n}\n/** @type {Resolver} */\n\nfunction resolveToLabelEnd(events, context) {\n let index = events.length\n let offset = 0\n /** @type {Token} */\n\n let token\n /** @type {number|undefined} */\n\n let open\n /** @type {number|undefined} */\n\n let close\n /** @type {Event[]} */\n\n let media // Find an opening.\n\n while (index--) {\n token = events[index][1]\n\n if (open) {\n // If we see another link, or inactive link label, we’ve been here before.\n if (\n token.type === 'link' ||\n (token.type === 'labelLink' && token._inactive)\n ) {\n break\n } // Mark other link openings as inactive, as we can’t have links in\n // links.\n\n if (events[index][0] === 'enter' && token.type === 'labelLink') {\n token._inactive = true\n }\n } else if (close) {\n if (\n events[index][0] === 'enter' &&\n (token.type === 'labelImage' || token.type === 'labelLink') &&\n !token._balanced\n ) {\n open = index\n\n if (token.type !== 'labelLink') {\n offset = 2\n break\n }\n }\n } else if (token.type === 'labelEnd') {\n close = index\n }\n }\n\n const group = {\n type: events[open][1].type === 'labelLink' ? 'link' : 'image',\n start: Object.assign({}, events[open][1].start),\n end: Object.assign({}, events[events.length - 1][1].end)\n }\n const label = {\n type: 'label',\n start: Object.assign({}, events[open][1].start),\n end: Object.assign({}, events[close][1].end)\n }\n const text = {\n type: 'labelText',\n start: Object.assign({}, events[open + offset + 2][1].end),\n end: Object.assign({}, events[close - 2][1].start)\n }\n media = [\n ['enter', group, context],\n ['enter', label, context]\n ] // Opening marker.\n\n media = push(media, events.slice(open + 1, open + offset + 3)) // Text open.\n\n media = push(media, [['enter', text, context]]) // Between.\n\n media = push(\n media,\n resolveAll(\n context.parser.constructs.insideSpan.null,\n events.slice(open + offset + 4, close - 3),\n context\n )\n ) // Text close, marker close, label close.\n\n media = push(media, [\n ['exit', text, context],\n events[close - 2],\n events[close - 1],\n ['exit', label, context]\n ]) // Reference, resource, or so.\n\n media = push(media, events.slice(close + 1)) // Media close.\n\n media = push(media, [['exit', group, context]])\n splice(events, open, events.length, media)\n return events\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeLabelEnd(effects, ok, nok) {\n const self = this\n let index = self.events.length\n /** @type {Token} */\n\n let labelStart\n /** @type {boolean} */\n\n let defined // Find an opening.\n\n while (index--) {\n if (\n (self.events[index][1].type === 'labelImage' ||\n self.events[index][1].type === 'labelLink') &&\n !self.events[index][1]._balanced\n ) {\n labelStart = self.events[index][1]\n break\n }\n }\n\n return start\n /** @type {State} */\n\n function start(code) {\n if (!labelStart) {\n return nok(code)\n } // It’s a balanced bracket, but contains a link.\n\n if (labelStart._inactive) return balanced(code)\n defined = self.parser.defined.includes(\n normalizeIdentifier(\n self.sliceSerialize({\n start: labelStart.end,\n end: self.now()\n })\n )\n )\n effects.enter('labelEnd')\n effects.enter('labelMarker')\n effects.consume(code)\n effects.exit('labelMarker')\n effects.exit('labelEnd')\n return afterLabelEnd\n }\n /** @type {State} */\n\n function afterLabelEnd(code) {\n // Resource: `[asd](fgh)`.\n if (code === 40) {\n return effects.attempt(\n resourceConstruct,\n ok,\n defined ? ok : balanced\n )(code)\n } // Collapsed (`[asd][]`) or full (`[asd][fgh]`) reference?\n\n if (code === 91) {\n return effects.attempt(\n fullReferenceConstruct,\n ok,\n defined\n ? effects.attempt(collapsedReferenceConstruct, ok, balanced)\n : balanced\n )(code)\n } // Shortcut reference: `[asd]`?\n\n return defined ? ok(code) : balanced(code)\n }\n /** @type {State} */\n\n function balanced(code) {\n labelStart._balanced = true\n return nok(code)\n }\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeResource(effects, ok, nok) {\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('resource')\n effects.enter('resourceMarker')\n effects.consume(code)\n effects.exit('resourceMarker')\n return factoryWhitespace(effects, open)\n }\n /** @type {State} */\n\n function open(code) {\n if (code === 41) {\n return end(code)\n }\n\n return factoryDestination(\n effects,\n destinationAfter,\n nok,\n 'resourceDestination',\n 'resourceDestinationLiteral',\n 'resourceDestinationLiteralMarker',\n 'resourceDestinationRaw',\n 'resourceDestinationString',\n 32\n )(code)\n }\n /** @type {State} */\n\n function destinationAfter(code) {\n return markdownLineEndingOrSpace(code)\n ? factoryWhitespace(effects, between)(code)\n : end(code)\n }\n /** @type {State} */\n\n function between(code) {\n if (code === 34 || code === 39 || code === 40) {\n return factoryTitle(\n effects,\n factoryWhitespace(effects, end),\n nok,\n 'resourceTitle',\n 'resourceTitleMarker',\n 'resourceTitleString'\n )(code)\n }\n\n return end(code)\n }\n /** @type {State} */\n\n function end(code) {\n if (code === 41) {\n effects.enter('resourceMarker')\n effects.consume(code)\n effects.exit('resourceMarker')\n effects.exit('resource')\n return ok\n }\n\n return nok(code)\n }\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeFullReference(effects, ok, nok) {\n const self = this\n return start\n /** @type {State} */\n\n function start(code) {\n return factoryLabel.call(\n self,\n effects,\n afterLabel,\n nok,\n 'reference',\n 'referenceMarker',\n 'referenceString'\n )(code)\n }\n /** @type {State} */\n\n function afterLabel(code) {\n return self.parser.defined.includes(\n normalizeIdentifier(\n self.sliceSerialize(self.events[self.events.length - 1][1]).slice(1, -1)\n )\n )\n ? ok(code)\n : nok(code)\n }\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeCollapsedReference(effects, ok, nok) {\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('reference')\n effects.enter('referenceMarker')\n effects.consume(code)\n effects.exit('referenceMarker')\n return open\n }\n /** @type {State} */\n\n function open(code) {\n if (code === 93) {\n effects.enter('referenceMarker')\n effects.consume(code)\n effects.exit('referenceMarker')\n effects.exit('reference')\n return ok\n }\n\n return nok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n */\nimport {labelEnd} from './label-end.js'\n/** @type {Construct} */\n\nexport const labelStartImage = {\n name: 'labelStartImage',\n tokenize: tokenizeLabelStartImage,\n resolveAll: labelEnd.resolveAll\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeLabelStartImage(effects, ok, nok) {\n const self = this\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('labelImage')\n effects.enter('labelImageMarker')\n effects.consume(code)\n effects.exit('labelImageMarker')\n return open\n }\n /** @type {State} */\n\n function open(code) {\n if (code === 91) {\n effects.enter('labelMarker')\n effects.consume(code)\n effects.exit('labelMarker')\n effects.exit('labelImage')\n return after\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function after(code) {\n /* To do: remove in the future once we’ve switched from\n * `micromark-extension-footnote` to `micromark-extension-gfm-footnote`,\n * which doesn’t need this */\n\n /* Hidden footnotes hook */\n\n /* c8 ignore next 3 */\n return code === 94 && '_hiddenFootnoteSupport' in self.parser.constructs\n ? nok(code)\n : ok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n */\nimport {labelEnd} from './label-end.js'\n/** @type {Construct} */\n\nexport const labelStartLink = {\n name: 'labelStartLink',\n tokenize: tokenizeLabelStartLink,\n resolveAll: labelEnd.resolveAll\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeLabelStartLink(effects, ok, nok) {\n const self = this\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('labelLink')\n effects.enter('labelMarker')\n effects.consume(code)\n effects.exit('labelMarker')\n effects.exit('labelLink')\n return after\n }\n /** @type {State} */\n\n function after(code) {\n /* To do: remove in the future once we’ve switched from\n * `micromark-extension-footnote` to `micromark-extension-gfm-footnote`,\n * which doesn’t need this */\n\n /* Hidden footnotes hook. */\n\n /* c8 ignore next 3 */\n return code === 94 && '_hiddenFootnoteSupport' in self.parser.constructs\n ? nok(code)\n : ok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownLineEnding} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const lineEnding = {\n name: 'lineEnding',\n tokenize: tokenizeLineEnding\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeLineEnding(effects, ok) {\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n return factorySpace(effects, ok, 'linePrefix')\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Code} Code\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownLineEnding, markdownSpace} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const thematicBreak = {\n name: 'thematicBreak',\n tokenize: tokenizeThematicBreak\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeThematicBreak(effects, ok, nok) {\n let size = 0\n /** @type {NonNullable} */\n\n let marker\n return start\n /** @type {State} */\n\n function start(code) {\n effects.enter('thematicBreak')\n marker = code\n return atBreak(code)\n }\n /** @type {State} */\n\n function atBreak(code) {\n if (code === marker) {\n effects.enter('thematicBreakSequence')\n return sequence(code)\n }\n\n if (markdownSpace(code)) {\n return factorySpace(effects, atBreak, 'whitespace')(code)\n }\n\n if (size < 3 || (code !== null && !markdownLineEnding(code))) {\n return nok(code)\n }\n\n effects.exit('thematicBreak')\n return ok(code)\n }\n /** @type {State} */\n\n function sequence(code) {\n if (code === marker) {\n effects.consume(code)\n size++\n return sequence\n }\n\n effects.exit('thematicBreakSequence')\n return atBreak(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext\n * @typedef {import('micromark-util-types').Exiter} Exiter\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Code} Code\n */\n\n/**\n * @typedef {Record & {marker: Code, type: string, size: number}} ListContainerState\n * @typedef {TokenizeContext & {containerState: ListContainerState}} TokenizeContextWithState\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {asciiDigit, markdownSpace} from 'micromark-util-character'\nimport {blankLine} from './blank-line.js'\nimport {thematicBreak} from './thematic-break.js'\n/** @type {Construct} */\n\nexport const list = {\n name: 'list',\n tokenize: tokenizeListStart,\n continuation: {\n tokenize: tokenizeListContinuation\n },\n exit: tokenizeListEnd\n}\n/** @type {Construct} */\n\nconst listItemPrefixWhitespaceConstruct = {\n tokenize: tokenizeListItemPrefixWhitespace,\n partial: true\n}\n/** @type {Construct} */\n\nconst indentConstruct = {\n tokenize: tokenizeIndent,\n partial: true\n}\n/**\n * @type {Tokenizer}\n * @this {TokenizeContextWithState}\n */\n\nfunction tokenizeListStart(effects, ok, nok) {\n const self = this\n const tail = self.events[self.events.length - 1]\n let initialSize =\n tail && tail[1].type === 'linePrefix'\n ? tail[2].sliceSerialize(tail[1], true).length\n : 0\n let size = 0\n return start\n /** @type {State} */\n\n function start(code) {\n const kind =\n self.containerState.type ||\n (code === 42 || code === 43 || code === 45\n ? 'listUnordered'\n : 'listOrdered')\n\n if (\n kind === 'listUnordered'\n ? !self.containerState.marker || code === self.containerState.marker\n : asciiDigit(code)\n ) {\n if (!self.containerState.type) {\n self.containerState.type = kind\n effects.enter(kind, {\n _container: true\n })\n }\n\n if (kind === 'listUnordered') {\n effects.enter('listItemPrefix')\n return code === 42 || code === 45\n ? effects.check(thematicBreak, nok, atMarker)(code)\n : atMarker(code)\n }\n\n if (!self.interrupt || code === 49) {\n effects.enter('listItemPrefix')\n effects.enter('listItemValue')\n return inside(code)\n }\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function inside(code) {\n if (asciiDigit(code) && ++size < 10) {\n effects.consume(code)\n return inside\n }\n\n if (\n (!self.interrupt || size < 2) &&\n (self.containerState.marker\n ? code === self.containerState.marker\n : code === 41 || code === 46)\n ) {\n effects.exit('listItemValue')\n return atMarker(code)\n }\n\n return nok(code)\n }\n /**\n * @type {State}\n **/\n\n function atMarker(code) {\n effects.enter('listItemMarker')\n effects.consume(code)\n effects.exit('listItemMarker')\n self.containerState.marker = self.containerState.marker || code\n return effects.check(\n blankLine, // Can’t be empty when interrupting.\n self.interrupt ? nok : onBlank,\n effects.attempt(\n listItemPrefixWhitespaceConstruct,\n endOfPrefix,\n otherPrefix\n )\n )\n }\n /** @type {State} */\n\n function onBlank(code) {\n self.containerState.initialBlankLine = true\n initialSize++\n return endOfPrefix(code)\n }\n /** @type {State} */\n\n function otherPrefix(code) {\n if (markdownSpace(code)) {\n effects.enter('listItemPrefixWhitespace')\n effects.consume(code)\n effects.exit('listItemPrefixWhitespace')\n return endOfPrefix\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function endOfPrefix(code) {\n self.containerState.size =\n initialSize +\n self.sliceSerialize(effects.exit('listItemPrefix'), true).length\n return ok(code)\n }\n}\n/**\n * @type {Tokenizer}\n * @this {TokenizeContextWithState}\n */\n\nfunction tokenizeListContinuation(effects, ok, nok) {\n const self = this\n self.containerState._closeFlow = undefined\n return effects.check(blankLine, onBlank, notBlank)\n /** @type {State} */\n\n function onBlank(code) {\n self.containerState.furtherBlankLines =\n self.containerState.furtherBlankLines ||\n self.containerState.initialBlankLine // We have a blank line.\n // Still, try to consume at most the items size.\n\n return factorySpace(\n effects,\n ok,\n 'listItemIndent',\n self.containerState.size + 1\n )(code)\n }\n /** @type {State} */\n\n function notBlank(code) {\n if (self.containerState.furtherBlankLines || !markdownSpace(code)) {\n self.containerState.furtherBlankLines = undefined\n self.containerState.initialBlankLine = undefined\n return notInCurrentItem(code)\n }\n\n self.containerState.furtherBlankLines = undefined\n self.containerState.initialBlankLine = undefined\n return effects.attempt(indentConstruct, ok, notInCurrentItem)(code)\n }\n /** @type {State} */\n\n function notInCurrentItem(code) {\n // While we do continue, we signal that the flow should be closed.\n self.containerState._closeFlow = true // As we’re closing flow, we’re no longer interrupting.\n\n self.interrupt = undefined\n return factorySpace(\n effects,\n effects.attempt(list, ok, nok),\n 'linePrefix',\n self.parser.constructs.disable.null.includes('codeIndented')\n ? undefined\n : 4\n )(code)\n }\n}\n/**\n * @type {Tokenizer}\n * @this {TokenizeContextWithState}\n */\n\nfunction tokenizeIndent(effects, ok, nok) {\n const self = this\n return factorySpace(\n effects,\n afterPrefix,\n 'listItemIndent',\n self.containerState.size + 1\n )\n /** @type {State} */\n\n function afterPrefix(code) {\n const tail = self.events[self.events.length - 1]\n return tail &&\n tail[1].type === 'listItemIndent' &&\n tail[2].sliceSerialize(tail[1], true).length === self.containerState.size\n ? ok(code)\n : nok(code)\n }\n}\n/**\n * @type {Exiter}\n * @this {TokenizeContextWithState}\n */\n\nfunction tokenizeListEnd(effects) {\n effects.exit(this.containerState.type)\n}\n/**\n * @type {Tokenizer}\n * @this {TokenizeContextWithState}\n */\n\nfunction tokenizeListItemPrefixWhitespace(effects, ok, nok) {\n const self = this\n return factorySpace(\n effects,\n afterPrefix,\n 'listItemPrefixWhitespace',\n self.parser.constructs.disable.null.includes('codeIndented')\n ? undefined\n : 4 + 1\n )\n /** @type {State} */\n\n function afterPrefix(code) {\n const tail = self.events[self.events.length - 1]\n return !markdownSpace(code) &&\n tail &&\n tail[1].type === 'listItemPrefixWhitespace'\n ? ok(code)\n : nok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').Resolver} Resolver\n * @typedef {import('micromark-util-types').Tokenizer} Tokenizer\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Code} Code\n */\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownLineEnding} from 'micromark-util-character'\n\n/** @type {Construct} */\nexport const setextUnderline = {\n name: 'setextUnderline',\n tokenize: tokenizeSetextUnderline,\n resolveTo: resolveToSetextUnderline\n}\n/** @type {Resolver} */\n\nfunction resolveToSetextUnderline(events, context) {\n let index = events.length\n /** @type {number|undefined} */\n\n let content\n /** @type {number|undefined} */\n\n let text\n /** @type {number|undefined} */\n\n let definition // Find the opening of the content.\n // It’ll always exist: we don’t tokenize if it isn’t there.\n\n while (index--) {\n if (events[index][0] === 'enter') {\n if (events[index][1].type === 'content') {\n content = index\n break\n }\n\n if (events[index][1].type === 'paragraph') {\n text = index\n }\n } // Exit\n else {\n if (events[index][1].type === 'content') {\n // Remove the content end (if needed we’ll add it later)\n events.splice(index, 1)\n }\n\n if (!definition && events[index][1].type === 'definition') {\n definition = index\n }\n }\n }\n\n const heading = {\n type: 'setextHeading',\n start: Object.assign({}, events[text][1].start),\n end: Object.assign({}, events[events.length - 1][1].end)\n } // Change the paragraph to setext heading text.\n\n events[text][1].type = 'setextHeadingText' // If we have definitions in the content, we’ll keep on having content,\n // but we need move it.\n\n if (definition) {\n events.splice(text, 0, ['enter', heading, context])\n events.splice(definition + 1, 0, ['exit', events[content][1], context])\n events[content][1].end = Object.assign({}, events[definition][1].end)\n } else {\n events[content][1] = heading\n } // Add the heading exit at the end.\n\n events.push(['exit', heading, context])\n return events\n}\n/** @type {Tokenizer} */\n\nfunction tokenizeSetextUnderline(effects, ok, nok) {\n const self = this\n let index = self.events.length\n /** @type {NonNullable} */\n\n let marker\n /** @type {boolean} */\n\n let paragraph // Find an opening.\n\n while (index--) {\n // Skip enter/exit of line ending, line prefix, and content.\n // We can now either have a definition or a paragraph.\n if (\n self.events[index][1].type !== 'lineEnding' &&\n self.events[index][1].type !== 'linePrefix' &&\n self.events[index][1].type !== 'content'\n ) {\n paragraph = self.events[index][1].type === 'paragraph'\n break\n }\n }\n\n return start\n /** @type {State} */\n\n function start(code) {\n if (!self.parser.lazy[self.now().line] && (self.interrupt || paragraph)) {\n effects.enter('setextHeadingLine')\n effects.enter('setextHeadingLineSequence')\n marker = code\n return closingSequence(code)\n }\n\n return nok(code)\n }\n /** @type {State} */\n\n function closingSequence(code) {\n if (code === marker) {\n effects.consume(code)\n return closingSequence\n }\n\n effects.exit('setextHeadingLineSequence')\n return factorySpace(effects, closingSequenceEnd, 'lineSuffix')(code)\n }\n /** @type {State} */\n\n function closingSequenceEnd(code) {\n if (code === null || markdownLineEnding(code)) {\n effects.exit('setextHeadingLine')\n return ok(code)\n }\n\n return nok(code)\n }\n}\n","/**\n * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct\n * @typedef {import('micromark-util-types').Initializer} Initializer\n * @typedef {import('micromark-util-types').State} State\n */\nimport {blankLine, content} from 'micromark-core-commonmark'\nimport {factorySpace} from 'micromark-factory-space'\nimport {markdownLineEnding} from 'micromark-util-character'\n\n/** @type {InitialConstruct} */\nexport const flow = {\n tokenize: initializeFlow\n}\n/** @type {Initializer} */\n\nfunction initializeFlow(effects) {\n const self = this\n const initial = effects.attempt(\n // Try to parse a blank line.\n blankLine,\n atBlankEnding, // Try to parse initial flow (essentially, only code).\n effects.attempt(\n this.parser.constructs.flowInitial,\n afterConstruct,\n factorySpace(\n effects,\n effects.attempt(\n this.parser.constructs.flow,\n afterConstruct,\n effects.attempt(content, afterConstruct)\n ),\n 'linePrefix'\n )\n )\n )\n return initial\n /** @type {State} */\n\n function atBlankEnding(code) {\n if (code === null) {\n effects.consume(code)\n return\n }\n\n effects.enter('lineEndingBlank')\n effects.consume(code)\n effects.exit('lineEndingBlank')\n self.currentConstruct = undefined\n return initial\n }\n /** @type {State} */\n\n function afterConstruct(code) {\n if (code === null) {\n effects.consume(code)\n return\n }\n\n effects.enter('lineEnding')\n effects.consume(code)\n effects.exit('lineEnding')\n self.currentConstruct = undefined\n return initial\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Resolver} Resolver\n * @typedef {import('micromark-util-types').Initializer} Initializer\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Code} Code\n */\nexport const resolver = {\n resolveAll: createResolver()\n}\nexport const string = initializeFactory('string')\nexport const text = initializeFactory('text')\n/**\n * @param {'string'|'text'} field\n * @returns {InitialConstruct}\n */\n\nfunction initializeFactory(field) {\n return {\n tokenize: initializeText,\n resolveAll: createResolver(\n field === 'text' ? resolveAllLineSuffixes : undefined\n )\n }\n /** @type {Initializer} */\n\n function initializeText(effects) {\n const self = this\n const constructs = this.parser.constructs[field]\n const text = effects.attempt(constructs, start, notText)\n return start\n /** @type {State} */\n\n function start(code) {\n return atBreak(code) ? text(code) : notText(code)\n }\n /** @type {State} */\n\n function notText(code) {\n if (code === null) {\n effects.consume(code)\n return\n }\n\n effects.enter('data')\n effects.consume(code)\n return data\n }\n /** @type {State} */\n\n function data(code) {\n if (atBreak(code)) {\n effects.exit('data')\n return text(code)\n } // Data.\n\n effects.consume(code)\n return data\n }\n /**\n * @param {Code} code\n * @returns {boolean}\n */\n\n function atBreak(code) {\n if (code === null) {\n return true\n }\n\n const list = constructs[code]\n let index = -1\n\n if (list) {\n while (++index < list.length) {\n const item = list[index]\n\n if (!item.previous || item.previous.call(self, self.previous)) {\n return true\n }\n }\n }\n\n return false\n }\n }\n}\n/**\n * @param {Resolver} [extraResolver]\n * @returns {Resolver}\n */\n\nfunction createResolver(extraResolver) {\n return resolveAllText\n /** @type {Resolver} */\n\n function resolveAllText(events, context) {\n let index = -1\n /** @type {number|undefined} */\n\n let enter // A rather boring computation (to merge adjacent `data` events) which\n // improves mm performance by 29%.\n\n while (++index <= events.length) {\n if (enter === undefined) {\n if (events[index] && events[index][1].type === 'data') {\n enter = index\n index++\n }\n } else if (!events[index] || events[index][1].type !== 'data') {\n // Don’t do anything if there is one data token.\n if (index !== enter + 2) {\n events[enter][1].end = events[index - 1][1].end\n events.splice(enter + 2, index - enter - 2)\n index = enter + 2\n }\n\n enter = undefined\n }\n }\n\n return extraResolver ? extraResolver(events, context) : events\n }\n}\n/**\n * A rather ugly set of instructions which again looks at chunks in the input\n * stream.\n * The reason to do this here is that it is *much* faster to parse in reverse.\n * And that we can’t hook into `null` to split the line suffix before an EOF.\n * To do: figure out if we can make this into a clean utility, or even in core.\n * As it will be useful for GFMs literal autolink extension (and maybe even\n * tables?)\n *\n * @type {Resolver}\n */\n\nfunction resolveAllLineSuffixes(events, context) {\n let eventIndex = 0 // Skip first.\n\n while (++eventIndex <= events.length) {\n if (\n (eventIndex === events.length ||\n events[eventIndex][1].type === 'lineEnding') &&\n events[eventIndex - 1][1].type === 'data'\n ) {\n const data = events[eventIndex - 1][1]\n const chunks = context.sliceStream(data)\n let index = chunks.length\n let bufferIndex = -1\n let size = 0\n /** @type {boolean|undefined} */\n\n let tabs\n\n while (index--) {\n const chunk = chunks[index]\n\n if (typeof chunk === 'string') {\n bufferIndex = chunk.length\n\n while (chunk.charCodeAt(bufferIndex - 1) === 32) {\n size++\n bufferIndex--\n }\n\n if (bufferIndex) break\n bufferIndex = -1\n } // Number\n else if (chunk === -2) {\n tabs = true\n size++\n } else if (chunk === -1) {\n // Empty\n } else {\n // Replacement character, exit.\n index++\n break\n }\n }\n\n if (size) {\n const token = {\n type:\n eventIndex === events.length || tabs || size < 2\n ? 'lineSuffix'\n : 'hardBreakTrailing',\n start: {\n line: data.end.line,\n column: data.end.column - size,\n offset: data.end.offset - size,\n _index: data.start._index + index,\n _bufferIndex: index\n ? bufferIndex\n : data.start._bufferIndex + bufferIndex\n },\n end: Object.assign({}, data.end)\n }\n data.end = Object.assign({}, token.start)\n\n if (data.start.offset === data.end.offset) {\n Object.assign(data, token)\n } else {\n events.splice(\n eventIndex,\n 0,\n ['enter', token, context],\n ['exit', token, context]\n )\n eventIndex += 2\n }\n }\n\n eventIndex++\n }\n }\n\n return events\n}\n","/**\n * @typedef {import('micromark-util-types').Code} Code\n * @typedef {import('micromark-util-types').Chunk} Chunk\n * @typedef {import('micromark-util-types').Point} Point\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').Effects} Effects\n * @typedef {import('micromark-util-types').State} State\n * @typedef {import('micromark-util-types').Construct} Construct\n * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct\n * @typedef {import('micromark-util-types').ConstructRecord} ConstructRecord\n * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext\n * @typedef {import('micromark-util-types').ParseContext} ParseContext\n */\n\n/**\n * @typedef Info\n * @property {() => void} restore\n * @property {number} from\n *\n * @callback ReturnHandle\n * Handle a successful run.\n * @param {Construct} construct\n * @param {Info} info\n * @returns {void}\n */\nimport {markdownLineEnding} from 'micromark-util-character'\nimport {push, splice} from 'micromark-util-chunked'\nimport {resolveAll} from 'micromark-util-resolve-all'\n\n/**\n * Create a tokenizer.\n * Tokenizers deal with one type of data (e.g., containers, flow, text).\n * The parser is the object dealing with it all.\n * `initialize` works like other constructs, except that only its `tokenize`\n * function is used, in which case it doesn’t receive an `ok` or `nok`.\n * `from` can be given to set the point before the first character, although\n * when further lines are indented, they must be set with `defineSkip`.\n *\n * @param {ParseContext} parser\n * @param {InitialConstruct} initialize\n * @param {Omit} [from]\n * @returns {TokenizeContext}\n */\nexport function createTokenizer(parser, initialize, from) {\n /** @type {Point} */\n let point = Object.assign(\n from\n ? Object.assign({}, from)\n : {\n line: 1,\n column: 1,\n offset: 0\n },\n {\n _index: 0,\n _bufferIndex: -1\n }\n )\n /** @type {Record} */\n\n const columnStart = {}\n /** @type {Construct[]} */\n\n const resolveAllConstructs = []\n /** @type {Chunk[]} */\n\n let chunks = []\n /** @type {Token[]} */\n\n let stack = []\n /** @type {boolean|undefined} */\n\n let consumed = true\n /**\n * Tools used for tokenizing.\n *\n * @type {Effects}\n */\n\n const effects = {\n consume,\n enter,\n exit,\n attempt: constructFactory(onsuccessfulconstruct),\n check: constructFactory(onsuccessfulcheck),\n interrupt: constructFactory(onsuccessfulcheck, {\n interrupt: true\n })\n }\n /**\n * State and tools for resolving and serializing.\n *\n * @type {TokenizeContext}\n */\n\n const context = {\n previous: null,\n code: null,\n containerState: {},\n events: [],\n parser,\n sliceStream,\n sliceSerialize,\n now,\n defineSkip,\n write\n }\n /**\n * The state function.\n *\n * @type {State|void}\n */\n\n let state = initialize.tokenize.call(context, effects)\n /**\n * Track which character we expect to be consumed, to catch bugs.\n *\n * @type {Code}\n */\n\n let expectedCode\n\n if (initialize.resolveAll) {\n resolveAllConstructs.push(initialize)\n }\n\n return context\n /** @type {TokenizeContext['write']} */\n\n function write(slice) {\n chunks = push(chunks, slice)\n main() // Exit if we’re not done, resolve might change stuff.\n\n if (chunks[chunks.length - 1] !== null) {\n return []\n }\n\n addResult(initialize, 0) // Otherwise, resolve, and exit.\n\n context.events = resolveAll(resolveAllConstructs, context.events, context)\n return context.events\n } //\n // Tools.\n //\n\n /** @type {TokenizeContext['sliceSerialize']} */\n\n function sliceSerialize(token, expandTabs) {\n return serializeChunks(sliceStream(token), expandTabs)\n }\n /** @type {TokenizeContext['sliceStream']} */\n\n function sliceStream(token) {\n return sliceChunks(chunks, token)\n }\n /** @type {TokenizeContext['now']} */\n\n function now() {\n return Object.assign({}, point)\n }\n /** @type {TokenizeContext['defineSkip']} */\n\n function defineSkip(value) {\n columnStart[value.line] = value.column\n accountForPotentialSkip()\n } //\n // State management.\n //\n\n /**\n * Main loop (note that `_index` and `_bufferIndex` in `point` are modified by\n * `consume`).\n * Here is where we walk through the chunks, which either include strings of\n * several characters, or numerical character codes.\n * The reason to do this in a loop instead of a call is so the stack can\n * drain.\n *\n * @returns {void}\n */\n\n function main() {\n /** @type {number} */\n let chunkIndex\n\n while (point._index < chunks.length) {\n const chunk = chunks[point._index] // If we’re in a buffer chunk, loop through it.\n\n if (typeof chunk === 'string') {\n chunkIndex = point._index\n\n if (point._bufferIndex < 0) {\n point._bufferIndex = 0\n }\n\n while (\n point._index === chunkIndex &&\n point._bufferIndex < chunk.length\n ) {\n go(chunk.charCodeAt(point._bufferIndex))\n }\n } else {\n go(chunk)\n }\n }\n }\n /**\n * Deal with one code.\n *\n * @param {Code} code\n * @returns {void}\n */\n\n function go(code) {\n consumed = undefined\n expectedCode = code\n state = state(code)\n }\n /** @type {Effects['consume']} */\n\n function consume(code) {\n if (markdownLineEnding(code)) {\n point.line++\n point.column = 1\n point.offset += code === -3 ? 2 : 1\n accountForPotentialSkip()\n } else if (code !== -1) {\n point.column++\n point.offset++\n } // Not in a string chunk.\n\n if (point._bufferIndex < 0) {\n point._index++\n } else {\n point._bufferIndex++ // At end of string chunk.\n // @ts-expect-error Points w/ non-negative `_bufferIndex` reference\n // strings.\n\n if (point._bufferIndex === chunks[point._index].length) {\n point._bufferIndex = -1\n point._index++\n }\n } // Expose the previous character.\n\n context.previous = code // Mark as consumed.\n\n consumed = true\n }\n /** @type {Effects['enter']} */\n\n function enter(type, fields) {\n /** @type {Token} */\n // @ts-expect-error Patch instead of assign required fields to help GC.\n const token = fields || {}\n token.type = type\n token.start = now()\n context.events.push(['enter', token, context])\n stack.push(token)\n return token\n }\n /** @type {Effects['exit']} */\n\n function exit(type) {\n const token = stack.pop()\n token.end = now()\n context.events.push(['exit', token, context])\n return token\n }\n /**\n * Use results.\n *\n * @type {ReturnHandle}\n */\n\n function onsuccessfulconstruct(construct, info) {\n addResult(construct, info.from)\n }\n /**\n * Discard results.\n *\n * @type {ReturnHandle}\n */\n\n function onsuccessfulcheck(_, info) {\n info.restore()\n }\n /**\n * Factory to attempt/check/interrupt.\n *\n * @param {ReturnHandle} onreturn\n * @param {Record} [fields]\n */\n\n function constructFactory(onreturn, fields) {\n return hook\n /**\n * Handle either an object mapping codes to constructs, a list of\n * constructs, or a single construct.\n *\n * @param {Construct|Construct[]|ConstructRecord} constructs\n * @param {State} returnState\n * @param {State} [bogusState]\n * @returns {State}\n */\n\n function hook(constructs, returnState, bogusState) {\n /** @type {Construct[]} */\n let listOfConstructs\n /** @type {number} */\n\n let constructIndex\n /** @type {Construct} */\n\n let currentConstruct\n /** @type {Info} */\n\n let info\n return Array.isArray(constructs)\n ? /* c8 ignore next 1 */\n handleListOfConstructs(constructs)\n : 'tokenize' in constructs // @ts-expect-error Looks like a construct.\n ? handleListOfConstructs([constructs])\n : handleMapOfConstructs(constructs)\n /**\n * Handle a list of construct.\n *\n * @param {ConstructRecord} map\n * @returns {State}\n */\n\n function handleMapOfConstructs(map) {\n return start\n /** @type {State} */\n\n function start(code) {\n const def = code !== null && map[code]\n const all = code !== null && map.null\n const list = [\n // To do: add more extension tests.\n\n /* c8 ignore next 2 */\n ...(Array.isArray(def) ? def : def ? [def] : []),\n ...(Array.isArray(all) ? all : all ? [all] : [])\n ]\n return handleListOfConstructs(list)(code)\n }\n }\n /**\n * Handle a list of construct.\n *\n * @param {Construct[]} list\n * @returns {State}\n */\n\n function handleListOfConstructs(list) {\n listOfConstructs = list\n constructIndex = 0\n\n if (list.length === 0) {\n return bogusState\n }\n\n return handleConstruct(list[constructIndex])\n }\n /**\n * Handle a single construct.\n *\n * @param {Construct} construct\n * @returns {State}\n */\n\n function handleConstruct(construct) {\n return start\n /** @type {State} */\n\n function start(code) {\n // To do: not needed to store if there is no bogus state, probably?\n // Currently doesn’t work because `inspect` in document does a check\n // w/o a bogus, which doesn’t make sense. But it does seem to help perf\n // by not storing.\n info = store()\n currentConstruct = construct\n\n if (!construct.partial) {\n context.currentConstruct = construct\n }\n\n if (\n construct.name &&\n context.parser.constructs.disable.null.includes(construct.name)\n ) {\n return nok(code)\n }\n\n return construct.tokenize.call(\n // If we do have fields, create an object w/ `context` as its\n // prototype.\n // This allows a “live binding”, which is needed for `interrupt`.\n fields ? Object.assign(Object.create(context), fields) : context,\n effects,\n ok,\n nok\n )(code)\n }\n }\n /** @type {State} */\n\n function ok(code) {\n consumed = true\n onreturn(currentConstruct, info)\n return returnState\n }\n /** @type {State} */\n\n function nok(code) {\n consumed = true\n info.restore()\n\n if (++constructIndex < listOfConstructs.length) {\n return handleConstruct(listOfConstructs[constructIndex])\n }\n\n return bogusState\n }\n }\n }\n /**\n * @param {Construct} construct\n * @param {number} from\n * @returns {void}\n */\n\n function addResult(construct, from) {\n if (construct.resolveAll && !resolveAllConstructs.includes(construct)) {\n resolveAllConstructs.push(construct)\n }\n\n if (construct.resolve) {\n splice(\n context.events,\n from,\n context.events.length - from,\n construct.resolve(context.events.slice(from), context)\n )\n }\n\n if (construct.resolveTo) {\n context.events = construct.resolveTo(context.events, context)\n }\n }\n /**\n * Store state.\n *\n * @returns {Info}\n */\n\n function store() {\n const startPoint = now()\n const startPrevious = context.previous\n const startCurrentConstruct = context.currentConstruct\n const startEventsIndex = context.events.length\n const startStack = Array.from(stack)\n return {\n restore,\n from: startEventsIndex\n }\n /**\n * Restore state.\n *\n * @returns {void}\n */\n\n function restore() {\n point = startPoint\n context.previous = startPrevious\n context.currentConstruct = startCurrentConstruct\n context.events.length = startEventsIndex\n stack = startStack\n accountForPotentialSkip()\n }\n }\n /**\n * Move the current point a bit forward in the line when it’s on a column\n * skip.\n *\n * @returns {void}\n */\n\n function accountForPotentialSkip() {\n if (point.line in columnStart && point.column < 2) {\n point.column = columnStart[point.line]\n point.offset += columnStart[point.line] - 1\n }\n }\n}\n/**\n * Get the chunks from a slice of chunks in the range of a token.\n *\n * @param {Chunk[]} chunks\n * @param {Pick} token\n * @returns {Chunk[]}\n */\n\nfunction sliceChunks(chunks, token) {\n const startIndex = token.start._index\n const startBufferIndex = token.start._bufferIndex\n const endIndex = token.end._index\n const endBufferIndex = token.end._bufferIndex\n /** @type {Chunk[]} */\n\n let view\n\n if (startIndex === endIndex) {\n // @ts-expect-error `_bufferIndex` is used on string chunks.\n view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)]\n } else {\n view = chunks.slice(startIndex, endIndex)\n\n if (startBufferIndex > -1) {\n // @ts-expect-error `_bufferIndex` is used on string chunks.\n view[0] = view[0].slice(startBufferIndex)\n }\n\n if (endBufferIndex > 0) {\n // @ts-expect-error `_bufferIndex` is used on string chunks.\n view.push(chunks[endIndex].slice(0, endBufferIndex))\n }\n }\n\n return view\n}\n/**\n * Get the string value of a slice of chunks.\n *\n * @param {Chunk[]} chunks\n * @param {boolean} [expandTabs=false]\n * @returns {string}\n */\n\nfunction serializeChunks(chunks, expandTabs) {\n let index = -1\n /** @type {string[]} */\n\n const result = []\n /** @type {boolean|undefined} */\n\n let atTab\n\n while (++index < chunks.length) {\n const chunk = chunks[index]\n /** @type {string} */\n\n let value\n\n if (typeof chunk === 'string') {\n value = chunk\n } else\n switch (chunk) {\n case -5: {\n value = '\\r'\n break\n }\n\n case -4: {\n value = '\\n'\n break\n }\n\n case -3: {\n value = '\\r' + '\\n'\n break\n }\n\n case -2: {\n value = expandTabs ? ' ' : '\\t'\n break\n }\n\n case -1: {\n if (!expandTabs && atTab) continue\n value = ' '\n break\n }\n\n default: {\n // Currently only replacement character.\n value = String.fromCharCode(chunk)\n }\n }\n\n atTab = chunk === -2\n result.push(value)\n }\n\n return result.join('')\n}\n","/**\n * @typedef {import('micromark-util-types').Extension} Extension\n */\nimport {\n attention,\n autolink,\n blockQuote,\n characterEscape,\n characterReference,\n codeFenced,\n codeIndented,\n codeText,\n definition,\n hardBreakEscape,\n headingAtx,\n htmlFlow,\n htmlText,\n labelEnd,\n labelStartImage,\n labelStartLink,\n lineEnding,\n list,\n setextUnderline,\n thematicBreak\n} from 'micromark-core-commonmark'\nimport {resolver as resolveText} from './initialize/text.js'\n/** @type {Extension['document']} */\n\nexport const document = {\n [42]: list,\n [43]: list,\n [45]: list,\n [48]: list,\n [49]: list,\n [50]: list,\n [51]: list,\n [52]: list,\n [53]: list,\n [54]: list,\n [55]: list,\n [56]: list,\n [57]: list,\n [62]: blockQuote\n}\n/** @type {Extension['contentInitial']} */\n\nexport const contentInitial = {\n [91]: definition\n}\n/** @type {Extension['flowInitial']} */\n\nexport const flowInitial = {\n [-2]: codeIndented,\n [-1]: codeIndented,\n [32]: codeIndented\n}\n/** @type {Extension['flow']} */\n\nexport const flow = {\n [35]: headingAtx,\n [42]: thematicBreak,\n [45]: [setextUnderline, thematicBreak],\n [60]: htmlFlow,\n [61]: setextUnderline,\n [95]: thematicBreak,\n [96]: codeFenced,\n [126]: codeFenced\n}\n/** @type {Extension['string']} */\n\nexport const string = {\n [38]: characterReference,\n [92]: characterEscape\n}\n/** @type {Extension['text']} */\n\nexport const text = {\n [-5]: lineEnding,\n [-4]: lineEnding,\n [-3]: lineEnding,\n [33]: labelStartImage,\n [38]: characterReference,\n [42]: attention,\n [60]: [autolink, htmlText],\n [91]: labelStartLink,\n [92]: [hardBreakEscape, characterEscape],\n [93]: labelEnd,\n [95]: attention,\n [96]: codeText\n}\n/** @type {Extension['insideSpan']} */\n\nexport const insideSpan = {\n null: [attention, resolveText]\n}\n/** @type {Extension['attentionMarkers']} */\n\nexport const attentionMarkers = {\n null: [42, 95]\n}\n/** @type {Extension['disable']} */\n\nexport const disable = {\n null: []\n}\n","/**\n * @typedef {import('micromark-util-types').InitialConstruct} InitialConstruct\n * @typedef {import('micromark-util-types').FullNormalizedExtension} FullNormalizedExtension\n * @typedef {import('micromark-util-types').ParseOptions} ParseOptions\n * @typedef {import('micromark-util-types').ParseContext} ParseContext\n * @typedef {import('micromark-util-types').Create} Create\n */\nimport {combineExtensions} from 'micromark-util-combine-extensions'\nimport {content} from './initialize/content.js'\nimport {document} from './initialize/document.js'\nimport {flow} from './initialize/flow.js'\nimport {text, string} from './initialize/text.js'\nimport {createTokenizer} from './create-tokenizer.js'\nimport * as defaultConstructs from './constructs.js'\n/**\n * @param {ParseOptions} [options]\n * @returns {ParseContext}\n */\n\nexport function parse(options = {}) {\n /** @type {FullNormalizedExtension} */\n // @ts-expect-error `defaultConstructs` is full, so the result will be too.\n const constructs = combineExtensions(\n // @ts-expect-error Same as above.\n [defaultConstructs].concat(options.extensions || [])\n )\n /** @type {ParseContext} */\n\n const parser = {\n defined: [],\n lazy: {},\n constructs,\n content: create(content),\n document: create(document),\n flow: create(flow),\n string: create(string),\n text: create(text)\n }\n return parser\n /**\n * @param {InitialConstruct} initial\n */\n\n function create(initial) {\n return creator\n /** @type {Create} */\n\n function creator(from) {\n return createTokenizer(parser, initial, from)\n }\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Encoding} Encoding\n * @typedef {import('micromark-util-types').Value} Value\n * @typedef {import('micromark-util-types').Chunk} Chunk\n * @typedef {import('micromark-util-types').Code} Code\n */\n\n/**\n * @callback Preprocessor\n * @param {Value} value\n * @param {Encoding} [encoding]\n * @param {boolean} [end=false]\n * @returns {Chunk[]}\n */\nconst search = /[\\0\\t\\n\\r]/g\n/**\n * @returns {Preprocessor}\n */\n\nexport function preprocess() {\n let column = 1\n let buffer = ''\n /** @type {boolean|undefined} */\n\n let start = true\n /** @type {boolean|undefined} */\n\n let atCarriageReturn\n return preprocessor\n /** @type {Preprocessor} */\n\n function preprocessor(value, encoding, end) {\n /** @type {Chunk[]} */\n const chunks = []\n /** @type {RegExpMatchArray|null} */\n\n let match\n /** @type {number} */\n\n let next\n /** @type {number} */\n\n let startPosition\n /** @type {number} */\n\n let endPosition\n /** @type {Code} */\n\n let code // @ts-expect-error `Buffer` does allow an encoding.\n\n value = buffer + value.toString(encoding)\n startPosition = 0\n buffer = ''\n\n if (start) {\n if (value.charCodeAt(0) === 65279) {\n startPosition++\n }\n\n start = undefined\n }\n\n while (startPosition < value.length) {\n search.lastIndex = startPosition\n match = search.exec(value)\n endPosition =\n match && match.index !== undefined ? match.index : value.length\n code = value.charCodeAt(endPosition)\n\n if (!match) {\n buffer = value.slice(startPosition)\n break\n }\n\n if (code === 10 && startPosition === endPosition && atCarriageReturn) {\n chunks.push(-3)\n atCarriageReturn = undefined\n } else {\n if (atCarriageReturn) {\n chunks.push(-5)\n atCarriageReturn = undefined\n }\n\n if (startPosition < endPosition) {\n chunks.push(value.slice(startPosition, endPosition))\n column += endPosition - startPosition\n }\n\n switch (code) {\n case 0: {\n chunks.push(65533)\n column++\n break\n }\n\n case 9: {\n next = Math.ceil(column / 4) * 4\n chunks.push(-2)\n\n while (column++ < next) chunks.push(-1)\n\n break\n }\n\n case 10: {\n chunks.push(-4)\n column = 1\n break\n }\n\n default: {\n atCarriageReturn = true\n column = 1\n }\n }\n }\n\n startPosition = endPosition + 1\n }\n\n if (end) {\n if (atCarriageReturn) chunks.push(-5)\n if (buffer) chunks.push(buffer)\n chunks.push(null)\n }\n\n return chunks\n }\n}\n","/**\n * Turn the number (in string form as either hexa- or plain decimal) coming from\n * a numeric character reference into a character.\n *\n * @param {string} value\n * Value to decode.\n * @param {number} base\n * Numeric base.\n * @returns {string}\n */\nexport function decodeNumericCharacterReference(value, base) {\n const code = Number.parseInt(value, base)\n\n if (\n // C0 except for HT, LF, FF, CR, space\n code < 9 ||\n code === 11 ||\n (code > 13 && code < 32) || // Control character (DEL) of the basic block and C1 controls.\n (code > 126 && code < 160) || // Lone high surrogates and low surrogates.\n (code > 55295 && code < 57344) || // Noncharacters.\n (code > 64975 && code < 65008) ||\n (code & 65535) === 65535 ||\n (code & 65535) === 65534 || // Out of range\n code > 1114111\n ) {\n return '\\uFFFD'\n }\n\n return String.fromCharCode(code)\n}\n","import {decodeNamedCharacterReference} from 'decode-named-character-reference'\nimport {decodeNumericCharacterReference} from 'micromark-util-decode-numeric-character-reference'\nconst characterEscapeOrReference =\n /\\\\([!-/:-@[-`{-~])|&(#(?:\\d{1,7}|x[\\da-f]{1,6})|[\\da-z]{1,31});/gi\n/**\n * Utility to decode markdown strings (which occur in places such as fenced\n * code info strings, destinations, labels, and titles).\n * The “string” content type allows character escapes and -references.\n * This decodes those.\n *\n * @param {string} value\n * @returns {string}\n */\n\nexport function decodeString(value) {\n return value.replace(characterEscapeOrReference, decode)\n}\n/**\n * @param {string} $0\n * @param {string} $1\n * @param {string} $2\n * @returns {string}\n */\n\nfunction decode($0, $1, $2) {\n if ($1) {\n // Escape.\n return $1\n } // Reference.\n\n const head = $2.charCodeAt(0)\n\n if (head === 35) {\n const head = $2.charCodeAt(1)\n const hex = head === 120 || head === 88\n return decodeNumericCharacterReference($2.slice(hex ? 2 : 1), hex ? 16 : 10)\n }\n\n return decodeNamedCharacterReference($2) || $0\n}\n","/**\n * @typedef {import('micromark-util-types').Encoding} Encoding\n * @typedef {import('micromark-util-types').Event} Event\n * @typedef {import('micromark-util-types').ParseOptions} ParseOptions\n * @typedef {import('micromark-util-types').Token} Token\n * @typedef {import('micromark-util-types').TokenizeContext} TokenizeContext\n * @typedef {import('micromark-util-types').Value} Value\n * @typedef {import('unist').Parent} UnistParent\n * @typedef {import('unist').Point} Point\n * @typedef {import('mdast').PhrasingContent} PhrasingContent\n * @typedef {import('mdast').Content} Content\n * @typedef {Root|Content} Node\n * @typedef {Extract} Parent\n * @typedef {import('mdast').Break} Break\n * @typedef {import('mdast').Blockquote} Blockquote\n * @typedef {import('mdast').Code} Code\n * @typedef {import('mdast').Definition} Definition\n * @typedef {import('mdast').Emphasis} Emphasis\n * @typedef {import('mdast').Heading} Heading\n * @typedef {import('mdast').HTML} HTML\n * @typedef {import('mdast').Image} Image\n * @typedef {import('mdast').ImageReference} ImageReference\n * @typedef {import('mdast').InlineCode} InlineCode\n * @typedef {import('mdast').Link} Link\n * @typedef {import('mdast').LinkReference} LinkReference\n * @typedef {import('mdast').List} List\n * @typedef {import('mdast').ListItem} ListItem\n * @typedef {import('mdast').Paragraph} Paragraph\n * @typedef {import('mdast').Root} Root\n * @typedef {import('mdast').Strong} Strong\n * @typedef {import('mdast').Text} Text\n * @typedef {import('mdast').ThematicBreak} ThematicBreak\n *\n * @typedef {UnistParent & {type: 'fragment', children: Array}} Fragment\n */\n\n/**\n * @typedef _CompileDataFields\n * @property {boolean|undefined} expectingFirstListItemValue\n * @property {boolean|undefined} flowCodeInside\n * @property {boolean|undefined} setextHeadingSlurpLineEnding\n * @property {boolean|undefined} atHardBreak\n * @property {'collapsed'|'full'} referenceType\n * @property {boolean|undefined} inReference\n * @property {'characterReferenceMarkerHexadecimal'|'characterReferenceMarkerNumeric'} characterReferenceType\n *\n * @typedef {Record & Partial<_CompileDataFields>} CompileData\n *\n * @typedef {(tree: Root) => Root|void} Transform\n * @typedef {(this: CompileContext, token: Token) => void} Handle\n * @typedef {Record} Handles\n * Token types mapping to handles\n * @typedef {Record|Array> & {canContainEols: Array, transforms: Array, enter: Handles, exit: Handles}} NormalizedExtension\n * @typedef {Partial} Extension\n * An mdast extension changes how markdown tokens are turned into mdast.\n *\n * @typedef {(this: Omit, left: Token|undefined, right: Token) => void} OnEnterError\n * @typedef {(this: Omit, left: Token, right: Token) => void} OnExitError\n *\n * @typedef CompileContext\n * mdast compiler context\n * @property {Array} stack\n * @property {Array<[Token, OnEnterError|undefined]>} tokenStack\n * @property {(key: string, value?: unknown) => void} setData\n * Set data into the key-value store.\n * @property {(key: K) => CompileData[K]} getData\n * Get data from the key-value store.\n * @property {(this: CompileContext) => void} buffer\n * Capture some of the output data.\n * @property {(this: CompileContext) => string} resume\n * Stop capturing and access the output data.\n * @property {(this: CompileContext, node: N, token: Token, onError?: OnEnterError) => N} enter\n * Enter a token.\n * @property {(this: CompileContext, token: Token, onError?: OnExitError) => Node} exit\n * Exit a token.\n * @property {TokenizeContext['sliceSerialize']} sliceSerialize\n * Get the string value of a token.\n * @property {NormalizedExtension} config\n * Configuration.\n *\n * @typedef {{mdastExtensions?: Array>}} FromMarkdownOptions\n * @typedef {ParseOptions & FromMarkdownOptions} Options\n */\nimport {toString} from 'mdast-util-to-string'\nimport {parse} from 'micromark/lib/parse.js'\nimport {preprocess} from 'micromark/lib/preprocess.js'\nimport {postprocess} from 'micromark/lib/postprocess.js'\nimport {decodeNumericCharacterReference} from 'micromark-util-decode-numeric-character-reference'\nimport {decodeString} from 'micromark-util-decode-string'\nimport {normalizeIdentifier} from 'micromark-util-normalize-identifier'\nimport {decodeNamedCharacterReference} from 'decode-named-character-reference'\nimport {stringifyPosition} from 'unist-util-stringify-position'\nconst own = {}.hasOwnProperty\n/**\n * @param value Markdown to parse (`string` or `Buffer`).\n * @param [encoding] Character encoding to understand `value` as when it’s a `Buffer` (`string`, default: `'utf8'`).\n * @param [options] Configuration\n */\n\nexport const fromMarkdown =\n /**\n * @type {(\n * ((value: Value, encoding: Encoding, options?: Options) => Root) &\n * ((value: Value, options?: Options) => Root)\n * )}\n */\n\n /**\n * @param {Value} value\n * @param {Encoding} [encoding]\n * @param {Options} [options]\n * @returns {Root}\n */\n function (value, encoding, options) {\n if (typeof encoding !== 'string') {\n options = encoding\n encoding = undefined\n }\n\n return compiler(options)(\n postprocess(\n parse(options).document().write(preprocess()(value, encoding, true))\n )\n )\n }\n/**\n * Note this compiler only understand complete buffering, not streaming.\n *\n * @param {Options} [options]\n */\n\nfunction compiler(options = {}) {\n /** @type {NormalizedExtension} */\n // @ts-expect-error: our base has all required fields, so the result will too.\n const config = configure(\n {\n transforms: [],\n canContainEols: [\n 'emphasis',\n 'fragment',\n 'heading',\n 'paragraph',\n 'strong'\n ],\n enter: {\n autolink: opener(link),\n autolinkProtocol: onenterdata,\n autolinkEmail: onenterdata,\n atxHeading: opener(heading),\n blockQuote: opener(blockQuote),\n characterEscape: onenterdata,\n characterReference: onenterdata,\n codeFenced: opener(codeFlow),\n codeFencedFenceInfo: buffer,\n codeFencedFenceMeta: buffer,\n codeIndented: opener(codeFlow, buffer),\n codeText: opener(codeText, buffer),\n codeTextData: onenterdata,\n data: onenterdata,\n codeFlowValue: onenterdata,\n definition: opener(definition),\n definitionDestinationString: buffer,\n definitionLabelString: buffer,\n definitionTitleString: buffer,\n emphasis: opener(emphasis),\n hardBreakEscape: opener(hardBreak),\n hardBreakTrailing: opener(hardBreak),\n htmlFlow: opener(html, buffer),\n htmlFlowData: onenterdata,\n htmlText: opener(html, buffer),\n htmlTextData: onenterdata,\n image: opener(image),\n label: buffer,\n link: opener(link),\n listItem: opener(listItem),\n listItemValue: onenterlistitemvalue,\n listOrdered: opener(list, onenterlistordered),\n listUnordered: opener(list),\n paragraph: opener(paragraph),\n reference: onenterreference,\n referenceString: buffer,\n resourceDestinationString: buffer,\n resourceTitleString: buffer,\n setextHeading: opener(heading),\n strong: opener(strong),\n thematicBreak: opener(thematicBreak)\n },\n exit: {\n atxHeading: closer(),\n atxHeadingSequence: onexitatxheadingsequence,\n autolink: closer(),\n autolinkEmail: onexitautolinkemail,\n autolinkProtocol: onexitautolinkprotocol,\n blockQuote: closer(),\n characterEscapeValue: onexitdata,\n characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker,\n characterReferenceMarkerNumeric: onexitcharacterreferencemarker,\n characterReferenceValue: onexitcharacterreferencevalue,\n codeFenced: closer(onexitcodefenced),\n codeFencedFence: onexitcodefencedfence,\n codeFencedFenceInfo: onexitcodefencedfenceinfo,\n codeFencedFenceMeta: onexitcodefencedfencemeta,\n codeFlowValue: onexitdata,\n codeIndented: closer(onexitcodeindented),\n codeText: closer(onexitcodetext),\n codeTextData: onexitdata,\n data: onexitdata,\n definition: closer(),\n definitionDestinationString: onexitdefinitiondestinationstring,\n definitionLabelString: onexitdefinitionlabelstring,\n definitionTitleString: onexitdefinitiontitlestring,\n emphasis: closer(),\n hardBreakEscape: closer(onexithardbreak),\n hardBreakTrailing: closer(onexithardbreak),\n htmlFlow: closer(onexithtmlflow),\n htmlFlowData: onexitdata,\n htmlText: closer(onexithtmltext),\n htmlTextData: onexitdata,\n image: closer(onexitimage),\n label: onexitlabel,\n labelText: onexitlabeltext,\n lineEnding: onexitlineending,\n link: closer(onexitlink),\n listItem: closer(),\n listOrdered: closer(),\n listUnordered: closer(),\n paragraph: closer(),\n referenceString: onexitreferencestring,\n resourceDestinationString: onexitresourcedestinationstring,\n resourceTitleString: onexitresourcetitlestring,\n resource: onexitresource,\n setextHeading: closer(onexitsetextheading),\n setextHeadingLineSequence: onexitsetextheadinglinesequence,\n setextHeadingText: onexitsetextheadingtext,\n strong: closer(),\n thematicBreak: closer()\n }\n },\n options.mdastExtensions || []\n )\n /** @type {CompileData} */\n\n const data = {}\n return compile\n /**\n * @param {Array} events\n * @returns {Root}\n */\n\n function compile(events) {\n /** @type {Root} */\n let tree = {\n type: 'root',\n children: []\n }\n /** @type {CompileContext['stack']} */\n\n const stack = [tree]\n /** @type {CompileContext['tokenStack']} */\n\n const tokenStack = []\n /** @type {Array} */\n\n const listStack = []\n /** @type {Omit} */\n\n const context = {\n stack,\n tokenStack,\n config,\n enter,\n exit,\n buffer,\n resume,\n setData,\n getData\n }\n let index = -1\n\n while (++index < events.length) {\n // We preprocess lists to add `listItem` tokens, and to infer whether\n // items the list itself are spread out.\n if (\n events[index][1].type === 'listOrdered' ||\n events[index][1].type === 'listUnordered'\n ) {\n if (events[index][0] === 'enter') {\n listStack.push(index)\n } else {\n const tail = listStack.pop()\n index = prepareList(events, tail, index)\n }\n }\n }\n\n index = -1\n\n while (++index < events.length) {\n const handler = config[events[index][0]]\n\n if (own.call(handler, events[index][1].type)) {\n handler[events[index][1].type].call(\n Object.assign(\n {\n sliceSerialize: events[index][2].sliceSerialize\n },\n context\n ),\n events[index][1]\n )\n }\n }\n\n if (tokenStack.length > 0) {\n const tail = tokenStack[tokenStack.length - 1]\n const handler = tail[1] || defaultOnError\n handler.call(context, undefined, tail[0])\n } // Figure out `root` position.\n\n tree.position = {\n start: point(\n events.length > 0\n ? events[0][1].start\n : {\n line: 1,\n column: 1,\n offset: 0\n }\n ),\n end: point(\n events.length > 0\n ? events[events.length - 2][1].end\n : {\n line: 1,\n column: 1,\n offset: 0\n }\n )\n }\n index = -1\n\n while (++index < config.transforms.length) {\n tree = config.transforms[index](tree) || tree\n }\n\n return tree\n }\n /**\n * @param {Array} events\n * @param {number} start\n * @param {number} length\n * @returns {number}\n */\n\n function prepareList(events, start, length) {\n let index = start - 1\n let containerBalance = -1\n let listSpread = false\n /** @type {Token|undefined} */\n\n let listItem\n /** @type {number|undefined} */\n\n let lineIndex\n /** @type {number|undefined} */\n\n let firstBlankLineIndex\n /** @type {boolean|undefined} */\n\n let atMarker\n\n while (++index <= length) {\n const event = events[index]\n\n if (\n event[1].type === 'listUnordered' ||\n event[1].type === 'listOrdered' ||\n event[1].type === 'blockQuote'\n ) {\n if (event[0] === 'enter') {\n containerBalance++\n } else {\n containerBalance--\n }\n\n atMarker = undefined\n } else if (event[1].type === 'lineEndingBlank') {\n if (event[0] === 'enter') {\n if (\n listItem &&\n !atMarker &&\n !containerBalance &&\n !firstBlankLineIndex\n ) {\n firstBlankLineIndex = index\n }\n\n atMarker = undefined\n }\n } else if (\n event[1].type === 'linePrefix' ||\n event[1].type === 'listItemValue' ||\n event[1].type === 'listItemMarker' ||\n event[1].type === 'listItemPrefix' ||\n event[1].type === 'listItemPrefixWhitespace'\n ) {\n // Empty.\n } else {\n atMarker = undefined\n }\n\n if (\n (!containerBalance &&\n event[0] === 'enter' &&\n event[1].type === 'listItemPrefix') ||\n (containerBalance === -1 &&\n event[0] === 'exit' &&\n (event[1].type === 'listUnordered' ||\n event[1].type === 'listOrdered'))\n ) {\n if (listItem) {\n let tailIndex = index\n lineIndex = undefined\n\n while (tailIndex--) {\n const tailEvent = events[tailIndex]\n\n if (\n tailEvent[1].type === 'lineEnding' ||\n tailEvent[1].type === 'lineEndingBlank'\n ) {\n if (tailEvent[0] === 'exit') continue\n\n if (lineIndex) {\n events[lineIndex][1].type = 'lineEndingBlank'\n listSpread = true\n }\n\n tailEvent[1].type = 'lineEnding'\n lineIndex = tailIndex\n } else if (\n tailEvent[1].type === 'linePrefix' ||\n tailEvent[1].type === 'blockQuotePrefix' ||\n tailEvent[1].type === 'blockQuotePrefixWhitespace' ||\n tailEvent[1].type === 'blockQuoteMarker' ||\n tailEvent[1].type === 'listItemIndent'\n ) {\n // Empty\n } else {\n break\n }\n }\n\n if (\n firstBlankLineIndex &&\n (!lineIndex || firstBlankLineIndex < lineIndex)\n ) {\n // @ts-expect-error Patched.\n listItem._spread = true\n } // Fix position.\n\n listItem.end = Object.assign(\n {},\n lineIndex ? events[lineIndex][1].start : event[1].end\n )\n events.splice(lineIndex || index, 0, ['exit', listItem, event[2]])\n index++\n length++\n } // Create a new list item.\n\n if (event[1].type === 'listItemPrefix') {\n listItem = {\n type: 'listItem',\n // @ts-expect-error Patched\n _spread: false,\n start: Object.assign({}, event[1].start)\n } // @ts-expect-error: `listItem` is most definitely defined, TS...\n\n events.splice(index, 0, ['enter', listItem, event[2]])\n index++\n length++\n firstBlankLineIndex = undefined\n atMarker = true\n }\n }\n } // @ts-expect-error Patched.\n\n events[start][1]._spread = listSpread\n return length\n }\n /**\n * @type {CompileContext['setData']}\n * @param [value]\n */\n\n function setData(key, value) {\n data[key] = value\n }\n /**\n * @type {CompileContext['getData']}\n * @template {string} K\n * @param {K} key\n * @returns {CompileData[K]}\n */\n\n function getData(key) {\n return data[key]\n }\n /**\n * @param {Point} d\n * @returns {Point}\n */\n\n function point(d) {\n return {\n line: d.line,\n column: d.column,\n offset: d.offset\n }\n }\n /**\n * @param {(token: Token) => Node} create\n * @param {Handle} [and]\n * @returns {Handle}\n */\n\n function opener(create, and) {\n return open\n /**\n * @this {CompileContext}\n * @param {Token} token\n * @returns {void}\n */\n\n function open(token) {\n enter.call(this, create(token), token)\n if (and) and.call(this, token)\n }\n }\n /** @type {CompileContext['buffer']} */\n\n function buffer() {\n this.stack.push({\n type: 'fragment',\n children: []\n })\n }\n /**\n * @type {CompileContext['enter']}\n * @template {Node} N\n * @this {CompileContext}\n * @param {N} node\n * @param {Token} token\n * @param {OnEnterError} [errorHandler]\n * @returns {N}\n */\n\n function enter(node, token, errorHandler) {\n const parent = this.stack[this.stack.length - 1]\n // @ts-expect-error: Assume `Node` can exist as a child of `parent`.\n parent.children.push(node)\n this.stack.push(node)\n this.tokenStack.push([token, errorHandler]) // @ts-expect-error: `end` will be patched later.\n\n node.position = {\n start: point(token.start)\n }\n return node\n }\n /**\n * @param {Handle} [and]\n * @returns {Handle}\n */\n\n function closer(and) {\n return close\n /**\n * @this {CompileContext}\n * @param {Token} token\n * @returns {void}\n */\n\n function close(token) {\n if (and) and.call(this, token)\n exit.call(this, token)\n }\n }\n /**\n * @type {CompileContext['exit']}\n * @this {CompileContext}\n * @param {Token} token\n * @param {OnExitError} [onExitError]\n * @returns {Node}\n */\n\n function exit(token, onExitError) {\n const node = this.stack.pop()\n const open = this.tokenStack.pop()\n\n if (!open) {\n throw new Error(\n 'Cannot close `' +\n token.type +\n '` (' +\n stringifyPosition({\n start: token.start,\n end: token.end\n }) +\n '): it’s not open'\n )\n } else if (open[0].type !== token.type) {\n if (onExitError) {\n onExitError.call(this, token, open[0])\n } else {\n const handler = open[1] || defaultOnError\n handler.call(this, token, open[0])\n }\n }\n\n node.position.end = point(token.end)\n return node\n }\n /**\n * @this {CompileContext}\n * @returns {string}\n */\n\n function resume() {\n return toString(this.stack.pop())\n } //\n // Handlers.\n //\n\n /** @type {Handle} */\n\n function onenterlistordered() {\n setData('expectingFirstListItemValue', true)\n }\n /** @type {Handle} */\n\n function onenterlistitemvalue(token) {\n if (getData('expectingFirstListItemValue')) {\n const ancestor =\n /** @type {List} */\n this.stack[this.stack.length - 2]\n ancestor.start = Number.parseInt(this.sliceSerialize(token), 10)\n setData('expectingFirstListItemValue')\n }\n }\n /** @type {Handle} */\n\n function onexitcodefencedfenceinfo() {\n const data = this.resume()\n const node =\n /** @type {Code} */\n this.stack[this.stack.length - 1]\n node.lang = data\n }\n /** @type {Handle} */\n\n function onexitcodefencedfencemeta() {\n const data = this.resume()\n const node =\n /** @type {Code} */\n this.stack[this.stack.length - 1]\n node.meta = data\n }\n /** @type {Handle} */\n\n function onexitcodefencedfence() {\n // Exit if this is the closing fence.\n if (getData('flowCodeInside')) return\n this.buffer()\n setData('flowCodeInside', true)\n }\n /** @type {Handle} */\n\n function onexitcodefenced() {\n const data = this.resume()\n const node =\n /** @type {Code} */\n this.stack[this.stack.length - 1]\n node.value = data.replace(/^(\\r?\\n|\\r)|(\\r?\\n|\\r)$/g, '')\n setData('flowCodeInside')\n }\n /** @type {Handle} */\n\n function onexitcodeindented() {\n const data = this.resume()\n const node =\n /** @type {Code} */\n this.stack[this.stack.length - 1]\n node.value = data.replace(/(\\r?\\n|\\r)$/g, '')\n }\n /** @type {Handle} */\n\n function onexitdefinitionlabelstring(token) {\n // Discard label, use the source content instead.\n const label = this.resume()\n const node =\n /** @type {Definition} */\n this.stack[this.stack.length - 1]\n node.label = label\n node.identifier = normalizeIdentifier(\n this.sliceSerialize(token)\n ).toLowerCase()\n }\n /** @type {Handle} */\n\n function onexitdefinitiontitlestring() {\n const data = this.resume()\n const node =\n /** @type {Definition} */\n this.stack[this.stack.length - 1]\n node.title = data\n }\n /** @type {Handle} */\n\n function onexitdefinitiondestinationstring() {\n const data = this.resume()\n const node =\n /** @type {Definition} */\n this.stack[this.stack.length - 1]\n node.url = data\n }\n /** @type {Handle} */\n\n function onexitatxheadingsequence(token) {\n const node =\n /** @type {Heading} */\n this.stack[this.stack.length - 1]\n\n if (!node.depth) {\n const depth = this.sliceSerialize(token).length\n node.depth = depth\n }\n }\n /** @type {Handle} */\n\n function onexitsetextheadingtext() {\n setData('setextHeadingSlurpLineEnding', true)\n }\n /** @type {Handle} */\n\n function onexitsetextheadinglinesequence(token) {\n const node =\n /** @type {Heading} */\n this.stack[this.stack.length - 1]\n node.depth = this.sliceSerialize(token).charCodeAt(0) === 61 ? 1 : 2\n }\n /** @type {Handle} */\n\n function onexitsetextheading() {\n setData('setextHeadingSlurpLineEnding')\n }\n /** @type {Handle} */\n\n function onenterdata(token) {\n const parent =\n /** @type {Parent} */\n this.stack[this.stack.length - 1]\n /** @type {Node} */\n\n let tail = parent.children[parent.children.length - 1]\n\n if (!tail || tail.type !== 'text') {\n // Add a new text node.\n tail = text() // @ts-expect-error: we’ll add `end` later.\n\n tail.position = {\n start: point(token.start)\n } // @ts-expect-error: Assume `parent` accepts `text`.\n\n parent.children.push(tail)\n }\n\n this.stack.push(tail)\n }\n /** @type {Handle} */\n\n function onexitdata(token) {\n const tail = this.stack.pop()\n tail.value += this.sliceSerialize(token)\n tail.position.end = point(token.end)\n }\n /** @type {Handle} */\n\n function onexitlineending(token) {\n const context = this.stack[this.stack.length - 1]\n\n // If we’re at a hard break, include the line ending in there.\n if (getData('atHardBreak')) {\n const tail = context.children[context.children.length - 1]\n tail.position.end = point(token.end)\n setData('atHardBreak')\n return\n }\n\n if (\n !getData('setextHeadingSlurpLineEnding') &&\n config.canContainEols.includes(context.type)\n ) {\n onenterdata.call(this, token)\n onexitdata.call(this, token)\n }\n }\n /** @type {Handle} */\n\n function onexithardbreak() {\n setData('atHardBreak', true)\n }\n /** @type {Handle} */\n\n function onexithtmlflow() {\n const data = this.resume()\n const node =\n /** @type {HTML} */\n this.stack[this.stack.length - 1]\n node.value = data\n }\n /** @type {Handle} */\n\n function onexithtmltext() {\n const data = this.resume()\n const node =\n /** @type {HTML} */\n this.stack[this.stack.length - 1]\n node.value = data\n }\n /** @type {Handle} */\n\n function onexitcodetext() {\n const data = this.resume()\n const node =\n /** @type {InlineCode} */\n this.stack[this.stack.length - 1]\n node.value = data\n }\n /** @type {Handle} */\n\n function onexitlink() {\n const context =\n /** @type {Link & {identifier: string, label: string}} */\n this.stack[this.stack.length - 1] // To do: clean.\n\n if (getData('inReference')) {\n context.type += 'Reference' // @ts-expect-error: mutate.\n\n context.referenceType = getData('referenceType') || 'shortcut' // @ts-expect-error: mutate.\n\n delete context.url\n delete context.title\n } else {\n // @ts-expect-error: mutate.\n delete context.identifier // @ts-expect-error: mutate.\n\n delete context.label\n }\n\n setData('referenceType')\n }\n /** @type {Handle} */\n\n function onexitimage() {\n const context =\n /** @type {Image & {identifier: string, label: string}} */\n this.stack[this.stack.length - 1] // To do: clean.\n\n if (getData('inReference')) {\n context.type += 'Reference' // @ts-expect-error: mutate.\n\n context.referenceType = getData('referenceType') || 'shortcut' // @ts-expect-error: mutate.\n\n delete context.url\n delete context.title\n } else {\n // @ts-expect-error: mutate.\n delete context.identifier // @ts-expect-error: mutate.\n\n delete context.label\n }\n\n setData('referenceType')\n }\n /** @type {Handle} */\n\n function onexitlabeltext(token) {\n const ancestor =\n /** @type {(Link|Image) & {identifier: string, label: string}} */\n this.stack[this.stack.length - 2]\n const string = this.sliceSerialize(token)\n ancestor.label = decodeString(string)\n ancestor.identifier = normalizeIdentifier(string).toLowerCase()\n }\n /** @type {Handle} */\n\n function onexitlabel() {\n const fragment =\n /** @type {Fragment} */\n this.stack[this.stack.length - 1]\n const value = this.resume()\n const node =\n /** @type {(Link|Image) & {identifier: string, label: string}} */\n this.stack[this.stack.length - 1] // Assume a reference.\n\n setData('inReference', true)\n\n if (node.type === 'link') {\n // @ts-expect-error: Assume static phrasing content.\n node.children = fragment.children\n } else {\n node.alt = value\n }\n }\n /** @type {Handle} */\n\n function onexitresourcedestinationstring() {\n const data = this.resume()\n const node =\n /** @type {Link|Image} */\n this.stack[this.stack.length - 1]\n node.url = data\n }\n /** @type {Handle} */\n\n function onexitresourcetitlestring() {\n const data = this.resume()\n const node =\n /** @type {Link|Image} */\n this.stack[this.stack.length - 1]\n node.title = data\n }\n /** @type {Handle} */\n\n function onexitresource() {\n setData('inReference')\n }\n /** @type {Handle} */\n\n function onenterreference() {\n setData('referenceType', 'collapsed')\n }\n /** @type {Handle} */\n\n function onexitreferencestring(token) {\n const label = this.resume()\n const node =\n /** @type {LinkReference|ImageReference} */\n this.stack[this.stack.length - 1]\n node.label = label\n node.identifier = normalizeIdentifier(\n this.sliceSerialize(token)\n ).toLowerCase()\n setData('referenceType', 'full')\n }\n /** @type {Handle} */\n\n function onexitcharacterreferencemarker(token) {\n setData('characterReferenceType', token.type)\n }\n /** @type {Handle} */\n\n function onexitcharacterreferencevalue(token) {\n const data = this.sliceSerialize(token)\n const type = getData('characterReferenceType')\n /** @type {string} */\n\n let value\n\n if (type) {\n value = decodeNumericCharacterReference(\n data,\n type === 'characterReferenceMarkerNumeric' ? 10 : 16\n )\n setData('characterReferenceType')\n } else {\n // @ts-expect-error `decodeNamedCharacterReference` can return false for\n // invalid named character references, but everything we’ve tokenized is\n // valid.\n value = decodeNamedCharacterReference(data)\n }\n\n const tail = this.stack.pop()\n tail.value += value\n tail.position.end = point(token.end)\n }\n /** @type {Handle} */\n\n function onexitautolinkprotocol(token) {\n onexitdata.call(this, token)\n const node =\n /** @type {Link} */\n this.stack[this.stack.length - 1]\n node.url = this.sliceSerialize(token)\n }\n /** @type {Handle} */\n\n function onexitautolinkemail(token) {\n onexitdata.call(this, token)\n const node =\n /** @type {Link} */\n this.stack[this.stack.length - 1]\n node.url = 'mailto:' + this.sliceSerialize(token)\n } //\n // Creaters.\n //\n\n /** @returns {Blockquote} */\n\n function blockQuote() {\n return {\n type: 'blockquote',\n children: []\n }\n }\n /** @returns {Code} */\n\n function codeFlow() {\n return {\n type: 'code',\n lang: null,\n meta: null,\n value: ''\n }\n }\n /** @returns {InlineCode} */\n\n function codeText() {\n return {\n type: 'inlineCode',\n value: ''\n }\n }\n /** @returns {Definition} */\n\n function definition() {\n return {\n type: 'definition',\n identifier: '',\n label: null,\n title: null,\n url: ''\n }\n }\n /** @returns {Emphasis} */\n\n function emphasis() {\n return {\n type: 'emphasis',\n children: []\n }\n }\n /** @returns {Heading} */\n\n function heading() {\n // @ts-expect-error `depth` will be set later.\n return {\n type: 'heading',\n depth: undefined,\n children: []\n }\n }\n /** @returns {Break} */\n\n function hardBreak() {\n return {\n type: 'break'\n }\n }\n /** @returns {HTML} */\n\n function html() {\n return {\n type: 'html',\n value: ''\n }\n }\n /** @returns {Image} */\n\n function image() {\n return {\n type: 'image',\n title: null,\n url: '',\n alt: null\n }\n }\n /** @returns {Link} */\n\n function link() {\n return {\n type: 'link',\n title: null,\n url: '',\n children: []\n }\n }\n /**\n * @param {Token} token\n * @returns {List}\n */\n\n function list(token) {\n return {\n type: 'list',\n ordered: token.type === 'listOrdered',\n start: null,\n // @ts-expect-error Patched.\n spread: token._spread,\n children: []\n }\n }\n /**\n * @param {Token} token\n * @returns {ListItem}\n */\n\n function listItem(token) {\n return {\n type: 'listItem',\n // @ts-expect-error Patched.\n spread: token._spread,\n checked: null,\n children: []\n }\n }\n /** @returns {Paragraph} */\n\n function paragraph() {\n return {\n type: 'paragraph',\n children: []\n }\n }\n /** @returns {Strong} */\n\n function strong() {\n return {\n type: 'strong',\n children: []\n }\n }\n /** @returns {Text} */\n\n function text() {\n return {\n type: 'text',\n value: ''\n }\n }\n /** @returns {ThematicBreak} */\n\n function thematicBreak() {\n return {\n type: 'thematicBreak'\n }\n }\n}\n/**\n * @param {Extension} combined\n * @param {Array>} extensions\n * @returns {Extension}\n */\n\nfunction configure(combined, extensions) {\n let index = -1\n\n while (++index < extensions.length) {\n const value = extensions[index]\n\n if (Array.isArray(value)) {\n configure(combined, value)\n } else {\n extension(combined, value)\n }\n }\n\n return combined\n}\n/**\n * @param {Extension} combined\n * @param {Extension} extension\n * @returns {void}\n */\n\nfunction extension(combined, extension) {\n /** @type {string} */\n let key\n\n for (key in extension) {\n if (own.call(extension, key)) {\n const list = key === 'canContainEols' || key === 'transforms'\n const maybe = own.call(combined, key) ? combined[key] : undefined\n /* c8 ignore next */\n\n const left = maybe || (combined[key] = list ? [] : {})\n const right = extension[key]\n\n if (right) {\n if (list) {\n // @ts-expect-error: `left` is an array.\n combined[key] = [...left, ...right]\n } else {\n Object.assign(left, right)\n }\n }\n }\n }\n}\n/** @type {OnEnterError} */\n\nfunction defaultOnError(left, right) {\n if (left) {\n throw new Error(\n 'Cannot close `' +\n left.type +\n '` (' +\n stringifyPosition({\n start: left.start,\n end: left.end\n }) +\n '): a different token (`' +\n right.type +\n '`, ' +\n stringifyPosition({\n start: right.start,\n end: right.end\n }) +\n ') is open'\n )\n } else {\n throw new Error(\n 'Cannot close document, a token (`' +\n right.type +\n '`, ' +\n stringifyPosition({\n start: right.start,\n end: right.end\n }) +\n ') is still open'\n )\n }\n}\n","/**\n * @typedef {import('micromark-util-types').Event} Event\n */\nimport {subtokenize} from 'micromark-util-subtokenize'\n/**\n * @param {Event[]} events\n * @returns {Event[]}\n */\n\nexport function postprocess(events) {\n while (!subtokenize(events)) {\n // Empty\n }\n\n return events\n}\n","/**\n * @typedef {import('mdast').Root} Root\n * @typedef {import('mdast-util-from-markdown').Options} Options\n */\n\nimport {fromMarkdown} from 'mdast-util-from-markdown'\n\n/** @type {import('unified').Plugin<[Options?] | void[], string, Root>} */\nexport default function remarkParse(options) {\n /** @type {import('unified').ParserFunction} */\n const parser = (doc) => {\n // Assume options.\n const settings = /** @type {Options} */ (this.data('settings'))\n\n return fromMarkdown(\n doc,\n Object.assign({}, settings, options, {\n // Note: these options are not in the readme.\n // The goal is for them to be set by plugins on `data` instead of being\n // passed by users.\n extensions: this.data('micromarkExtensions') || [],\n mdastExtensions: this.data('fromMarkdownExtensions') || []\n })\n )\n }\n\n Object.assign(this, {Parser: parser})\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist').Literal} Literal\n * @typedef {Object.} Props\n * @typedef {Array.|string} ChildrenOrValue\n *\n * @typedef {(, C extends Node[]>(type: T, props: P, children: C) => {type: T, children: C} & P)} BuildParentWithProps\n * @typedef {(>(type: T, props: P, value: string) => {type: T, value: string} & P)} BuildLiteralWithProps\n * @typedef {(>(type: T, props: P) => {type: T} & P)} BuildVoidWithProps\n * @typedef {((type: T, children: C) => {type: T, children: C})} BuildParent\n * @typedef {((type: T, value: string) => {type: T, value: string})} BuildLiteral\n * @typedef {((type: T) => {type: T})} BuildVoid\n */\n\nexport var u = /**\n * @type {BuildVoid & BuildVoidWithProps & BuildLiteral & BuildLiteralWithProps & BuildParent & BuildParentWithProps}\n */ (\n /**\n * @param {string} type Type of node\n * @param {Props|ChildrenOrValue} [props] Additional properties for node (or `children` or `value`)\n * @param {ChildrenOrValue} [value] `children` or `value` of node\n * @returns {Node}\n */\n function (type, props, value) {\n /** @type {Node} */\n var node = {type: String(type)}\n\n if (\n (value === undefined || value === null) &&\n (typeof props === 'string' || Array.isArray(props))\n ) {\n value = props\n } else {\n Object.assign(node, props)\n }\n\n if (Array.isArray(value)) {\n node.children = value\n } else if (value !== undefined && value !== null) {\n node.value = String(value)\n }\n\n return node\n }\n)\n","/**\n * @typedef {import('mdast').Root|import('mdast').Parent['children'][number]} MdastNode\n * @typedef {import('./index.js').H} H\n * @typedef {import('./index.js').Handler} Handler\n * @typedef {import('./index.js').Content} Content\n */\n\nimport {u} from 'unist-builder'\n\nconst own = {}.hasOwnProperty\n\n/**\n * Transform an unknown node.\n * @type {Handler}\n * @param {MdastNode} node\n */\nfunction unknown(h, node) {\n const data = node.data || {}\n\n if (\n 'value' in node &&\n !(\n own.call(data, 'hName') ||\n own.call(data, 'hProperties') ||\n own.call(data, 'hChildren')\n )\n ) {\n return h.augment(node, u('text', node.value))\n }\n\n return h(node, 'div', all(h, node))\n}\n\n/**\n * @type {Handler}\n * @param {MdastNode} node\n */\nexport function one(h, node, parent) {\n const type = node && node.type\n /** @type {Handler} */\n let fn\n\n // Fail on non-nodes.\n if (!type) {\n throw new Error('Expected node, got `' + node + '`')\n }\n\n if (own.call(h.handlers, type)) {\n fn = h.handlers[type]\n } else if (h.passThrough && h.passThrough.includes(type)) {\n fn = returnNode\n } else {\n fn = h.unknownHandler\n }\n\n return (typeof fn === 'function' ? fn : unknown)(h, node, parent)\n}\n\n/**\n * @type {Handler}\n * @param {MdastNode} node\n */\nfunction returnNode(h, node) {\n // @ts-expect-error: Pass through custom node.\n return 'children' in node ? {...node, children: all(h, node)} : node\n}\n\n/**\n * @param {H} h\n * @param {MdastNode} parent\n */\nexport function all(h, parent) {\n /** @type {Array.} */\n const values = []\n\n if ('children' in parent) {\n const nodes = parent.children\n let index = -1\n\n while (++index < nodes.length) {\n const result = one(h, nodes[index], parent)\n\n if (result) {\n if (index && nodes[index - 1].type === 'break') {\n if (!Array.isArray(result) && result.type === 'text') {\n result.value = result.value.replace(/^\\s+/, '')\n }\n\n if (!Array.isArray(result) && result.type === 'element') {\n const head = result.children[0]\n\n if (head && head.type === 'text') {\n head.value = head.value.replace(/^\\s+/, '')\n }\n }\n }\n\n if (Array.isArray(result)) {\n values.push(...result)\n } else {\n values.push(result)\n }\n }\n }\n }\n\n return values\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n *\n * @typedef {string} Type\n * @typedef {Object} Props\n *\n * @typedef {null|undefined|Type|Props|TestFunctionAnything|Array.} Test\n */\n\n/**\n * Check if a node passes a test\n *\n * @callback TestFunctionAnything\n * @param {Node} node\n * @param {number|null|undefined} [index]\n * @param {Parent|null|undefined} [parent]\n * @returns {boolean|void}\n */\n\n/**\n * Check if a node passes a certain node test\n *\n * @template {Node} X\n * @callback TestFunctionPredicate\n * @param {Node} node\n * @param {number|null|undefined} [index]\n * @param {Parent|null|undefined} [parent]\n * @returns {node is X}\n */\n\n/**\n * @callback AssertAnything\n * @param {unknown} [node]\n * @param {number|null|undefined} [index]\n * @param {Parent|null|undefined} [parent]\n * @returns {boolean}\n */\n\n/**\n * Check if a node passes a certain node test\n *\n * @template {Node} Y\n * @callback AssertPredicate\n * @param {unknown} [node]\n * @param {number|null|undefined} [index]\n * @param {Parent|null|undefined} [parent]\n * @returns {node is Y}\n */\n\nexport const is =\n /**\n * Check if a node passes a test.\n * When a `parent` node is known the `index` of node should also be given.\n *\n * @type {(\n * ((node: unknown, test: T['type']|Partial|TestFunctionPredicate|Array.|TestFunctionPredicate>, index?: number|null|undefined, parent?: Parent|null|undefined, context?: unknown) => node is T) &\n * ((node?: unknown, test?: Test, index?: number|null|undefined, parent?: Parent|null|undefined, context?: unknown) => boolean)\n * )}\n */\n (\n /**\n * Check if a node passes a test.\n * When a `parent` node is known the `index` of node should also be given.\n *\n * @param {unknown} [node] Node to check\n * @param {Test} [test]\n * When nullish, checks if `node` is a `Node`.\n * When `string`, works like passing `function (node) {return node.type === test}`.\n * When `function` checks if function passed the node is true.\n * When `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * When `array`, checks any one of the subtests pass.\n * @param {number|null|undefined} [index] Position of `node` in `parent`\n * @param {Parent|null|undefined} [parent] Parent of `node`\n * @param {unknown} [context] Context object to invoke `test` with\n * @returns {boolean} Whether test passed and `node` is a `Node` (object with `type` set to non-empty `string`).\n */\n // eslint-disable-next-line max-params\n function is(node, test, index, parent, context) {\n const check = convert(test)\n\n if (\n index !== undefined &&\n index !== null &&\n (typeof index !== 'number' ||\n index < 0 ||\n index === Number.POSITIVE_INFINITY)\n ) {\n throw new Error('Expected positive finite index')\n }\n\n if (\n parent !== undefined &&\n parent !== null &&\n (!is(parent) || !parent.children)\n ) {\n throw new Error('Expected parent node')\n }\n\n if (\n (parent === undefined || parent === null) !==\n (index === undefined || index === null)\n ) {\n throw new Error('Expected both parent and index')\n }\n\n // @ts-expect-error Looks like a node.\n return node && node.type && typeof node.type === 'string'\n ? Boolean(check.call(context, node, index, parent))\n : false\n }\n )\n\nexport const convert =\n /**\n * @type {(\n * ((test: T['type']|Partial|TestFunctionPredicate) => AssertPredicate) &\n * ((test?: Test) => AssertAnything)\n * )}\n */\n (\n /**\n * Generate an assertion from a check.\n * @param {Test} [test]\n * When nullish, checks if `node` is a `Node`.\n * When `string`, works like passing `function (node) {return node.type === test}`.\n * When `function` checks if function passed the node is true.\n * When `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * When `array`, checks any one of the subtests pass.\n * @returns {AssertAnything}\n */\n function (test) {\n if (test === undefined || test === null) {\n return ok\n }\n\n if (typeof test === 'string') {\n return typeFactory(test)\n }\n\n if (typeof test === 'object') {\n return Array.isArray(test) ? anyFactory(test) : propsFactory(test)\n }\n\n if (typeof test === 'function') {\n return castFactory(test)\n }\n\n throw new Error('Expected function, string, or object as test')\n }\n )\n/**\n * @param {Array.} tests\n * @returns {AssertAnything}\n */\nfunction anyFactory(tests) {\n /** @type {Array.} */\n const checks = []\n let index = -1\n\n while (++index < tests.length) {\n checks[index] = convert(tests[index])\n }\n\n return castFactory(any)\n\n /**\n * @this {unknown}\n * @param {unknown[]} parameters\n * @returns {boolean}\n */\n function any(...parameters) {\n let index = -1\n\n while (++index < checks.length) {\n if (checks[index].call(this, ...parameters)) return true\n }\n\n return false\n }\n}\n\n/**\n * Utility to assert each property in `test` is represented in `node`, and each\n * values are strictly equal.\n *\n * @param {Props} check\n * @returns {AssertAnything}\n */\nfunction propsFactory(check) {\n return castFactory(all)\n\n /**\n * @param {Node} node\n * @returns {boolean}\n */\n function all(node) {\n /** @type {string} */\n let key\n\n for (key in check) {\n // @ts-expect-error: hush, it sure works as an index.\n if (node[key] !== check[key]) return false\n }\n\n return true\n }\n}\n\n/**\n * Utility to convert a string into a function which checks a given node’s type\n * for said string.\n *\n * @param {Type} check\n * @returns {AssertAnything}\n */\nfunction typeFactory(check) {\n return castFactory(type)\n\n /**\n * @param {Node} node\n */\n function type(node) {\n return node && node.type === check\n }\n}\n\n/**\n * Utility to convert a string into a function which checks a given node’s type\n * for said string.\n * @param {TestFunctionAnything} check\n * @returns {AssertAnything}\n */\nfunction castFactory(check) {\n return assertion\n\n /**\n * @this {unknown}\n * @param {Array.} parameters\n * @returns {boolean}\n */\n function assertion(...parameters) {\n // @ts-expect-error: spreading is fine.\n return Boolean(check.call(this, ...parameters))\n }\n}\n\n// Utility to return true.\nfunction ok() {\n return true\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n * @typedef {import('./complex-types').Action} Action\n * @typedef {import('./complex-types').Index} Index\n * @typedef {import('./complex-types').ActionTuple} ActionTuple\n * @typedef {import('./complex-types').VisitorResult} VisitorResult\n * @typedef {import('./complex-types').Visitor} Visitor\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from './color.js'\n\n/**\n * Continue traversing as normal\n */\nexport const CONTINUE = true\n/**\n * Do not traverse this node’s children\n */\nexport const SKIP = 'skip'\n/**\n * Stop traversing immediately\n */\nexport const EXIT = false\n\n/**\n * Visit children of tree which pass a test\n *\n * @param tree Abstract syntax tree to walk\n * @param test Test node, optional\n * @param visitor Function to run for each node\n * @param reverse Visit the tree in reverse order, defaults to false\n */\nexport const visitParents =\n /**\n * @type {(\n * ((tree: Tree, test: Check, visitor: import('./complex-types').BuildVisitor, reverse?: boolean) => void) &\n * ((tree: Tree, visitor: import('./complex-types').BuildVisitor, reverse?: boolean) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {import('./complex-types').Visitor} visitor\n * @param {boolean} [reverse]\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-expect-error no visitor given, so `visitor` is test.\n visitor = test\n test = null\n }\n\n const is = convert(test)\n const step = reverse ? -1 : 1\n\n factory(tree, null, [])()\n\n /**\n * @param {Node} node\n * @param {number?} index\n * @param {Array.} parents\n */\n function factory(node, index, parents) {\n /** @type {Object.} */\n // @ts-expect-error: hush\n const value = typeof node === 'object' && node !== null ? node : {}\n /** @type {string|undefined} */\n let name\n\n if (typeof value.type === 'string') {\n name =\n typeof value.tagName === 'string'\n ? value.tagName\n : typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' +\n color(value.type + (name ? '<' + name + '>' : '')) +\n ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {ActionTuple} */\n let result = []\n /** @type {ActionTuple} */\n let subresult\n /** @type {number} */\n let offset\n /** @type {Array.} */\n let grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || null)) {\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n // @ts-expect-error looks like a parent.\n if (node.children && result[0] !== SKIP) {\n // @ts-expect-error looks like a parent.\n offset = (reverse ? node.children.length : -1) + step\n // @ts-expect-error looks like a parent.\n grandparents = parents.concat(node)\n\n // @ts-expect-error looks like a parent.\n while (offset > -1 && offset < node.children.length) {\n // @ts-expect-error looks like a parent.\n subresult = factory(node.children[offset], offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n\n return result\n }\n }\n }\n )\n\n/**\n * @param {VisitorResult} value\n * @returns {ActionTuple}\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return [value]\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult\n * @typedef {import('./complex-types').Visitor} Visitor\n */\n\nimport {visitParents, CONTINUE, SKIP, EXIT} from 'unist-util-visit-parents'\n\nexport {CONTINUE, SKIP, EXIT}\n\n/**\n * Visit children of tree which pass a test\n *\n * @param tree Abstract syntax tree to walk\n * @param test Test, optional\n * @param visitor Function to run for each node\n * @param reverse Fisit the tree in reverse, defaults to false\n */\nexport const visit =\n /**\n * @type {(\n * ((tree: Tree, test: Check, visitor: import('./complex-types').BuildVisitor, reverse?: boolean) => void) &\n * ((tree: Tree, visitor: import('./complex-types').BuildVisitor, reverse?: boolean) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {import('./complex-types').Visitor} visitor\n * @param {boolean} [reverse]\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n visitor = test\n test = null\n }\n\n visitParents(tree, test, overload, reverse)\n\n /**\n * @param {Node} node\n * @param {Array.} parents\n */\n function overload(node, parents) {\n const parent = parents[parents.length - 1]\n return visitor(\n node,\n parent ? parent.children.indexOf(node) : null,\n parent\n )\n }\n }\n )\n","/**\n * @typedef {import('unist').Position} Position\n * @typedef {import('unist').Point} Point\n *\n * @typedef {Partial} PointLike\n *\n * @typedef {Object} PositionLike\n * @property {PointLike} [start]\n * @property {PointLike} [end]\n *\n * @typedef {Object} NodeLike\n * @property {PositionLike} [position]\n */\n\nexport var pointStart = point('start')\nexport var pointEnd = point('end')\n\n/**\n * Get the positional info of `node`.\n *\n * @param {NodeLike} [node]\n * @returns {Position}\n */\nexport function position(node) {\n return {start: pointStart(node), end: pointEnd(node)}\n}\n\n/**\n * Get the positional info of `node`.\n *\n * @param {'start'|'end'} type\n */\nfunction point(type) {\n return point\n\n /**\n * Get the positional info of `node`.\n *\n * @param {NodeLike} [node]\n * @returns {Point}\n */\n function point(node) {\n /** @type {Point} */\n // @ts-ignore looks like a point\n var point = (node && node.position && node.position[type]) || {}\n\n return {\n line: point.line || null,\n column: point.column || null,\n offset: point.offset > -1 ? point.offset : null\n }\n }\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n */\n\n/**\n * @typedef {CONTINUE|SKIP|EXIT} Action Union of the action types\n * @typedef {number} Index Move to the sibling at index next (after node itself is completely traversed). Useful if mutating the tree, such as removing the node the visitor is currently on, or any of its previous siblings (or next siblings, in case of reverse) Results less than 0 or greater than or equal to children.length stop traversing the parent\n * @typedef {[(Action|null|undefined|void)?, (Index|null|undefined)?]} ActionTuple List with one or two values, the first an action, the second an index.\n * @typedef {null|undefined|Action|Index|ActionTuple|void} VisitorResult Any value that can be returned from a visitor\n */\n\n/**\n * Invoked when a node (matching test, if given) is found.\n * Visitors are free to transform node.\n * They can also transform the parent of node (the last of ancestors).\n * Replacing node itself, if `SKIP` is not returned, still causes its descendants to be visited.\n * If adding or removing previous siblings (or next siblings, in case of reverse) of node,\n * visitor should return a new index (number) to specify the sibling to traverse after node is traversed.\n * Adding or removing next siblings of node (or previous siblings, in case of reverse)\n * is handled as expected without needing to return a new index.\n * Removing the children property of an ancestor still results in them being traversed.\n *\n * @template {Node} V\n * @callback Visitor\n * @param {V} node Found node\n * @param {Array.} ancestors Ancestors of node\n * @returns {VisitorResult}\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from './color.js'\n\n/**\n * Continue traversing as normal\n */\nexport const CONTINUE = true\n/**\n * Do not traverse this node’s children\n */\nexport const SKIP = 'skip'\n/**\n * Stop traversing immediately\n */\nexport const EXIT = false\n\nexport const visitParents =\n /**\n * @type {(\n * ((tree: Node, test: T['type']|Partial|import('unist-util-is').TestFunctionPredicate|Array.|import('unist-util-is').TestFunctionPredicate>, visitor: Visitor, reverse?: boolean) => void) &\n * ((tree: Node, test: Test, visitor: Visitor, reverse?: boolean) => void) &\n * ((tree: Node, visitor: Visitor, reverse?: boolean) => void)\n * )}\n */\n (\n /**\n * Visit children of tree which pass a test\n *\n * @param {Node} tree Abstract syntax tree to walk\n * @param {Test} test test Test node\n * @param {Visitor} visitor Function to run for each node\n * @param {boolean} [reverse] Fisit the tree in reverse, defaults to false\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-ignore no visitor given, so `visitor` is test.\n visitor = test\n test = null\n }\n\n var is = convert(test)\n var step = reverse ? -1 : 1\n\n factory(tree, null, [])()\n\n /**\n * @param {Node} node\n * @param {number?} index\n * @param {Array.} parents\n */\n function factory(node, index, parents) {\n /** @type {Object.} */\n var value = typeof node === 'object' && node !== null ? node : {}\n /** @type {string} */\n var name\n\n if (typeof value.type === 'string') {\n name =\n typeof value.tagName === 'string'\n ? value.tagName\n : typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' +\n color(value.type + (name ? '<' + name + '>' : '')) +\n ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {ActionTuple} */\n var result = []\n /** @type {ActionTuple} */\n var subresult\n /** @type {number} */\n var offset\n /** @type {Array.} */\n var grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || null)) {\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n if (node.children && result[0] !== SKIP) {\n // @ts-ignore looks like a parent.\n offset = (reverse ? node.children.length : -1) + step\n // @ts-ignore looks like a parent.\n grandparents = parents.concat(node)\n\n // @ts-ignore looks like a parent.\n while (offset > -1 && offset < node.children.length) {\n subresult = factory(node.children[offset], offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n\n return result\n }\n }\n }\n )\n\n/**\n * @param {VisitorResult} value\n * @returns {ActionTuple}\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return [value]\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult\n */\n\n/**\n * Invoked when a node (matching test, if given) is found.\n * Visitors are free to transform node.\n * They can also transform the parent of node (the last of ancestors).\n * Replacing node itself, if `SKIP` is not returned, still causes its descendants to be visited.\n * If adding or removing previous siblings (or next siblings, in case of reverse) of node,\n * visitor should return a new index (number) to specify the sibling to traverse after node is traversed.\n * Adding or removing next siblings of node (or previous siblings, in case of reverse)\n * is handled as expected without needing to return a new index.\n * Removing the children property of an ancestor still results in them being traversed.\n *\n * @template {Node} V\n * @callback Visitor\n * @param {V} node Found node\n * @param {number|null} index Position of `node` in `parent`\n * @param {Parent|null} parent Parent of `node`\n * @returns {VisitorResult}\n */\n\nimport {visitParents, CONTINUE, SKIP, EXIT} from 'unist-util-visit-parents'\n\nexport {CONTINUE, SKIP, EXIT}\n\nexport const visit =\n /**\n * @type {(\n * ((tree: Node, test: T['type']|Partial|import('unist-util-is').TestFunctionPredicate|Array.|import('unist-util-is').TestFunctionPredicate>, visitor: Visitor, reverse?: boolean) => void) &\n * ((tree: Node, test: Test, visitor: Visitor, reverse?: boolean) => void) &\n * ((tree: Node, visitor: Visitor, reverse?: boolean) => void)\n * )}\n */\n (\n /**\n * Visit children of tree which pass a test\n *\n * @param {Node} tree Abstract syntax tree to walk\n * @param {Test} test test Test node\n * @param {Visitor} visitor Function to run for each node\n * @param {boolean} [reverse] Fisit the tree in reverse, defaults to false\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n visitor = test\n test = null\n }\n\n visitParents(tree, test, overload, reverse)\n\n /**\n * @param {Node} node\n * @param {Array.} parents\n */\n function overload(node, parents) {\n var parent = parents[parents.length - 1]\n return visitor(\n node,\n parent ? parent.children.indexOf(node) : null,\n parent\n )\n }\n }\n )\n","/**\n * @typedef {import('mdast').Root|import('mdast').Content} Node\n * @typedef {import('mdast').Definition} Definition\n * @typedef {import('unist-util-visit').Visitor} DefinitionVisitor\n */\n\nimport {visit} from 'unist-util-visit'\n\nconst own = {}.hasOwnProperty\n\n/**\n *\n * @param {Node} node\n */\nexport function definitions(node) {\n /** @type {Object.} */\n const cache = Object.create(null)\n\n if (!node || !node.type) {\n throw new Error('mdast-util-definitions expected node')\n }\n\n visit(node, 'definition', ondefinition)\n\n return getDefinition\n\n /** @type {DefinitionVisitor} */\n function ondefinition(definition) {\n const id = clean(definition.identifier)\n if (id && !own.call(cache, id)) {\n cache[id] = definition\n }\n }\n\n /**\n * Get a node from the bound definition-cache.\n *\n * @param {string} identifier\n * @returns {Definition|null}\n */\n function getDefinition(identifier) {\n const id = clean(identifier)\n return id && own.call(cache, id) ? cache[id] : null\n }\n}\n\n/**\n * @param {string} [value]\n * @returns {string}\n */\nfunction clean(value) {\n return String(value || '').toUpperCase()\n}\n","/**\n * @typedef {import('mdast').ThematicBreak} ThematicBreak\n * @typedef {import('hast').Element} Element\n * @typedef {import('../index.js').Handler} Handler\n */\n\n/**\n * @type {Handler}\n * @param {ThematicBreak} [node]\n * @returns {Element}\n */\nexport function thematicBreak(h, node) {\n return h(node, 'hr')\n}\n","/**\n * @typedef {import('./index.js').Content} Content\n */\n\nimport {u} from 'unist-builder'\n\n/**\n * Wrap `nodes` with line feeds between each entry.\n * Optionally adds line feeds at the start and end.\n *\n * @param {Array.} nodes\n * @param {boolean} [loose=false]\n * @returns {Array.}\n */\nexport function wrap(nodes, loose) {\n /** @type {Array.} */\n const result = []\n let index = -1\n\n if (loose) {\n result.push(u('text', '\\n'))\n }\n\n while (++index < nodes.length) {\n if (index) result.push(u('text', '\\n'))\n result.push(nodes[index])\n }\n\n if (loose && nodes.length > 0) {\n result.push(u('text', '\\n'))\n }\n\n return result\n}\n","/**\n * @typedef {import('mdast').List} List\n * @typedef {import('hast').Element} Element\n * @typedef {import('hast').Properties} Properties\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {wrap} from '../wrap.js'\nimport {all} from '../traverse.js'\n\n/**\n * @type {Handler}\n * @param {List} node\n * @returns {Element}\n */\nexport function list(h, node) {\n /** @type {Properties} */\n const props = {}\n const name = node.ordered ? 'ol' : 'ul'\n const items = all(h, node)\n let index = -1\n\n if (typeof node.start === 'number' && node.start !== 1) {\n props.start = node.start\n }\n\n // Like GitHub, add a class for custom styling.\n while (++index < items.length) {\n const item = items[index]\n\n if (\n item.type === 'element' &&\n item.tagName === 'li' &&\n item.properties &&\n Array.isArray(item.properties.className) &&\n item.properties.className.includes('task-list-item')\n ) {\n props.className = ['contains-task-list']\n break\n }\n }\n\n return h(node, name, props, wrap(items, true))\n}\n","/**\n * @typedef {import('mdast').FootnoteReference} FootnoteReference\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {u} from 'unist-builder'\n\n/**\n * @type {Handler}\n * @param {FootnoteReference} node\n */\nexport function footnoteReference(h, node) {\n const footnoteOrder = h.footnoteOrder\n const identifier = String(node.identifier)\n const index = footnoteOrder.indexOf(identifier)\n const marker = String(\n index === -1 ? footnoteOrder.push(identifier) : index + 1\n )\n\n return h(\n node,\n 'a',\n {\n href: '#fn' + marker,\n className: ['footnote-ref'],\n id: 'fnref' + marker,\n role: 'doc-noteref'\n },\n [h(node.position, 'sup', [u('text', marker)])]\n )\n}\n","\n'use strict';\n\n\nvar encodeCache = {};\n\n\n// Create a lookup array where anything but characters in `chars` string\n// and alphanumeric chars is percent-encoded.\n//\nfunction getEncodeCache(exclude) {\n var i, ch, cache = encodeCache[exclude];\n if (cache) { return cache; }\n\n cache = encodeCache[exclude] = [];\n\n for (i = 0; i < 128; i++) {\n ch = String.fromCharCode(i);\n\n if (/^[0-9a-z]$/i.test(ch)) {\n // always allow unencoded alphanumeric characters\n cache.push(ch);\n } else {\n cache.push('%' + ('0' + i.toString(16).toUpperCase()).slice(-2));\n }\n }\n\n for (i = 0; i < exclude.length; i++) {\n cache[exclude.charCodeAt(i)] = exclude[i];\n }\n\n return cache;\n}\n\n\n// Encode unsafe characters with percent-encoding, skipping already\n// encoded sequences.\n//\n// - string - string to encode\n// - exclude - list of characters to ignore (in addition to a-zA-Z0-9)\n// - keepEscaped - don't encode '%' in a correct escape sequence (default: true)\n//\nfunction encode(string, exclude, keepEscaped) {\n var i, l, code, nextCode, cache,\n result = '';\n\n if (typeof exclude !== 'string') {\n // encode(string, keepEscaped)\n keepEscaped = exclude;\n exclude = encode.defaultChars;\n }\n\n if (typeof keepEscaped === 'undefined') {\n keepEscaped = true;\n }\n\n cache = getEncodeCache(exclude);\n\n for (i = 0, l = string.length; i < l; i++) {\n code = string.charCodeAt(i);\n\n if (keepEscaped && code === 0x25 /* % */ && i + 2 < l) {\n if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) {\n result += string.slice(i, i + 3);\n i += 2;\n continue;\n }\n }\n\n if (code < 128) {\n result += cache[code];\n continue;\n }\n\n if (code >= 0xD800 && code <= 0xDFFF) {\n if (code >= 0xD800 && code <= 0xDBFF && i + 1 < l) {\n nextCode = string.charCodeAt(i + 1);\n if (nextCode >= 0xDC00 && nextCode <= 0xDFFF) {\n result += encodeURIComponent(string[i] + string[i + 1]);\n i++;\n continue;\n }\n }\n result += '%EF%BF%BD';\n continue;\n }\n\n result += encodeURIComponent(string[i]);\n }\n\n return result;\n}\n\nencode.defaultChars = \";/?:@&=+$,-_.!~*'()#\";\nencode.componentChars = \"-_.!~*'()\";\n\n\nmodule.exports = encode;\n","/**\n * @typedef {import('mdast').LinkReference} LinkReference\n * @typedef {import('mdast').ImageReference} ImageReference\n * @typedef {import('./index.js').Handler} Handler\n * @typedef {import('./index.js').Content} Content\n */\n\nimport {u} from 'unist-builder'\nimport {all} from './traverse.js'\n\n/**\n * Return the content of a reference without definition as plain text.\n *\n * @type {Handler}\n * @param {ImageReference|LinkReference} node\n * @returns {Content|Array.}\n */\nexport function revert(h, node) {\n const subtype = node.referenceType\n let suffix = ']'\n\n if (subtype === 'collapsed') {\n suffix += '[]'\n } else if (subtype === 'full') {\n suffix += '[' + (node.label || node.identifier) + ']'\n }\n\n if (node.type === 'imageReference') {\n return u('text', '![' + node.alt + suffix)\n }\n\n const contents = all(h, node)\n const head = contents[0]\n\n if (head && head.type === 'text') {\n head.value = '[' + head.value\n } else {\n contents.unshift(u('text', '['))\n }\n\n const tail = contents[contents.length - 1]\n\n if (tail && tail.type === 'text') {\n tail.value += suffix\n } else {\n contents.push(u('text', suffix))\n }\n\n return contents\n}\n","/**\n * @typedef {import('mdast').ListItem} ListItem\n * @typedef {import('mdast').List} List\n * @typedef {import('hast').Properties} Properties\n * @typedef {import('hast').Element} Element\n * @typedef {import('../index.js').Handler} Handler\n * @typedef {import('../index.js').Content} Content\n */\n\nimport {u} from 'unist-builder'\nimport {all} from '../traverse.js'\n\n/**\n * @type {Handler}\n * @param {ListItem} node\n * @param {List} parent\n */\nexport function listItem(h, node, parent) {\n const result = all(h, node)\n const loose = parent ? listLoose(parent) : listItemLoose(node)\n /** @type {Properties} */\n const props = {}\n /** @type {Array.} */\n const wrapped = []\n\n if (typeof node.checked === 'boolean') {\n /** @type {Element} */\n let paragraph\n\n if (\n result[0] &&\n result[0].type === 'element' &&\n result[0].tagName === 'p'\n ) {\n paragraph = result[0]\n } else {\n paragraph = h(null, 'p', [])\n result.unshift(paragraph)\n }\n\n if (paragraph.children.length > 0) {\n paragraph.children.unshift(u('text', ' '))\n }\n\n paragraph.children.unshift(\n h(null, 'input', {\n type: 'checkbox',\n checked: node.checked,\n disabled: true\n })\n )\n\n // According to github-markdown-css, this class hides bullet.\n // See: .\n props.className = ['task-list-item']\n }\n\n let index = -1\n\n while (++index < result.length) {\n const child = result[index]\n\n // Add eols before nodes, except if this is a loose, first paragraph.\n if (\n loose ||\n index !== 0 ||\n child.type !== 'element' ||\n child.tagName !== 'p'\n ) {\n wrapped.push(u('text', '\\n'))\n }\n\n if (child.type === 'element' && child.tagName === 'p' && !loose) {\n wrapped.push(...child.children)\n } else {\n wrapped.push(child)\n }\n }\n\n const tail = result[result.length - 1]\n\n // Add a final eol.\n if (tail && (loose || !('tagName' in tail) || tail.tagName !== 'p')) {\n wrapped.push(u('text', '\\n'))\n }\n\n return h(node, 'li', props, wrapped)\n}\n\n/**\n * @param {List} node\n * @return {Boolean}\n */\nfunction listLoose(node) {\n let loose = node.spread\n const children = node.children\n let index = -1\n\n while (!loose && ++index < children.length) {\n loose = listItemLoose(children[index])\n }\n\n return Boolean(loose)\n}\n\n/**\n * @param {ListItem} node\n * @return {Boolean}\n */\nfunction listItemLoose(node) {\n const spread = node.spread\n\n return spread === undefined || spread === null\n ? node.children.length > 1\n : spread\n}\n","import {blockquote} from './blockquote.js'\nimport {hardBreak} from './break.js'\nimport {code} from './code.js'\nimport {strikethrough} from './delete.js'\nimport {emphasis} from './emphasis.js'\nimport {footnoteReference} from './footnote-reference.js'\nimport {footnote} from './footnote.js'\nimport {heading} from './heading.js'\nimport {html} from './html.js'\nimport {imageReference} from './image-reference.js'\nimport {image} from './image.js'\nimport {inlineCode} from './inline-code.js'\nimport {linkReference} from './link-reference.js'\nimport {link} from './link.js'\nimport {listItem} from './list-item.js'\nimport {list} from './list.js'\nimport {paragraph} from './paragraph.js'\nimport {root} from './root.js'\nimport {strong} from './strong.js'\nimport {table} from './table.js'\nimport {text} from './text.js'\nimport {thematicBreak} from './thematic-break.js'\n\nexport const handlers = {\n blockquote,\n break: hardBreak,\n code,\n delete: strikethrough,\n emphasis,\n footnoteReference,\n footnote,\n heading,\n html,\n imageReference,\n image,\n inlineCode,\n linkReference,\n link,\n listItem,\n list,\n paragraph,\n root,\n strong,\n table,\n text,\n thematicBreak,\n toml: ignore,\n yaml: ignore,\n definition: ignore,\n footnoteDefinition: ignore\n}\n\n// Return nothing for nodes that are ignored.\nfunction ignore() {\n return null\n}\n","/**\n * @typedef {import('mdast').Blockquote} Blockquote\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {wrap} from '../wrap.js'\nimport {all} from '../traverse.js'\n\n/**\n * @type {Handler}\n * @param {Blockquote} node\n */\nexport function blockquote(h, node) {\n return h(node, 'blockquote', wrap(all(h, node), true))\n}\n","/**\n * @typedef {import('hast').Element} Element\n * @typedef {import('hast').Text} Text\n * @typedef {import('mdast').Break} Break\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {u} from 'unist-builder'\n\n/**\n * @type {Handler}\n * @param {Break} node\n * @returns {Array}\n */\nexport function hardBreak(h, node) {\n return [h(node, 'br'), u('text', '\\n')]\n}\n","/**\n * @typedef {import('mdast').Code} Code\n * @typedef {import('hast').Element} Element\n * @typedef {import('hast').Properties} Properties\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {u} from 'unist-builder'\n\n/**\n * @type {Handler}\n * @param {Code} node\n */\nexport function code(h, node) {\n const value = node.value ? node.value + '\\n' : ''\n // To do: next major, use `node.lang` w/o regex, the splitting’s been going\n // on for years in remark now.\n const lang = node.lang && node.lang.match(/^[^ \\t]+(?=[ \\t]|$)/)\n /** @type {Properties} */\n const props = {}\n\n if (lang) {\n props.className = ['language-' + lang]\n }\n\n const code = h(node, 'code', props, [u('text', value)])\n\n if (node.meta) {\n code.data = {meta: node.meta}\n }\n\n return h(node.position, 'pre', [code])\n}\n","/**\n * @typedef {import('mdast').Delete} Delete\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {all} from '../traverse.js'\n\n/**\n * @type {Handler}\n * @param {Delete} node\n */\nexport function strikethrough(h, node) {\n return h(node, 'del', all(h, node))\n}\n","/**\n * @typedef {import('mdast').Emphasis} Emphasis\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {all} from '../traverse.js'\n\n/**\n * @type {Handler}\n * @param {Emphasis} node\n */\nexport function emphasis(h, node) {\n return h(node, 'em', all(h, node))\n}\n","/**\n * @typedef {import('mdast').Footnote} Footnote\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {footnoteReference} from './footnote-reference.js'\n\n/**\n * @type {Handler}\n * @param {Footnote} node\n */\nexport function footnote(h, node) {\n const footnoteById = h.footnoteById\n const footnoteOrder = h.footnoteOrder\n let no = 1\n\n while (no in footnoteById) no++\n\n const identifier = String(no)\n\n // No need to check if `identifier` exists in `footnoteOrder`, it’s guaranteed\n // to not exist because we just generated it.\n footnoteOrder.push(identifier)\n\n footnoteById[identifier] = {\n type: 'footnoteDefinition',\n identifier,\n children: [{type: 'paragraph', children: node.children}],\n position: node.position\n }\n\n return footnoteReference(h, {\n type: 'footnoteReference',\n identifier,\n position: node.position\n })\n}\n","/**\n * @typedef {import('mdast').Heading} Heading\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {all} from '../traverse.js'\n\n/**\n * @type {Handler}\n * @param {Heading} node\n */\nexport function heading(h, node) {\n return h(node, 'h' + node.depth, all(h, node))\n}\n","/**\n * @typedef {import('mdast').HTML} HTML\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {u} from 'unist-builder'\n\n/**\n * Return either a `raw` node in dangerous mode, otherwise nothing.\n *\n * @type {Handler}\n * @param {HTML} node\n */\nexport function html(h, node) {\n return h.dangerous ? h.augment(node, u('raw', node.value)) : null\n}\n","/**\n * @typedef {import('mdast').ImageReference} ImageReference\n * @typedef {import('hast').Properties} Properties\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport normalize from 'mdurl/encode.js'\nimport {revert} from '../revert.js'\n\n/**\n * @type {Handler}\n * @param {ImageReference} node\n */\nexport function imageReference(h, node) {\n const def = h.definition(node.identifier)\n\n if (!def) {\n return revert(h, node)\n }\n\n /** @type {Properties} */\n const props = {src: normalize(def.url || ''), alt: node.alt}\n\n if (def.title !== null && def.title !== undefined) {\n props.title = def.title\n }\n\n return h(node, 'img', props)\n}\n","/**\n * @typedef {import('mdast').Image} Image\n * @typedef {import('hast').Properties} Properties\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport normalize from 'mdurl/encode.js'\n\n/**\n * @type {Handler}\n * @param {Image} node\n */\nexport function image(h, node) {\n /** @type {Properties} */\n const props = {src: normalize(node.url), alt: node.alt}\n\n if (node.title !== null && node.title !== undefined) {\n props.title = node.title\n }\n\n return h(node, 'img', props)\n}\n","/**\n * @typedef {import('mdast').InlineCode} InlineCode\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {u} from 'unist-builder'\n\n/**\n * @type {Handler}\n * @param {InlineCode} node\n */\nexport function inlineCode(h, node) {\n return h(node, 'code', [u('text', node.value.replace(/\\r?\\n|\\r/g, ' '))])\n}\n","/**\n * @typedef {import('mdast').LinkReference} LinkReference\n * @typedef {import('hast').Properties} Properties\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport normalize from 'mdurl/encode.js'\nimport {revert} from '../revert.js'\nimport {all} from '../traverse.js'\n\n/**\n * @type {Handler}\n * @param {LinkReference} node\n */\nexport function linkReference(h, node) {\n const def = h.definition(node.identifier)\n\n if (!def) {\n return revert(h, node)\n }\n\n /** @type {Properties} */\n const props = {href: normalize(def.url || '')}\n\n if (def.title !== null && def.title !== undefined) {\n props.title = def.title\n }\n\n return h(node, 'a', props, all(h, node))\n}\n","/**\n * @typedef {import('mdast').Link} Link\n * @typedef {import('hast').Properties} Properties\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport normalize from 'mdurl/encode.js'\nimport {all} from '../traverse.js'\n\n/**\n * @type {Handler}\n * @param {Link} node\n */\nexport function link(h, node) {\n /** @type {Properties} */\n const props = {href: normalize(node.url)}\n\n if (node.title !== null && node.title !== undefined) {\n props.title = node.title\n }\n\n return h(node, 'a', props, all(h, node))\n}\n","/**\n * @typedef {import('mdast').Paragraph} Paragraph\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {all} from '../traverse.js'\n\n/**\n * @type {Handler}\n * @param {Paragraph} node\n */\nexport function paragraph(h, node) {\n return h(node, 'p', all(h, node))\n}\n","/**\n * @typedef {import('mdast').Root} Root\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {u} from 'unist-builder'\nimport {all} from '../traverse.js'\nimport {wrap} from '../wrap.js'\n\n/**\n * @type {Handler}\n * @param {Root} node\n */\nexport function root(h, node) {\n // @ts-expect-error `root`s are also fine.\n return h.augment(node, u('root', wrap(all(h, node))))\n}\n","/**\n * @typedef {import('mdast').Strong} Strong\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {all} from '../traverse.js'\n\n/**\n * @type {Handler}\n * @param {Strong} node\n */\nexport function strong(h, node) {\n return h(node, 'strong', all(h, node))\n}\n","/**\n * @typedef {import('mdast').Table} Table\n * @typedef {import('mdast').TableCell} TableCell\n * @typedef {import('hast').Element} Element\n * @typedef {import('../index.js').Handler} Handler\n * @typedef {import('../index.js').Content} Content\n */\n\nimport {pointStart, pointEnd} from 'unist-util-position'\nimport {wrap} from '../wrap.js'\nimport {all} from '../traverse.js'\n\n/**\n * @type {Handler}\n * @param {Table} node\n */\nexport function table(h, node) {\n const rows = node.children\n let index = -1\n const align = node.align || []\n /** @type {Array.} */\n const result = []\n\n while (++index < rows.length) {\n const row = rows[index].children\n const name = index === 0 ? 'th' : 'td'\n let pos = node.align ? align.length : row.length\n /** @type {Array.} */\n const out = []\n\n while (pos--) {\n const cell = row[pos]\n out[pos] = h(cell, name, {align: align[pos]}, cell ? all(h, cell) : [])\n }\n\n result[index] = h(rows[index], 'tr', wrap(out, true))\n }\n\n return h(\n node,\n 'table',\n wrap(\n [h(result[0].position, 'thead', wrap([result[0]], true))].concat(\n result[1]\n ? h(\n {\n start: pointStart(result[1]),\n end: pointEnd(result[result.length - 1])\n },\n 'tbody',\n wrap(result.slice(1), true)\n )\n : []\n ),\n true\n )\n )\n}\n","/**\n * @typedef {import('mdast').Text} Text\n * @typedef {import('../index.js').Handler} Handler\n */\n\nimport {u} from 'unist-builder'\n\n/**\n * @type {Handler}\n * @param {Text} node\n */\nexport function text(h, node) {\n return h.augment(\n node,\n u('text', String(node.value).replace(/[ \\t]*(\\r?\\n|\\r)[ \\t]*/g, '$1'))\n )\n}\n","/**\n * @typedef {import('mdast').Root|import('mdast').Parent['children'][number]} MdastNode\n * @typedef {import('hast').Root|import('hast').Parent['children'][number]} HastNode\n * @typedef {import('mdast').Parent} Parent\n * @typedef {import('mdast').Definition} Definition\n * @typedef {import('mdast').FootnoteDefinition} FootnoteDefinition\n * @typedef {import('hast').Properties} Properties\n * @typedef {import('hast').Text} Text\n * @typedef {import('hast').Comment} Comment\n * @typedef {import('hast').Element} Element\n * @typedef {import('hast').Root} Root\n * @typedef {import('hast').ElementContent} Content\n * @typedef {import('unist-util-position').PositionLike} PositionLike\n *\n * @typedef EmbeddedHastFields\n * @property {string} [hName] Defines the tag name of an element\n * @property {Properties} [hProperties] Defines the properties of an element\n * @property {Array.} [hChildren] Defines the (hast) children of an element\n *\n * @typedef {Object. & EmbeddedHastFields} Data unist data with embedded hast fields\n *\n * @typedef {MdastNode & {data?: Data}} NodeWithData unist node with embedded hast data\n *\n * @callback Handler\n * @param {H} h Handle context\n * @param {any} node mdast node to handle\n * @param {Parent|null} parent Parent of `node`\n * @returns {Content|Array.|null|undefined} hast node\n *\n * @callback HFunctionProps\n * @param {MdastNode|PositionLike|null|undefined} node mdast node or unist position\n * @param {string} tagName HTML tag name\n * @param {Properties} props Properties\n * @param {Array.?} [children] hast content\n * @returns {Element}\n *\n * @callback HFunctionNoProps\n * @param {MdastNode|PositionLike|null|undefined} node mdast node or unist position\n * @param {string} tagName HTML tag name\n * @param {Array.?} [children] hast content\n * @returns {Element}\n *\n * @typedef HFields\n * @property {boolean} dangerous Whether HTML is allowed\n * @property {(identifier: string) => Definition|null} definition Definition cache\n * @property {Object.} footnoteById Footnote cache\n * @property {Array.} footnoteOrder Order in which footnotes occur\n * @property {Handlers} handlers Applied handlers\n * @property {Handler} unknownHandler Handler for any none not in `passThrough` or otherwise handled\n * @property {(left: NodeWithData|PositionLike|null|undefined, right: Content) => Content} augment Like `h` but lower-level and usable on non-elements.\n * @property {Array.} passThrough List of node types to pass through untouched (except for their children).\n *\n * @typedef Options\n * @property {boolean} [allowDangerousHtml=false] Whether to allow `html` nodes and inject them as `raw` HTML\n * @property {Handlers} [handlers] Object mapping mdast nodes to functions handling them\n * @property {Array.} [passThrough] List of custom mdast node types to pass through (keep) in hast\n * @property {Handler} [unknownHandler] Handler for all unknown nodes.\n *\n * @typedef {Record.} Handlers Map of node types to handlers\n * @typedef {HFunctionProps & HFunctionNoProps & HFields} H Handle context\n */\n\nimport {u} from 'unist-builder'\nimport {visit} from 'unist-util-visit'\nimport {pointStart, pointEnd} from 'unist-util-position'\nimport {generated} from 'unist-util-generated'\nimport {definitions} from 'mdast-util-definitions'\nimport {one} from './traverse.js'\nimport {footer} from './footer.js'\nimport {handlers} from './handlers/index.js'\n\nconst own = {}.hasOwnProperty\n\n/**\n * Factory to transform.\n * @param {MdastNode} tree mdast node\n * @param {Options} [options] Configuration\n * @returns {H} `h` function\n */\nfunction factory(tree, options) {\n const settings = options || {}\n const dangerous = settings.allowDangerousHtml || false\n /** @type {Object.} */\n const footnoteById = {}\n\n h.dangerous = dangerous\n h.definition = definitions(tree)\n h.footnoteById = footnoteById\n /** @type {Array.} */\n h.footnoteOrder = []\n h.augment = augment\n h.handlers = {...handlers, ...settings.handlers}\n h.unknownHandler = settings.unknownHandler\n h.passThrough = settings.passThrough\n\n visit(tree, 'footnoteDefinition', (definition) => {\n const id = String(definition.identifier).toUpperCase()\n\n // Mimick CM behavior of link definitions.\n // See: .\n if (!own.call(footnoteById, id)) {\n footnoteById[id] = definition\n }\n })\n\n // @ts-expect-error Hush, it’s fine!\n return h\n\n /**\n * Finalise the created `right`, a hast node, from `left`, an mdast node.\n * @param {(NodeWithData|PositionLike)?} left\n * @param {Content} right\n * @returns {Content}\n */\n function augment(left, right) {\n // Handle `data.hName`, `data.hProperties, `data.hChildren`.\n if (left && 'data' in left && left.data) {\n /** @type {Data} */\n const data = left.data\n\n if (data.hName) {\n if (right.type !== 'element') {\n right = {\n type: 'element',\n tagName: '',\n properties: {},\n children: []\n }\n }\n\n right.tagName = data.hName\n }\n\n if (right.type === 'element' && data.hProperties) {\n right.properties = {...right.properties, ...data.hProperties}\n }\n\n if ('children' in right && right.children && data.hChildren) {\n right.children = data.hChildren\n }\n }\n\n if (left) {\n const ctx = 'type' in left ? left : {position: left}\n\n if (!generated(ctx)) {\n right.position = {start: pointStart(ctx), end: pointEnd(ctx)}\n }\n }\n\n return right\n }\n\n /**\n * Create an element for `node`.\n *\n * @type {HFunctionProps}\n */\n function h(node, tagName, props, children) {\n if (Array.isArray(props)) {\n children = props\n props = {}\n }\n\n // @ts-expect-error augmenting an element yields an element.\n return augment(node, {\n type: 'element',\n tagName,\n properties: props || {},\n children: children || []\n })\n }\n}\n\n/**\n * Transform `tree` (an mdast node) to a hast node.\n *\n * @param {MdastNode} tree mdast node\n * @param {Options} [options] Configuration\n * @returns {HastNode|null|undefined} hast node\n */\nexport function toHast(tree, options) {\n const h = factory(tree, options)\n const node = one(h, tree, null)\n const foot = footer(h)\n\n if (foot) {\n // @ts-expect-error If there’s a footer, there were definitions, meaning block\n // content.\n // So assume `node` is a parent node.\n node.children.push(u('text', '\\n'), foot)\n }\n\n return Array.isArray(node) ? {type: 'root', children: node} : node\n}\n","/**\n * @typedef {Object} PointLike\n * @property {number} [line]\n * @property {number} [column]\n * @property {number} [offset]\n *\n * @typedef {Object} PositionLike\n * @property {PointLike} [start]\n * @property {PointLike} [end]\n *\n * @typedef {Object} NodeLike\n * @property {PositionLike} [position]\n */\n\n/**\n * Check if `node` is *generated*.\n *\n * @param {NodeLike} [node]\n * @returns {boolean}\n */\nexport function generated(node) {\n return (\n !node ||\n !node.position ||\n !node.position.start ||\n !node.position.start.line ||\n !node.position.start.column ||\n !node.position.end ||\n !node.position.end.line ||\n !node.position.end.column\n )\n}\n","/**\n * @typedef {import('mdast').BlockContent} BlockContent\n * @typedef {import('mdast').FootnoteDefinition} FootnoteDefinition\n * @typedef {import('mdast').Link} Link\n * @typedef {import('mdast').ListItem} ListItem\n * @typedef {import('mdast').Paragraph} Paragraph\n * @typedef {import('./index.js').H} H\n */\n\nimport {thematicBreak} from './handlers/thematic-break.js'\nimport {list} from './handlers/list.js'\nimport {wrap} from './wrap.js'\n\n/**\n * @param {H} h\n */\nexport function footer(h) {\n const footnoteById = h.footnoteById\n const footnoteOrder = h.footnoteOrder\n let index = -1\n /** @type {Array.} */\n const listItems = []\n\n while (++index < footnoteOrder.length) {\n const def = footnoteById[footnoteOrder[index].toUpperCase()]\n\n if (!def) {\n continue\n }\n\n const marker = String(index + 1)\n const content = [...def.children]\n /** @type {Link} */\n const backReference = {\n type: 'link',\n url: '#fnref' + marker,\n data: {hProperties: {className: ['footnote-back'], role: 'doc-backlink'}},\n children: [{type: 'text', value: '↩'}]\n }\n const tail = content[content.length - 1]\n\n if (tail && tail.type === 'paragraph') {\n tail.children.push(backReference)\n } else {\n // @ts-expect-error Indeed, link directly added in block content.\n // Which we do because that way at least the handlers will be called\n // for the other HTML we’re generating (as markdown).\n content.push(backReference)\n }\n\n listItems.push({\n type: 'listItem',\n data: {hProperties: {id: 'fn' + marker, role: 'doc-endnote'}},\n children: content,\n position: def.position\n })\n }\n\n if (listItems.length === 0) {\n return null\n }\n\n return h(\n null,\n 'section',\n {className: ['footnotes'], role: 'doc-endnotes'},\n wrap(\n [\n thematicBreak(h),\n list(h, {type: 'list', ordered: true, children: listItems})\n ],\n true\n )\n )\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('hast').Root} HastRoot\n * @typedef {import('mdast').Root} MdastRoot\n * @typedef {import('mdast-util-to-hast').Options} Options\n * @typedef {import('unified').Processor} Processor\n *\n * @typedef {import('mdast-util-to-hast')} DoNotTouchAsThisImportIncludesRawInTree\n */\n\nimport {toHast} from 'mdast-util-to-hast'\n\n// Note: the `` overload doesn’t seem to work :'(\n\n/**\n * Plugin to bridge or mutate to rehype.\n *\n * If a destination is given, runs the destination with the new hast tree\n * (bridge-mode).\n * Without destination, returns the hast tree: further plugins run on that tree\n * (mutate-mode).\n *\n * @param destination\n * Optional unified processor.\n * @param options\n * Options passed to `mdast-util-to-hast`.\n */\nconst remarkRehype =\n /** @type {(import('unified').Plugin<[Processor, Options?]|[Options]|[], MdastRoot>)} */\n (\n function (destination, options) {\n return destination && 'run' in destination\n ? bridge(destination, options)\n : mutate(destination)\n }\n )\n\nexport default remarkRehype\n\n/**\n * Bridge-mode.\n * Runs the destination with the new hast tree.\n *\n * @type {import('unified').Plugin<[Processor, Options?], MdastRoot>}\n */\nfunction bridge(destination, options) {\n return (node, file, next) => {\n destination.run(toHast(node, options), file, (error) => {\n next(error)\n })\n }\n}\n\n/**\n * Mutate-mode.\n * Further transformers run on the nlcst tree.\n *\n * @type {import('unified').Plugin<[Options?]|void[], MdastRoot, HastRoot>}\n */\nfunction mutate(options) {\n // @ts-expect-error: assume a corresponding node is returned for `toHast`.\n return (node) => toHast(node, options)\n}\n","/**\n * @typedef {import('./info.js').Info} Info\n * @typedef {Record} Properties\n * @typedef {Record} Normal\n */\n\nexport class Schema {\n /**\n * @constructor\n * @param {Properties} property\n * @param {Normal} normal\n * @param {string} [space]\n */\n constructor(property, normal, space) {\n this.property = property\n this.normal = normal\n if (space) {\n this.space = space\n }\n }\n}\n\n/** @type {Properties} */\nSchema.prototype.property = {}\n/** @type {Normal} */\nSchema.prototype.normal = {}\n/** @type {string|null} */\nSchema.prototype.space = null\n","/**\n * @typedef {import('./schema.js').Properties} Properties\n * @typedef {import('./schema.js').Normal} Normal\n */\n\nimport {Schema} from './schema.js'\n\n/**\n * @param {Schema[]} definitions\n * @param {string} [space]\n * @returns {Schema}\n */\nexport function merge(definitions, space) {\n /** @type {Properties} */\n const property = {}\n /** @type {Normal} */\n const normal = {}\n let index = -1\n\n while (++index < definitions.length) {\n Object.assign(property, definitions[index].property)\n Object.assign(normal, definitions[index].normal)\n }\n\n return new Schema(property, normal, space)\n}\n","/**\n * @param {string} value\n * @returns {string}\n */\nexport function normalize(value) {\n return value.toLowerCase()\n}\n","export class Info {\n /**\n * @constructor\n * @param {string} property\n * @param {string} attribute\n */\n constructor(property, attribute) {\n /** @type {string} */\n this.property = property\n /** @type {string} */\n this.attribute = attribute\n }\n}\n\n/** @type {string|null} */\nInfo.prototype.space = null\nInfo.prototype.boolean = false\nInfo.prototype.booleanish = false\nInfo.prototype.overloadedBoolean = false\nInfo.prototype.number = false\nInfo.prototype.commaSeparated = false\nInfo.prototype.spaceSeparated = false\nInfo.prototype.commaOrSpaceSeparated = false\nInfo.prototype.mustUseProperty = false\nInfo.prototype.defined = false\n","let powers = 0\n\nexport const boolean = increment()\nexport const booleanish = increment()\nexport const overloadedBoolean = increment()\nexport const number = increment()\nexport const spaceSeparated = increment()\nexport const commaSeparated = increment()\nexport const commaOrSpaceSeparated = increment()\n\nfunction increment() {\n return 2 ** ++powers\n}\n","import {Info} from './info.js'\nimport * as types from './types.js'\n\n/** @type {Array} */\n// @ts-expect-error: hush.\nconst checks = Object.keys(types)\n\nexport class DefinedInfo extends Info {\n /**\n * @constructor\n * @param {string} property\n * @param {string} attribute\n * @param {number|null} [mask]\n * @param {string} [space]\n */\n constructor(property, attribute, mask, space) {\n let index = -1\n\n super(property, attribute)\n\n mark(this, 'space', space)\n\n if (typeof mask === 'number') {\n while (++index < checks.length) {\n const check = checks[index]\n mark(this, checks[index], (mask & types[check]) === types[check])\n }\n }\n }\n}\n\nDefinedInfo.prototype.defined = true\n\n/**\n * @param {DefinedInfo} values\n * @param {string} key\n * @param {unknown} value\n */\nfunction mark(values, key, value) {\n if (value) {\n // @ts-expect-error: assume `value` matches the expected value of `key`.\n values[key] = value\n }\n}\n","/**\n * @typedef {import('./schema.js').Properties} Properties\n * @typedef {import('./schema.js').Normal} Normal\n *\n * @typedef {Record} Attributes\n *\n * @typedef {Object} Definition\n * @property {Record} properties\n * @property {(attributes: Attributes, property: string) => string} transform\n * @property {string} [space]\n * @property {Attributes} [attributes]\n * @property {Array} [mustUseProperty]\n */\n\nimport {normalize} from '../normalize.js'\nimport {Schema} from './schema.js'\nimport {DefinedInfo} from './defined-info.js'\n\nconst own = {}.hasOwnProperty\n\n/**\n * @param {Definition} definition\n * @returns {Schema}\n */\nexport function create(definition) {\n /** @type {Properties} */\n const property = {}\n /** @type {Normal} */\n const normal = {}\n /** @type {string} */\n let prop\n\n for (prop in definition.properties) {\n if (own.call(definition.properties, prop)) {\n const value = definition.properties[prop]\n const info = new DefinedInfo(\n prop,\n definition.transform(definition.attributes || {}, prop),\n value,\n definition.space\n )\n\n if (\n definition.mustUseProperty &&\n definition.mustUseProperty.includes(prop)\n ) {\n info.mustUseProperty = true\n }\n\n property[prop] = info\n\n normal[normalize(prop)] = prop\n normal[normalize(info.attribute)] = prop\n }\n }\n\n return new Schema(property, normal, definition.space)\n}\n","import {create} from './util/create.js'\n\nexport const xlink = create({\n space: 'xlink',\n transform(_, prop) {\n return 'xlink:' + prop.slice(5).toLowerCase()\n },\n properties: {\n xLinkActuate: null,\n xLinkArcRole: null,\n xLinkHref: null,\n xLinkRole: null,\n xLinkShow: null,\n xLinkTitle: null,\n xLinkType: null\n }\n})\n","import {create} from './util/create.js'\n\nexport const xml = create({\n space: 'xml',\n transform(_, prop) {\n return 'xml:' + prop.slice(3).toLowerCase()\n },\n properties: {xmlLang: null, xmlBase: null, xmlSpace: null}\n})\n","/**\n * @param {Record} attributes\n * @param {string} attribute\n * @returns {string}\n */\nexport function caseSensitiveTransform(attributes, attribute) {\n return attribute in attributes ? attributes[attribute] : attribute\n}\n","import {caseSensitiveTransform} from './case-sensitive-transform.js'\n\n/**\n * @param {Record} attributes\n * @param {string} property\n * @returns {string}\n */\nexport function caseInsensitiveTransform(attributes, property) {\n return caseSensitiveTransform(attributes, property.toLowerCase())\n}\n","import {create} from './util/create.js'\nimport {caseInsensitiveTransform} from './util/case-insensitive-transform.js'\n\nexport const xmlns = create({\n space: 'xmlns',\n attributes: {xmlnsxlink: 'xmlns:xlink'},\n transform: caseInsensitiveTransform,\n properties: {xmlns: null, xmlnsXLink: null}\n})\n","import {booleanish, number, spaceSeparated} from './util/types.js'\nimport {create} from './util/create.js'\n\nexport const aria = create({\n transform(_, prop) {\n return prop === 'role' ? prop : 'aria-' + prop.slice(4).toLowerCase()\n },\n properties: {\n ariaActiveDescendant: null,\n ariaAtomic: booleanish,\n ariaAutoComplete: null,\n ariaBusy: booleanish,\n ariaChecked: booleanish,\n ariaColCount: number,\n ariaColIndex: number,\n ariaColSpan: number,\n ariaControls: spaceSeparated,\n ariaCurrent: null,\n ariaDescribedBy: spaceSeparated,\n ariaDetails: null,\n ariaDisabled: booleanish,\n ariaDropEffect: spaceSeparated,\n ariaErrorMessage: null,\n ariaExpanded: booleanish,\n ariaFlowTo: spaceSeparated,\n ariaGrabbed: booleanish,\n ariaHasPopup: null,\n ariaHidden: booleanish,\n ariaInvalid: null,\n ariaKeyShortcuts: null,\n ariaLabel: null,\n ariaLabelledBy: spaceSeparated,\n ariaLevel: number,\n ariaLive: null,\n ariaModal: booleanish,\n ariaMultiLine: booleanish,\n ariaMultiSelectable: booleanish,\n ariaOrientation: null,\n ariaOwns: spaceSeparated,\n ariaPlaceholder: null,\n ariaPosInSet: number,\n ariaPressed: booleanish,\n ariaReadOnly: booleanish,\n ariaRelevant: null,\n ariaRequired: booleanish,\n ariaRoleDescription: spaceSeparated,\n ariaRowCount: number,\n ariaRowIndex: number,\n ariaRowSpan: number,\n ariaSelected: booleanish,\n ariaSetSize: number,\n ariaSort: null,\n ariaValueMax: number,\n ariaValueMin: number,\n ariaValueNow: number,\n ariaValueText: null,\n role: null\n }\n})\n","import {\n boolean,\n overloadedBoolean,\n booleanish,\n number,\n spaceSeparated,\n commaSeparated\n} from './util/types.js'\nimport {create} from './util/create.js'\nimport {caseInsensitiveTransform} from './util/case-insensitive-transform.js'\n\nexport const html = create({\n space: 'html',\n attributes: {\n acceptcharset: 'accept-charset',\n classname: 'class',\n htmlfor: 'for',\n httpequiv: 'http-equiv'\n },\n transform: caseInsensitiveTransform,\n mustUseProperty: ['checked', 'multiple', 'muted', 'selected'],\n properties: {\n // Standard Properties.\n abbr: null,\n accept: commaSeparated,\n acceptCharset: spaceSeparated,\n accessKey: spaceSeparated,\n action: null,\n allow: null,\n allowFullScreen: boolean,\n allowPaymentRequest: boolean,\n allowUserMedia: boolean,\n alt: null,\n as: null,\n async: boolean,\n autoCapitalize: null,\n autoComplete: spaceSeparated,\n autoFocus: boolean,\n autoPlay: boolean,\n capture: boolean,\n charSet: null,\n checked: boolean,\n cite: null,\n className: spaceSeparated,\n cols: number,\n colSpan: null,\n content: null,\n contentEditable: booleanish,\n controls: boolean,\n controlsList: spaceSeparated,\n coords: number | commaSeparated,\n crossOrigin: null,\n data: null,\n dateTime: null,\n decoding: null,\n default: boolean,\n defer: boolean,\n dir: null,\n dirName: null,\n disabled: boolean,\n download: overloadedBoolean,\n draggable: booleanish,\n encType: null,\n enterKeyHint: null,\n form: null,\n formAction: null,\n formEncType: null,\n formMethod: null,\n formNoValidate: boolean,\n formTarget: null,\n headers: spaceSeparated,\n height: number,\n hidden: boolean,\n high: number,\n href: null,\n hrefLang: null,\n htmlFor: spaceSeparated,\n httpEquiv: spaceSeparated,\n id: null,\n imageSizes: null,\n imageSrcSet: null,\n inputMode: null,\n integrity: null,\n is: null,\n isMap: boolean,\n itemId: null,\n itemProp: spaceSeparated,\n itemRef: spaceSeparated,\n itemScope: boolean,\n itemType: spaceSeparated,\n kind: null,\n label: null,\n lang: null,\n language: null,\n list: null,\n loading: null,\n loop: boolean,\n low: number,\n manifest: null,\n max: null,\n maxLength: number,\n media: null,\n method: null,\n min: null,\n minLength: number,\n multiple: boolean,\n muted: boolean,\n name: null,\n nonce: null,\n noModule: boolean,\n noValidate: boolean,\n onAbort: null,\n onAfterPrint: null,\n onAuxClick: null,\n onBeforePrint: null,\n onBeforeUnload: null,\n onBlur: null,\n onCancel: null,\n onCanPlay: null,\n onCanPlayThrough: null,\n onChange: null,\n onClick: null,\n onClose: null,\n onContextLost: null,\n onContextMenu: null,\n onContextRestored: null,\n onCopy: null,\n onCueChange: null,\n onCut: null,\n onDblClick: null,\n onDrag: null,\n onDragEnd: null,\n onDragEnter: null,\n onDragExit: null,\n onDragLeave: null,\n onDragOver: null,\n onDragStart: null,\n onDrop: null,\n onDurationChange: null,\n onEmptied: null,\n onEnded: null,\n onError: null,\n onFocus: null,\n onFormData: null,\n onHashChange: null,\n onInput: null,\n onInvalid: null,\n onKeyDown: null,\n onKeyPress: null,\n onKeyUp: null,\n onLanguageChange: null,\n onLoad: null,\n onLoadedData: null,\n onLoadedMetadata: null,\n onLoadEnd: null,\n onLoadStart: null,\n onMessage: null,\n onMessageError: null,\n onMouseDown: null,\n onMouseEnter: null,\n onMouseLeave: null,\n onMouseMove: null,\n onMouseOut: null,\n onMouseOver: null,\n onMouseUp: null,\n onOffline: null,\n onOnline: null,\n onPageHide: null,\n onPageShow: null,\n onPaste: null,\n onPause: null,\n onPlay: null,\n onPlaying: null,\n onPopState: null,\n onProgress: null,\n onRateChange: null,\n onRejectionHandled: null,\n onReset: null,\n onResize: null,\n onScroll: null,\n onSecurityPolicyViolation: null,\n onSeeked: null,\n onSeeking: null,\n onSelect: null,\n onSlotChange: null,\n onStalled: null,\n onStorage: null,\n onSubmit: null,\n onSuspend: null,\n onTimeUpdate: null,\n onToggle: null,\n onUnhandledRejection: null,\n onUnload: null,\n onVolumeChange: null,\n onWaiting: null,\n onWheel: null,\n open: boolean,\n optimum: number,\n pattern: null,\n ping: spaceSeparated,\n placeholder: null,\n playsInline: boolean,\n poster: null,\n preload: null,\n readOnly: boolean,\n referrerPolicy: null,\n rel: spaceSeparated,\n required: boolean,\n reversed: boolean,\n rows: number,\n rowSpan: number,\n sandbox: spaceSeparated,\n scope: null,\n scoped: boolean,\n seamless: boolean,\n selected: boolean,\n shape: null,\n size: number,\n sizes: null,\n slot: null,\n span: number,\n spellCheck: booleanish,\n src: null,\n srcDoc: null,\n srcLang: null,\n srcSet: null,\n start: number,\n step: null,\n style: null,\n tabIndex: number,\n target: null,\n title: null,\n translate: null,\n type: null,\n typeMustMatch: boolean,\n useMap: null,\n value: booleanish,\n width: number,\n wrap: null,\n\n // Legacy.\n // See: https://html.spec.whatwg.org/#other-elements,-attributes-and-apis\n align: null, // Several. Use CSS `text-align` instead,\n aLink: null, // ``. Use CSS `a:active {color}` instead\n archive: spaceSeparated, // ``. List of URIs to archives\n axis: null, // `
` and ``. Use `scope` on ``\n background: null, // ``. Use CSS `background-image` instead\n bgColor: null, // `` and table elements. Use CSS `background-color` instead\n border: number, // ``. Use CSS `border-width` instead,\n borderColor: null, // `
`. Use CSS `border-color` instead,\n bottomMargin: number, // ``\n cellPadding: null, // `
`\n cellSpacing: null, // `
`\n char: null, // Several table elements. When `align=char`, sets the character to align on\n charOff: null, // Several table elements. When `char`, offsets the alignment\n classId: null, // ``\n clear: null, // `
`. Use CSS `clear` instead\n code: null, // ``\n codeBase: null, // ``\n codeType: null, // ``\n color: null, // `` and `
`. Use CSS instead\n compact: boolean, // Lists. Use CSS to reduce space between items instead\n declare: boolean, // ``\n event: null, // `