diff --git "a/tools/ui/node_modules/prettier-plugin-svelte/plugin.js" "b/tools/ui/node_modules/prettier-plugin-svelte/plugin.js" new file mode 100644--- /dev/null +++ "b/tools/ui/node_modules/prettier-plugin-svelte/plugin.js" @@ -0,0 +1,2667 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var prettierPluginBabel = require('prettier/plugins/babel'); +var prettier = require('prettier'); +var compiler = require('svelte/compiler'); + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { + return e[k]; + } + }); + } + }); + } + n['default'] = e; + return Object.freeze(n); +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +// @see http://xahlee.info/js/html5_non-closing_tag.html +const selfClosingTags = [ + 'area', + 'base', + 'br', + 'col', + 'embed', + 'hr', + 'img', + 'input', + 'link', + 'meta', + 'param', + 'source', + 'track', + 'wbr', +]; +// https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements#Elements +const blockElements = [ + 'address', + 'article', + 'aside', + 'blockquote', + 'details', + 'dialog', + 'dd', + 'div', + 'dl', + 'dt', + 'fieldset', + 'figcaption', + 'figure', + 'footer', + 'form', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'header', + 'hgroup', + 'hr', + 'li', + 'main', + 'nav', + 'ol', + 'p', + 'pre', + 'section', + 'table', + 'ul', +]; +/** + * HTML attributes that we may safely reformat (trim whitespace, add or remove newlines) + */ +const formattableAttributes = [ +// None at the moment +// Prettier HTML does not format attributes at all +// and to be consistent we leave this array empty for now +]; + +// Base64 string encoding and decoding module. +// Uses Buffer for Node.js and btoa/atob for browser environments. +// We use TextEncoder/TextDecoder for browser environments because +// they can handle non-ASCII characters, unlike btoa/atob. +const stringToBase64 = typeof Buffer !== 'undefined' + ? (str) => Buffer.from(str).toString('base64') + : (str) => btoa(new TextEncoder() + .encode(str) + .reduce((acc, byte) => acc + String.fromCharCode(byte), '')); +const base64ToString = typeof Buffer !== 'undefined' + ? (str) => Buffer.from(str, 'base64').toString() + : (str) => new TextDecoder().decode(Uint8Array.from(atob(str), (c) => c.charCodeAt(0))); + +const snippedTagContentAttribute = '✂prettier:content✂'; +const scriptRegex = /|'"\/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"\/\s]+)*\s*)>([^]*?)<\/script>/g; +const styleRegex = /|'"\/\s]+=(?:"[^"]*"|'[^']*'|[^>\s]+)|\s+[^=>'"\/\s]+)*\s*)>([^]*?)<\/style>/g; +const langTsRegex = /\slang=["']?ts["']?/; +function snipScriptAndStyleTagContent(source) { + let scriptMatchSpans = getMatchIndexes('script'); + let styleMatchSpans = getMatchIndexes('style'); + let isTypescript = false; + const text = snipTagContent(snipTagContent(source, 'script', '{}', styleMatchSpans), 'style', '', scriptMatchSpans); + return { text, isTypescript }; + function getMatchIndexes(tagName) { + const regex = getRegexp(tagName); + const indexes = []; + let match = null; + while ((match = regex.exec(source)) != null) { + if (source.slice(match.index, match.index + 4) !== '`. With `svelteSortOrder`, that comment must stay below the + * printed block. Peel optional whitespace-only text nodes + the first HTML comment after `hoistedEnd` + * only when it matches `#endregion` and there is no non-whitespace in `originalText` between positions. + */ +function extractRegionEndTrailAfterHoistedEnd(nodes, hoistedEnd) { + const idx = nodes.findIndex((child) => child.start >= hoistedEnd); + if (idx === -1) { + return; + } + let whitespace; + for (let i = idx; i < Math.min(idx + 2, nodes.length); i++) { + const child = nodes[i]; + if (child.type === 'Text' && isOnlyHtmlCollapseWhitespace(getUnencodedText(child))) { + whitespace = child; + continue; + } + else if (child.type === 'Comment' && /#\s*endregion\b/i.test(child.data)) { + nodes.splice(idx, i + 1 - idx); + return { whitespace, comment: child }; + } + return; + } +} +function printRegionEndTrailDoc(trail) { + const pieces = []; + if (trail.whitespace) { + const doc = printWhitespace(getUnencodedText(trail.whitespace).replace(/^\r?\n/, '')); + pieces.push(...(Array.isArray(doc) ? doc : [doc])); + } + pieces.push(printComment(trail.comment)); + return group([...pieces, hardline]); +} +function mergeAdjacentTextNodesInFragment(nodes) { + for (let i = 0; i < nodes.length - 1;) { + const current = nodes[i]; + const next = nodes[i + 1]; + if (current.type === 'Text' && next.type === 'Text') { + // Trim right side so that something like + // + //
hello
+ // + //
world
+ // + // doesn't become + // + //
hello
+ // + //
world
+ trimTextNodeRight(current); + current.raw += next.raw; + current.data += next.data; + current.end = next.end; + nodes.splice(i + 1, 1); + } + else { + i++; + } + } +} +function printSvelteOptions(path, parserOptions, print, rootOptions, leadingCommentDoc) { + const bracketSameLine = isBracketSameLine(parserOptions); + const optsNode = { + type: 'Options', + name: 'svelte:options', + start: rootOptions.start, + end: rootOptions.end, + attributes: rootOptions.attributes, + }; + let doc = group([ + [ + '<', + optsNode.name, + indent(group([ + ...path.call((optionsPath) => optionsPath.map(printWithPrependedAttributeLine(optsNode, parserOptions, print), 'attributes'), 'options'), + bracketSameLine ? '' : dedent(line), + ])), + ...[bracketSameLine ? ' ' : '', '/>'], + ], + hardline, + ]); + if (leadingCommentDoc) { + doc = group([leadingCommentDoc, hardline, doc]); + } + return doc; +} +function printTopLevelParts(n, options, path, print) { + if (options.svelteSortOrder === 'none') { + if (n.options) { + const nodes = n.fragment.nodes; + const has_options_node = nodes.some((node) => node.type === 'Options'); + if (!has_options_node) { + nodes.push({ + type: 'Options', + name: 'svelte:options', + start: n.options.start, + end: n.options.end, + attributes: n.options.attributes, + }); + nodes.sort((a, b) => a.start - b.start); + } + } + const topLevelPartsByEnd = {}; + const topLevelPartsByStart = {}; + if (n.module) { + topLevelPartsByEnd[n.module.end] = n.module; + topLevelPartsByStart[n.module.start] = n.module; + } + if (n.instance) { + topLevelPartsByEnd[n.instance.end] = n.instance; + topLevelPartsByStart[n.instance.start] = n.instance; + } + if (n.css) { + topLevelPartsByEnd[n.css.end] = n.css; + topLevelPartsByStart[n.css.start] = n.css; + } + const children = n.fragment.nodes; + for (let i = 0; i < children.length; i++) { + const node = children[i]; + if (topLevelPartsByEnd[node.start]) { + children.splice(i, 0, topLevelPartsByEnd[node.start]); + delete topLevelPartsByEnd[node.start]; + } + else if (i === children.length - 1 && topLevelPartsByStart[node.end]) { + children.push(topLevelPartsByStart[node.end]); + } + } + mergeAdjacentTextNodesInFragment(children); + const result = path.call(print, 'fragment'); + if (options.insertPragma && !hasPragma(options.originalText)) { + return [``, hardline, result]; + } + else { + return result; + } + } + const parts = { + options: [], + scripts: [], + markup: [], + styles: [], + }; + const regionEndTrail = {}; + for (const { kind, end } of hoistedEndsDescending(n)) { + const trail = extractRegionEndTrailAfterHoistedEnd(n.fragment.nodes, end); + if (trail) { + regionEndTrail[kind] = trail; + } + } + // scripts + if (n.module) { + let doc = path.call(print, 'module'); + const trail = regionEndTrail.module; + if (trail) { + doc = group([doc, printRegionEndTrailDoc(trail)]); + } + parts.scripts.push(doc); + } + if (n.instance) { + let doc = path.call(print, 'instance'); + const trail = regionEndTrail.instance; + if (trail) { + doc = group([doc, printRegionEndTrailDoc(trail)]); + } + parts.scripts.push(doc); + } + // styles + if (n.css) { + let doc = path.call(print, 'css'); + const trail = regionEndTrail.css; + if (trail) { + doc = group([doc, printRegionEndTrailDoc(trail)]); + } + parts.styles.push(doc); + } + // markup + if (n.options) { + let doc = printSvelteOptions(path, options, print, n.options, stripSvelteOptionsComment(n)); + const trail = regionEndTrail.options; + if (trail) { + doc = group([doc, printRegionEndTrailDoc(trail)]); + } + parts.options.push(doc); + } + mergeAdjacentTextNodesInFragment(n.fragment.nodes); + const htmlDoc = path.call(print, 'fragment'); + if (htmlDoc) { + parts.markup.push(htmlDoc); + } + const docs = flatten(parseSortOrder(options.svelteSortOrder).map((p) => parts[p])); + // Need to reset these because they are global and could affect the next formatting run + ignoreNext = false; + ignoreRange = false; + // If this is invoked as an embed of markdown, remove the last hardline. + // The markdown parser tries this, too, but fails because it does not + // recurse into concats. Doing this will prevent an empty line + // at the end of the embedded code block. + if (options.parentParser === 'markdown') { + const lastDoc = docs[docs.length - 1]; + trimRight([lastDoc], isLine); + } + if (options.insertPragma && !hasPragma(options.originalText)) { + return [``, hardline, group(docs)]; + } + else { + return group([join(hardline, docs)]); + } +} +function printAttributeNodeValue(path, print, quotes, node) { + const valueDocs = Array.isArray(node.value) + ? path.map((childPath) => childPath.call(print), 'value') + : [path.call(print, 'value')]; + if (!quotes || !formattableAttributes.includes(node.name)) { + return valueDocs; + } + else { + return indent(group(trim(valueDocs, isLine))); + } +} +function printSvelteBlockChildren(path, print, options) { + var _a; + const fragment = path.node; + const children = (_a = fragment === null || fragment === void 0 ? void 0 : fragment.nodes) !== null && _a !== void 0 ? _a : []; + if (children.length === 0) { + return ''; + } + const whitespaceAtStartOfBlock = checkWhitespaceAtStartOfSvelteBlock(fragment, options); + const whitespaceAtEndOfBlock = checkWhitespaceAtEndOfSvelteBlock(fragment, options); + const startline = whitespaceAtStartOfBlock === 'none' + ? '' + : whitespaceAtEndOfBlock === 'line' || whitespaceAtStartOfBlock === 'line' + ? hardline + : line; + const endline = whitespaceAtEndOfBlock === 'none' + ? '' + : whitespaceAtEndOfBlock === 'line' || whitespaceAtStartOfBlock === 'line' + ? hardline + : line; + const firstChild = children[0]; + const lastChild = children[children.length - 1]; + if (isTextNodeStartingWithWhitespace(firstChild)) { + trimTextNodeLeft(firstChild); + } + if (isTextNodeEndingWithWhitespace(lastChild)) { + trimTextNodeRight(lastChild); + } + return [indent([startline, group(printChildren(path, print, options))]), endline]; +} +function printBlockFragment(path, print, options, to) { + return path.call((fragment_path) => printSvelteBlockChildren(fragment_path, print, options), to); +} +function printIfBlockAlternate(path, print, options) { + const node = path.node; + const alternate = node.alternate; + if (!alternate) { + return ''; + } + if (alternate.type === 'Fragment') { + if (alternate.nodes.length === 1 && + alternate.nodes[0].type === 'IfBlock' && + alternate.nodes[0].elseif) { + const def = [ + '{:else if ', + path.call((if_path) => printJS(if_path, print, 'test'), 'alternate', 'nodes', 0), + '}', + path.call((if_path) => printBlockFragment(if_path, print, options, 'consequent'), 'alternate', 'nodes', 0), + ]; + if (alternate.nodes[0].alternate) { + def.push(path.call((if_path) => printIfBlockAlternate(if_path, print, options), 'alternate', 'nodes', 0)); + } + return def; + } + return ['{:else}', printBlockFragment(path, print, options, 'alternate')]; + } + return ['{:else}', printBlockFragment(path, print, options, 'alternate')]; +} +function printEachBlockFallback(path, print, options) { + const node = path.node; + const fallback = node.fallback; + if (!fallback) { + return ''; + } + return ['{:else}', printBlockFragment(path, print, options, 'fallback')]; +} +function printPre(originalText, path, print) { + var _a; + const result = []; + const fragment = path.node; + const children = (_a = fragment === null || fragment === void 0 ? void 0 : fragment.nodes) !== null && _a !== void 0 ? _a : []; + if (children.length === 0) { + return ''; + } + const length = children.length; + for (let i = 0; i < length; i++) { + const child = children[i]; + if (child.type === 'Text') { + const lines = originalText.substring(child.start, child.end).split(/\r?\n/); + lines.forEach((line, j) => { + if (j > 0) + result.push(literalline); + result.push(line); + }); + } + else { + result.push(path.call(print, 'nodes', i)); + } + } + return result; +} +function printChildren(path, print, options) { + var _a; + const current_value = path.node; + if (isPreTagContent(path)) { + return path.map(print, 'nodes'); + } + const original_children = (_a = current_value.nodes) !== null && _a !== void 0 ? _a : []; + const prepared_children = prepareChildren(original_children); + if (prepared_children.length === 0) { + return ''; + } + const childDocs = []; + let handleWhitespaceOfPrevTextNode = false; + for (let i = 0; i < prepared_children.length; i++) { + const childNode = prepared_children[i].node; + if (childNode.type === 'Text') { + handleTextChild(i, childNode); + } + else if (isBlockElement(childNode, options)) { + handleBlockChild(i); + } + else if (isInlineElement(path, options, childNode)) { + handleInlineChild(i); + } + else { + childDocs.push(printChild(i)); + handleWhitespaceOfPrevTextNode = false; + } + } + // If there's at least one block element and more than one node, break content + const forceBreakContent = prepared_children.length > 1 && + prepared_children.some((child) => isBlockElement(child.node, options)); + if (forceBreakContent) { + childDocs.push(breakParent); + } + return childDocs; + function printChild(idx) { + return path.call(print, 'nodes', prepared_children[idx].index); + } + /** + * Print inline child. Hug whitespace of previous text child if there was one. + */ + function handleInlineChild(idx) { + if (handleWhitespaceOfPrevTextNode) { + childDocs.push(group([line, printChild(idx)])); + } + else { + childDocs.push(printChild(idx)); + } + handleWhitespaceOfPrevTextNode = false; + } + /** + * Print block element. Add softlines around it if needed + * so it breaks into a separate line if children are broken up. + * Don't add lines at the start/end if it's the first/last child because this + * kind of whitespace handling is done in the parent already. + */ + function handleBlockChild(idx) { + var _a, _b; + const prevChild = (_a = prepared_children[idx - 1]) === null || _a === void 0 ? void 0 : _a.node; + if (prevChild && + !isBlockElement(prevChild, options) && + (prevChild.type !== 'Text' || + handleWhitespaceOfPrevTextNode || + !isTextNodeEndingWithWhitespace(prevChild))) { + childDocs.push(softline); + } + childDocs.push(printChild(idx)); + const nextChild = (_b = prepared_children[idx + 1]) === null || _b === void 0 ? void 0 : _b.node; + if (nextChild && + (nextChild.type !== 'Text' || + // Only handle text which starts with a whitespace and has text afterwards, + // or is empty but followed by an inline element. The latter is done + // so that if the children break, the inline element afterwards is in a separate line. + ((!isEmptyTextNode(nextChild) || + (prepared_children[idx + 2] && + isInlineElement(path, options, prepared_children[idx + 2].node))) && + !isTextNodeStartingWithLinebreak(nextChild)))) { + childDocs.push(softline); + } + handleWhitespaceOfPrevTextNode = false; + } + /** + * Print text child. First/last child white space handling + * is done in parent already. By definition of the Svelte AST, + * a text node always is inbetween other tags. Add hardlines + * if the users wants to have them inbetween. + * If the text is trimmed right, toggle flag telling + * subsequent (inline)block element to alter its printing logic + * to check if they need to hug or print lines themselves. + */ + function handleTextChild(idx, childNode) { + handleWhitespaceOfPrevTextNode = false; + if (idx === 0 || idx === prepared_children.length - 1) { + childDocs.push(printChild(idx)); + return; + } + const prevNode = prepared_children[idx - 1].node; + const nextNode = prepared_children[idx + 1].node; + if (isTextNodeStartingWithWhitespace(childNode) && + // If node is empty, go straight through to checking the right end + !isEmptyTextNode(childNode)) { + if (isInlineElement(path, options, prevNode) && + !isTextNodeStartingWithLinebreak(childNode)) { + trimTextNodeLeft(childNode); + const lastChildDoc = childDocs.pop(); + childDocs.push(group([lastChildDoc, line])); + } + if (isBlockElement(prevNode, options) && !isTextNodeStartingWithLinebreak(childNode)) { + trimTextNodeLeft(childNode); + } + } + if (isTextNodeEndingWithWhitespace(childNode)) { + if (isInlineElement(path, options, nextNode) && + !isTextNodeEndingWithLinebreak(childNode)) { + handleWhitespaceOfPrevTextNode = !prevNode || !isBlockElement(prevNode, options); + trimTextNodeRight(childNode); + } + if (isBlockElement(nextNode, options) && !isTextNodeEndingWithLinebreak(childNode, 2)) { + handleWhitespaceOfPrevTextNode = !prevNode || !isBlockElement(prevNode, options); + trimTextNodeRight(childNode); + } + } + childDocs.push(printChild(idx)); + } +} +function prepareChildren(children, path) { + const prepared = []; + for (let idx = 0; idx < children.length; idx++) { + const currentChild = children[idx]; + if (currentChild.type === 'Text' && getUnencodedText(currentChild) === '') { + continue; + } + prepared.push({ node: currentChild, index: idx }); + } + return prepared; +} +/** + * Split the text into words separated by whitespace. Replace the whitespaces by lines, + * collapsing multiple whitespaces into a single line. + * + * If the text starts or ends with multiple newlines, two of those should be kept. + */ +function splitTextToDocs(node) { + const text = getUnencodedText(node); + const lines = text.split(/[\t\n\f\r ]+/); + let docs = join(line, lines).filter((doc) => doc !== ''); + if (startsWithLinebreak(text)) { + docs[0] = hardline; + } + if (startsWithLinebreak(text, 2)) { + docs = [hardline, ...docs]; + } + if (endsWithLinebreak(text)) { + docs[docs.length - 1] = hardline; + } + if (endsWithLinebreak(text, 2)) { + docs = [...docs, hardline]; + } + return docs; +} +function printJS(path, print, name) { + return path.call(print, name); +} +function expandNode(node, original) { + let str = _expandNode(node, original); + if (node === null || node === void 0 ? void 0 : node.typeAnnotation) { + str += + ': ' + + original.slice(node.typeAnnotation.typeAnnotation.start, node.typeAnnotation.typeAnnotation.end); + } + return str; +} +function _expandNode(node, original, parent) { + var _a, _b; + if (node === null) { + return ''; + } + if (typeof node === 'string') { + // pre-v3.20 AST + return ' ' + node; + } + switch (node.type) { + case 'ArrayExpression': + case 'ArrayPattern': + return (' [' + + node.elements + // handle null specifically here; else it would become the empty string, but that would mean + // fewer elements in the array, which would change the meaning of the array + .map((el) => (el === null ? ' ' : _expandNode(el, original))) + .join(',') + .slice(1) + + ']'); + case 'AssignmentPattern': + return _expandNode(node.left, original) + ' =' + _expandNode(node.right, original); + case 'Identifier': + return ' ' + node.name; + case 'Literal': + return ' ' + node.raw; + case 'ObjectExpression': + return (' {' + + node.properties.map((p) => _expandNode(p, original, node)).join(',') + + ' }'); + case 'ObjectPattern': + return (' {' + node.properties.map((p) => _expandNode(p, original)).join(',') + ' }'); + case 'Property': { + let computedKeyInner = ''; + if (node.computed) { + computedKeyInner = + typeof ((_a = node.key) === null || _a === void 0 ? void 0 : _a.start) === 'number' && typeof ((_b = node.key) === null || _b === void 0 ? void 0 : _b.end) === 'number' + ? original.slice(node.key.start, node.key.end) + : _expandNode(node.key, original).trim(); + } + if (node.value.type === 'ObjectPattern' || node.value.type === 'ArrayPattern') { + const keyStr = node.computed ? ' [' + computedKeyInner + ']' : ' ' + node.key.name; + return keyStr + ':' + _expandNode(node.value, original); + } + else if ((node.value.type === 'Identifier' && node.key.name !== node.value.name) || + (parent && parent.type === 'ObjectExpression')) { + const keyStr = node.computed + ? ' [' + computedKeyInner + ']' + : _expandNode(node.key, original); + return keyStr + ':' + _expandNode(node.value, original); + } + else { + return _expandNode(node.value, original); + } + } + case 'RestElement': + return ' ...' + node.argument.name; + } + console.error(JSON.stringify(node, null, 4)); + throw new Error('unknown node type: ' + node.type); +} +function printComment(node) { + let text = node.data; + if (hasSnippedContent(text)) { + text = unsnipContent(text); + } + return group(['']); +} +function printWhitespace(text) { + const hasWhiteSpace = text.length > 0; + const hasOneOrMoreNewlines = /\n/.test(text); + const hasTwoOrMoreNewlines = /\n\r?[\t\n\f\r ]*\n\r?/.test(text); + if (hasTwoOrMoreNewlines) { + return [hardline, hardline]; + } + if (hasOneOrMoreNewlines) { + return hardline; + } + if (hasWhiteSpace) { + return line; + } + return ''; +} + +function getText(node, options, unsnip = false) { + const leadingComments = node.leadingComments; + const text = options.originalText.slice(options.locStart( + // if there are comments before the node they are not included + // in the `start` of the node itself + (leadingComments && leadingComments[0]) || node), options.locEnd(node)); + if (!unsnip || !hasSnippedContent(text)) { + return text; + } + return unsnipContent(text); +} + +const { builders: { group: group$1, hardline: hardline$1, softline: softline$1, indent: indent$1, dedent: dedent$1, literalline: literalline$1 }, utils: { removeLines }, } = prettier.doc; +const leaveAlone = new Set([ + 'Script', + 'StyleSheet', + 'Identifier', + 'MemberExpression', + 'CallExpression', + 'ArrowFunctionExpression', +]); +const dontTraverse = new Set(['start', 'end', 'type']); +function getVisitorKeys(node, nonTraversableKeys) { + return Object.keys(node).filter((key) => { + return !nonTraversableKeys.has(key) && !leaveAlone.has(node.type) && !dontTraverse.has(key); + }); +} +// Embed works like this in Prettier v3: +// - do depth first traversal of all node properties +// - deepest property is calling embed first +// - if embed returns a function, it will be called after the traversal in a second pass, in the same order (deepest first) +// For performance reasons we try to only return functions when we're sure we need to transform something. +function embed(path, _options) { + var _a, _b, _c, _d, _e, _f, _g; + const node = path.getNode(); + const options = _options; + if (!options.locStart || !options.locEnd || !options.originalText) { + throw new Error('Missing required options'); + } + if (isASTNode(node)) { + assignCommentsToNodes(node); + attachAttributeComments(node, options.originalText); + return null; + } + // embed does depth first traversal with deepest node called first, therefore we need to + // check the parent to see if we are inside an expression that should be embedded. + const parent = path.getParentNode(); + const printJsExpression = () => parent.expression ? printJS$1(parent, 'expression', {}) : undefined; + const printSvelteBlockJS = (name) => printJS$1(parent, name, { forceSingleLine: true }); + switch (parent.type) { + case 'IfBlock': + printSvelteBlockJS('test'); + break; + case 'AwaitBlock': + case 'KeyBlock': + printSvelteBlockJS('expression'); + break; + case 'EachBlock': + printSvelteBlockJS('expression'); + printSvelteBlockJS('key'); + break; + case 'SnippetBlock': + // We merge the two parts into one expression to then treat it like a function + if (node === parent.expression) { + parent.expression.end = + options.originalText.indexOf(')', (_g = (_d = (_c = (_b = (_a = parent.parameters) === null || _a === void 0 ? void 0 : _a[parent.parameters.length - 1]) === null || _b === void 0 ? void 0 : _b.typeAnnotation) === null || _c === void 0 ? void 0 : _c.end) !== null && _d !== void 0 ? _d : (_f = (_e = parent.parameters) === null || _e === void 0 ? void 0 : _e[parent.parameters.length - 1]) === null || _f === void 0 ? void 0 : _f.end) !== null && _g !== void 0 ? _g : parent.expression.end) + 1; + parent.parameters = null; + node.isJS = true; + node.asFunction = true; + } + break; + case 'RegularElement': + case 'SvelteElement': + printJS$1(parent, 'tag', {}); + break; + case 'ExpressionTag': + printJS$1(parent, 'expression', { + forceSingleQuote: isInsideQuotedAttribute(path), + }); + break; + case 'HtmlTag': + printJS$1(parent, 'expression', {}); + break; + case 'SpreadAttribute': + printJS$1(parent, 'expression', {}); + break; + case 'AttachTag': + printJS$1(parent, 'expression', {}); + break; + case 'VariableDeclarator': { + const declaration = path.getParentNode(1); + const constTag = path.getParentNode(2); + if ((declaration === null || declaration === void 0 ? void 0 : declaration.type) === 'VariableDeclaration' && (constTag === null || constTag === void 0 ? void 0 : constTag.type) === 'ConstTag') { + constTag.declaration = parent; + printJS$1(constTag, 'declaration', { removeParentheses: true }); + } + break; + } + case 'BindDirective': + printJS$1(parent, 'expression', { + removeParentheses: parent.expression.type === 'SequenceExpression', + surroundWithSoftline: true, + }); + break; + case 'RenderTag': + if (node === parent.expression) { + printJS$1(parent, 'expression', {}); + } + break; + case 'DeclarationTag': + if (node === parent.declaration) { + printJS$1(parent, 'declaration', { asStatement: true }); + } + break; + case 'OnDirective': + case 'BindDirective': + case 'ClassDirective': + case 'LetDirective': + case 'TransitionDirective': + case 'UseDirective': + case 'AnimateDirective': + case 'SvelteComponent': + printJsExpression(); + break; + } + if (node.isJS) { + return (textToDoc) => __awaiter(this, void 0, void 0, function* () { + try { + const embeddedOptions = { + // Prettier only allows string references as parsers from v3 onwards, + // so we need to have another public parser and defer to that + parser: node.asStatement + ? options._svelte_ts + ? 'svelteTSStatementParser' + : 'svelteStatementParser' + : options._svelte_ts + ? 'svelteTSExpressionParser' + : 'svelteExpressionParser', + singleQuote: node.forceSingleQuote ? true : options.singleQuote, + _svelte_asFunction: node.asFunction, + }; + // If we have snipped content, it was done wrongly and we need to unsnip it. + // This happens for example for {@html ``} + const text = getText(node, options, true); + let docs = yield textToDoc(node.asStatement + ? text + : node.asFunction + ? forceIntoFunction(text) + : forceIntoExpression(text), embeddedOptions); + if (node.asStatement) { + trimRight([docs], (d) => d === ';'); + } + if (node.forceSingleLine) { + docs = removeLines(docs); + } + if (node.removeParentheses) { + docs = removeParentheses(docs); + } + if (node.asFunction) { + if (Array.isArray(docs) && typeof docs[0] === 'string') { + docs[0] = docs[0].replace('function ', ''); + docs.splice(-1, 1); + } + else { + throw new Error('Prettier AST changed, asFunction logic needs to change'); + } + } + if (node.surroundWithSoftline) { + docs = group$1(indent$1([softline$1, group$1(docs), dedent$1(softline$1)])); + } + return docs; + } + catch (e) { + return getText(node, options, true); + } + }); + } + const embedType = (tag, parser, isTopLevel) => { + return (textToDoc, print) => __awaiter(this, void 0, void 0, function* () { + return embedTag(tag, options.originalText, path, (content) => formatBodyContent(content, parser, textToDoc, options), print, isTopLevel, options); + }); + }; + const embedScript = (isTopLevel) => embedType('script', + // Use babel-ts as fallback because the absence does not mean the content is not TS, + // the user could have set the default language. babel-ts will format things a little + // bit different though, especially preserving parentheses around dot notation which + // fixes https://github.com/sveltejs/prettier-plugin-svelte/issues/218 + isTypeScript(node) ? 'typescript' : isJSON(node) ? 'json' : 'babel-ts', isTopLevel); + const embedStyle = (isTopLevel) => embedType('style', isLess(node) ? 'less' : isScss(node) ? 'scss' : 'css', isTopLevel); + const embedPug = () => embedType('template', 'pug', false); + switch (node.type) { + case 'Script': + return embedScript(true); + case 'StyleSheet': + return embedStyle(true); + case 'RegularElement': { + if (node.name === 'script') { + return embedScript(false); + } + else if (node.name === 'style') { + return embedStyle(false); + } + else if (isPugTemplate(node)) { + return embedPug(); + } + } + } + return null; +} +function forceIntoExpression(statement) { + // note the trailing newline: if the statement ends in a // comment, + // we can't add the closing bracket right afterwards + return `(${statement}\n)`; +} +function forceIntoFunction(statement) { + return `function ${statement} {}`; +} +function preformattedBody(str) { + if (!str) { + return ''; + } + const firstNewline = /^[\t\f\r ]*\n/; + const lastNewline = /\n[\t\f\r ]*$/; + // If we do not start with a new line prettier might try to break the opening tag + // to keep it together with the string. Use a literal line to skip indentation. + return [literalline$1, str.replace(firstNewline, '').replace(lastNewline, ''), hardline$1]; +} +function getSnippedContent(node) { + const encodedContent = getAttributeTextValue(snippedTagContentAttribute, node); + if (encodedContent) { + return base64ToString(encodedContent); + } + else { + return ''; + } +} +function formatBodyContent(content, parser, textToDoc, options) { + return __awaiter(this, void 0, void 0, function* () { + try { + const body = yield textToDoc(content, { parser }); + if (parser === 'pug' && typeof body === 'string') { + // Pug returns no docs but a final string. + // Therefore prepend the line offsets + const whitespace = options.useTabs + ? '\t' + : ' '.repeat(options.pugTabWidth && options.pugTabWidth > 0 + ? options.pugTabWidth + : options.tabWidth); + const pugBody = body + .split('\n') + .map((line) => (line ? whitespace + line : line)) + .join('\n'); + return [hardline$1, pugBody]; + } + const indentIfDesired = (doc) => options.svelteIndentScriptAndStyle ? indent$1(doc) : doc; + trimRight([body], isLine); + return [indentIfDesired([hardline$1, body]), hardline$1]; + } + catch (error) { + if (process.env.PRETTIER_DEBUG) { + throw error; + } + // We will wind up here if there is a syntax error in the embedded code. If we throw an error, + // prettier will try to print the node with the printer. That will fail with a hard-to-interpret + // error message (e.g. "Unsupported node type", referring to `