'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var require$$0 = require('source-map'); var parser$1 = require('@babel/parser'); var url = require('url'); var path = require('path'); var require$$0$1 = require('fs'); var require$$2 = require('util'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0); var path__default = /*#__PURE__*/_interopDefaultLegacy(path); var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1); var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var splitRE$2 = /\r?\n/g; var emptyRE$1 = /^\s*$/; var needFixRE = /^(\r?\n)*[\t\s]/; var deIndent = function deindent (str) { if (!needFixRE.test(str)) { return str } var lines = str.split(splitRE$2); var min = Infinity; var type, cur, c; for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (!emptyRE$1.test(line)) { if (!type) { c = line.charAt(0); if (c === ' ' || c === '\t') { type = c; cur = count(line, type); if (cur < min) { min = cur; } } else { return str } } else { cur = count(line, type); if (cur < min) { min = cur; } } } } return lines.map(function (line) { return line.slice(min) }).join('\n') }; function count (line, type) { var i = 0; while (line.charAt(i) === type) { i++; } return i } const emptyObject = Object.freeze({}); const isArray = Array.isArray; // These helpers produce better VM code in JS engines due to their // explicitness and function inlining. function isUndef(v) { return v === undefined || v === null; } function isDef(v) { return v !== undefined && v !== null; } function isTrue(v) { return v === true; } function isFalse(v) { return v === false; } /** * Check if value is primitive. */ function isPrimitive(value) { return (typeof value === 'string' || typeof value === 'number' || // $flow-disable-line typeof value === 'symbol' || typeof value === 'boolean'); } function isFunction(value) { return typeof value === 'function'; } /** * Quick object check - this is primarily used to tell * objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject$1(obj) { return obj !== null && typeof obj === 'object'; } /** * Get the raw type string of a value, e.g., [object Object]. */ const _toString = Object.prototype.toString; function toRawType(value) { return _toString.call(value).slice(8, -1); } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject(obj) { return _toString.call(obj) === '[object Object]'; } /** * Check if val is a valid array index. */ function isValidArrayIndex(val) { const n = parseFloat(String(val)); return n >= 0 && Math.floor(n) === n && isFinite(val); } function isPromise(val) { return (isDef(val) && typeof val.then === 'function' && typeof val.catch === 'function'); } /** * Convert a value to a string that is actually rendered. */ function toString$2(val) { return val == null ? '' : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString) ? JSON.stringify(val, replacer, 2) : String(val); } function replacer(_key, val) { // avoid circular deps from v3 if (val && val.__v_isRef) { return val.value; } return val; } /** * Convert an input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber(val) { const n = parseFloat(val); return isNaN(n) ? val : n; } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap(str, expectsLowerCase) { const map = Object.create(null); const list = str.split(','); for (let i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? val => map[val.toLowerCase()] : val => map[val]; } /** * Check if a tag is a built-in tag. */ const isBuiltInTag = makeMap('slot,component', true); /** * Check if an attribute is a reserved attribute. */ const isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); /** * Check whether an object has the property. */ const hasOwnProperty$1 = Object.prototype.hasOwnProperty; function hasOwn(obj, key) { return hasOwnProperty$1.call(obj, key); } /** * Create a cached version of a pure function. */ function cached(fn) { const cache = Object.create(null); return function cachedFn(str) { const hit = cache[str]; return hit || (cache[str] = fn(str)); }; } /** * Camelize a hyphen-delimited string. */ const camelizeRE = /-(\w)/g; const camelize = cached((str) => { return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : '')); }); /** * Capitalize a string. */ const capitalize = cached((str) => { return str.charAt(0).toUpperCase() + str.slice(1); }); /** * Hyphenate a camelCase string. */ const hyphenateRE = /\B([A-Z])/g; const hyphenate = cached((str) => { return str.replace(hyphenateRE, '-$1').toLowerCase(); }); /** * Mix properties into target object. */ function extend(to, _from) { for (const key in _from) { to[key] = _from[key]; } return to; } /** * Merge an Array of Objects into a single Object. */ function toObject(arr) { const res = {}; for (let i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res; } /* eslint-disable no-unused-vars */ /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/). */ function noop(a, b, c) { } /** * Always return false. */ const no = (a, b, c) => false; /* eslint-enable no-unused-vars */ /** * Return the same value. */ const identity = (_) => _; /** * Generate a string containing static keys from compiler modules. */ function genStaticKeys$1(modules) { return modules .reduce((keys, m) => keys.concat(m.staticKeys || []), []) .join(','); } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual(a, b) { if (a === b) return true; const isObjectA = isObject$1(a); const isObjectB = isObject$1(b); if (isObjectA && isObjectB) { try { const isArrayA = Array.isArray(a); const isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return (a.length === b.length && a.every((e, i) => { return looseEqual(e, b[i]); })); } else if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime(); } else if (!isArrayA && !isArrayB) { const keysA = Object.keys(a); const keysB = Object.keys(b); return (keysA.length === keysB.length && keysA.every(key => { return looseEqual(a[key], b[key]); })); } else { /* istanbul ignore next */ return false; } } catch (e) { /* istanbul ignore next */ return false; } } else if (!isObjectA && !isObjectB) { return String(a) === String(b); } else { return false; } } /** * Return the first index at which a loosely equal value can be * found in the array (if value is a plain object, the array must * contain an object of the same shape), or -1 if it is not present. */ function looseIndexOf(arr, val) { for (let i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) return i; } return -1; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#polyfill function hasChanged(x, y) { if (x === y) { return x === 0 && 1 / x !== 1 / y; } else { return x === x || y === y; } } const isUnaryTag = makeMap('area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr'); // Elements that you can, intentionally, leave open // (and which close themselves) const canBeLeftOpenTag = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source'); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content const isNonPhrasingTag = makeMap('address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track'); /** * unicode letters used for parsing html tags, component names and property paths. * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname * skipping \u10000-\uEFFFF due to it freezing up PhantomJS */ const unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/; /** * Define a property. */ function def(obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Not type-checking this file because it's mostly vendor code. */ // Regular Expressions for parsing tags and attributes const attribute$2 = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; const dynamicArgAttribute = /^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+?\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; const ncname = `[a-zA-Z_][\\-\\.0-9_a-zA-Z${unicodeRegExp.source}]*`; const qnameCapture = `((?:${ncname}\\:)?${ncname})`; const startTagOpen = new RegExp(`^<${qnameCapture}`); const startTagClose = /^\s*(\/?)>/; const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`); const doctype = /^]+>/i; // #7298: escape - to avoid being passed as HTML comment when inlined in page const comment$3 = /^', '"': '"', '&': '&', ' ': '\n', ' ': '\t', ''': "'" }; const encodedAttr = /&(?:lt|gt|quot|amp|#39);/g; const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#39|#10|#9);/g; // #5992 const isIgnoreNewlineTag = makeMap('pre,textarea', true); const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\n'; function decodeAttr(value, shouldDecodeNewlines) { const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr; return value.replace(re, match => decodingMap[match]); } function parseHTML(html, options) { const stack = []; const expectHTML = options.expectHTML; const isUnaryTag = options.isUnaryTag || no; const canBeLeftOpenTag = options.canBeLeftOpenTag || no; let index = 0; let last, lastTag; while (html) { last = html; // Make sure we're not in a plaintext content element like script/style if (!lastTag || !isPlainTextElement(lastTag)) { let textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment$3.test(html)) { const commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { if (options.shouldKeepComment && options.comment) { options.comment(html.substring(4, commentEnd), index, index + commentEnd + 3); } advance(commentEnd + 3); continue; } } // https://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { const conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue; } } // Doctype: const doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue; } // End tag: const endTagMatch = html.match(endTag); if (endTagMatch) { const curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue; } // Start tag: const startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); if (shouldIgnoreFirstNewline(startTagMatch.tagName, html)) { advance(1); } continue; } } let text, rest, next; if (textEnd >= 0) { rest = html.slice(textEnd); while (!endTag.test(rest) && !startTagOpen.test(rest) && !comment$3.test(rest) && !conditionalComment.test(rest)) { // < in plain text, be forgiving and treat it as text next = rest.indexOf('<', 1); if (next < 0) break; textEnd += next; rest = html.slice(textEnd); } text = html.substring(0, textEnd); } if (textEnd < 0) { text = html; } if (text) { advance(text.length); } if (options.chars && text) { options.chars(text, index - text.length, index); } } else { let endTagLength = 0; const stackedTag = lastTag.toLowerCase(); const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(]*>)', 'i')); const rest = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text .replace(//g, '$1') // #7298 .replace(//g, '$1'); } if (shouldIgnoreFirstNewline(stackedTag, text)) { text = text.slice(1); } if (options.chars) { options.chars(text); } return ''; }); index += html.length - rest.length; html = rest; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last) { options.chars && options.chars(html); if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) { options.warn(`Mal-formatted tag at end of template: "${html}"`, { start: index + html.length }); } break; } } // Clean up any remaining tags parseEndTag(); function advance(n) { index += n; html = html.substring(n); } function parseStartTag() { const start = html.match(startTagOpen); if (start) { const match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); let end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(dynamicArgAttribute) || html.match(attribute$2))) { attr.start = index; advance(attr[0].length); attr.end = index; match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match; } } } function handleStartTag(match) { const tagName = match.tagName; const unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag(tagName) && lastTag === tagName) { parseEndTag(tagName); } } const unary = isUnaryTag(tagName) || !!unarySlash; const l = match.attrs.length; const attrs = new Array(l); for (let i = 0; i < l; i++) { const args = match.attrs[i]; const value = args[3] || args[4] || args[5] || ''; const shouldDecodeNewlines = tagName === 'a' && args[1] === 'href' ? options.shouldDecodeNewlinesForHref : options.shouldDecodeNewlines; attrs[i] = { name: args[1], value: decodeAttr(value, shouldDecodeNewlines) }; if (process.env.NODE_ENV !== 'production' && options.outputSourceRange) { attrs[i].start = args.start + args[0].match(/^\s*/).length; attrs[i].end = args.end; } } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs, start: match.start, end: match.end }); lastTag = tagName; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag(tagName, start, end) { let pos, lowerCasedTagName; if (start == null) start = index; if (end == null) end = index; // Find the closest opened tag of the same type if (tagName) { lowerCasedTagName = tagName.toLowerCase(); for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break; } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (let i = stack.length - 1; i >= pos; i--) { if (process.env.NODE_ENV !== 'production' && (i > pos || !tagName) && options.warn) { options.warn(`tag <${stack[i].tag}> has no matching end tag.`, { start: stack[i].start, end: stack[i].end }); } if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } const DEFAULT_FILENAME = 'anonymous.vue'; const splitRE$1 = /\r?\n/g; const replaceRE = /./g; const isSpecialTag = makeMap('script,style,template', true); /** * Parse a single-file component (*.vue) file into an SFC Descriptor Object. */ function parseComponent(source, options = {}) { const sfc = { source, filename: DEFAULT_FILENAME, template: null, script: null, scriptSetup: null, styles: [], customBlocks: [], cssVars: [], errors: [], shouldForceReload: null // attached in parse() by compiler-sfc }; let depth = 0; let currentBlock = null; let warn = msg => { sfc.errors.push(msg); }; if (process.env.NODE_ENV !== 'production' && options.outputSourceRange) { warn = (msg, range) => { const data = { msg }; if (range.start != null) { data.start = range.start; } if (range.end != null) { data.end = range.end; } sfc.errors.push(data); }; } function start(tag, attrs, unary, start, end) { if (depth === 0) { currentBlock = { type: tag, content: '', start: end, end: 0, attrs: attrs.reduce((cumulated, { name, value }) => { cumulated[name] = value || true; return cumulated; }, {}) }; if (typeof currentBlock.attrs.src === 'string') { currentBlock.src = currentBlock.attrs.src; } if (isSpecialTag(tag)) { checkAttrs(currentBlock, attrs); if (tag === 'script') { const block = currentBlock; if (block.attrs.setup) { block.setup = currentBlock.attrs.setup; sfc.scriptSetup = block; } else { sfc.script = block; } } else if (tag === 'style') { sfc.styles.push(currentBlock); } else { sfc[tag] = currentBlock; } } else { // custom blocks sfc.customBlocks.push(currentBlock); } } if (!unary) { depth++; } } function checkAttrs(block, attrs) { for (let i = 0; i < attrs.length; i++) { const attr = attrs[i]; if (attr.name === 'lang') { block.lang = attr.value; } if (attr.name === 'scoped') { block.scoped = true; } if (attr.name === 'module') { block.module = attr.value || true; } } } function end(tag, start) { if (depth === 1 && currentBlock) { currentBlock.end = start; let text = source.slice(currentBlock.start, currentBlock.end); if (options.deindent === true || // by default, deindent unless it's script with default lang or (j/t)sx? (options.deindent !== false && !(currentBlock.type === 'script' && (!currentBlock.lang || /^(j|t)sx?$/.test(currentBlock.lang))))) { text = deIndent(text); } // pad content so that linters and pre-processors can output correct // line numbers in errors and warnings if (currentBlock.type !== 'template' && options.pad) { text = padContent(currentBlock, options.pad) + text; } currentBlock.content = text; currentBlock = null; } depth--; } function padContent(block, pad) { if (pad === 'space') { return source.slice(0, block.start).replace(replaceRE, ' '); } else { const offset = source.slice(0, block.start).split(splitRE$1).length; const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n'; return Array(offset).join(padChar); } } parseHTML(source, { warn, start, end, outputSourceRange: options.outputSourceRange }); return sfc; } function pad (hash, len) { while (hash.length < len) { hash = '0' + hash; } return hash; } function fold (hash, text) { var i; var chr; var len; if (text.length === 0) { return hash; } for (i = 0, len = text.length; i < len; i++) { chr = text.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; } return hash < 0 ? hash * -2 : hash; } function foldObject (hash, o, seen) { return Object.keys(o).sort().reduce(foldKey, hash); function foldKey (hash, key) { return foldValue(hash, o[key], key, seen); } } function foldValue (input, value, key, seen) { var hash = fold(fold(fold(input, key), toString$1(value)), typeof value); if (value === null) { return fold(hash, 'null'); } if (value === undefined) { return fold(hash, 'undefined'); } if (typeof value === 'object' || typeof value === 'function') { if (seen.indexOf(value) !== -1) { return fold(hash, '[Circular]' + key); } seen.push(value); var objHash = foldObject(hash, value, seen); if (!('valueOf' in value) || typeof value.valueOf !== 'function') { return objHash; } try { return fold(objHash, String(value.valueOf())) } catch (err) { return fold(objHash, '[valueOf exception]' + (err.stack || err.message)) } } return fold(hash, value.toString()); } function toString$1 (o) { return Object.prototype.toString.call(o); } function sum (o) { return pad(foldValue(0, o, '', []).toString(16), 8); } var hashSum = sum; var iterator; var hasRequiredIterator; function requireIterator () { if (hasRequiredIterator) return iterator; hasRequiredIterator = 1; iterator = function (Yallist) { Yallist.prototype[Symbol.iterator] = function* () { for (let walker = this.head; walker; walker = walker.next) { yield walker.value; } }; }; return iterator; } var yallist = Yallist$1; Yallist$1.Node = Node; Yallist$1.create = Yallist$1; function Yallist$1 (list) { var self = this; if (!(self instanceof Yallist$1)) { self = new Yallist$1(); } self.tail = null; self.head = null; self.length = 0; if (list && typeof list.forEach === 'function') { list.forEach(function (item) { self.push(item); }); } else if (arguments.length > 0) { for (var i = 0, l = arguments.length; i < l; i++) { self.push(arguments[i]); } } return self } Yallist$1.prototype.removeNode = function (node) { if (node.list !== this) { throw new Error('removing node which does not belong to this list') } var next = node.next; var prev = node.prev; if (next) { next.prev = prev; } if (prev) { prev.next = next; } if (node === this.head) { this.head = next; } if (node === this.tail) { this.tail = prev; } node.list.length--; node.next = null; node.prev = null; node.list = null; return next }; Yallist$1.prototype.unshiftNode = function (node) { if (node === this.head) { return } if (node.list) { node.list.removeNode(node); } var head = this.head; node.list = this; node.next = head; if (head) { head.prev = node; } this.head = node; if (!this.tail) { this.tail = node; } this.length++; }; Yallist$1.prototype.pushNode = function (node) { if (node === this.tail) { return } if (node.list) { node.list.removeNode(node); } var tail = this.tail; node.list = this; node.prev = tail; if (tail) { tail.next = node; } this.tail = node; if (!this.head) { this.head = node; } this.length++; }; Yallist$1.prototype.push = function () { for (var i = 0, l = arguments.length; i < l; i++) { push(this, arguments[i]); } return this.length }; Yallist$1.prototype.unshift = function () { for (var i = 0, l = arguments.length; i < l; i++) { unshift(this, arguments[i]); } return this.length }; Yallist$1.prototype.pop = function () { if (!this.tail) { return undefined } var res = this.tail.value; this.tail = this.tail.prev; if (this.tail) { this.tail.next = null; } else { this.head = null; } this.length--; return res }; Yallist$1.prototype.shift = function () { if (!this.head) { return undefined } var res = this.head.value; this.head = this.head.next; if (this.head) { this.head.prev = null; } else { this.tail = null; } this.length--; return res }; Yallist$1.prototype.forEach = function (fn, thisp) { thisp = thisp || this; for (var walker = this.head, i = 0; walker !== null; i++) { fn.call(thisp, walker.value, i, this); walker = walker.next; } }; Yallist$1.prototype.forEachReverse = function (fn, thisp) { thisp = thisp || this; for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { fn.call(thisp, walker.value, i, this); walker = walker.prev; } }; Yallist$1.prototype.get = function (n) { for (var i = 0, walker = this.head; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.next; } if (i === n && walker !== null) { return walker.value } }; Yallist$1.prototype.getReverse = function (n) { for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { // abort out of the list early if we hit a cycle walker = walker.prev; } if (i === n && walker !== null) { return walker.value } }; Yallist$1.prototype.map = function (fn, thisp) { thisp = thisp || this; var res = new Yallist$1(); for (var walker = this.head; walker !== null;) { res.push(fn.call(thisp, walker.value, this)); walker = walker.next; } return res }; Yallist$1.prototype.mapReverse = function (fn, thisp) { thisp = thisp || this; var res = new Yallist$1(); for (var walker = this.tail; walker !== null;) { res.push(fn.call(thisp, walker.value, this)); walker = walker.prev; } return res }; Yallist$1.prototype.reduce = function (fn, initial) { var acc; var walker = this.head; if (arguments.length > 1) { acc = initial; } else if (this.head) { walker = this.head.next; acc = this.head.value; } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = 0; walker !== null; i++) { acc = fn(acc, walker.value, i); walker = walker.next; } return acc }; Yallist$1.prototype.reduceReverse = function (fn, initial) { var acc; var walker = this.tail; if (arguments.length > 1) { acc = initial; } else if (this.tail) { walker = this.tail.prev; acc = this.tail.value; } else { throw new TypeError('Reduce of empty list with no initial value') } for (var i = this.length - 1; walker !== null; i--) { acc = fn(acc, walker.value, i); walker = walker.prev; } return acc }; Yallist$1.prototype.toArray = function () { var arr = new Array(this.length); for (var i = 0, walker = this.head; walker !== null; i++) { arr[i] = walker.value; walker = walker.next; } return arr }; Yallist$1.prototype.toArrayReverse = function () { var arr = new Array(this.length); for (var i = 0, walker = this.tail; walker !== null; i++) { arr[i] = walker.value; walker = walker.prev; } return arr }; Yallist$1.prototype.slice = function (from, to) { to = to || this.length; if (to < 0) { to += this.length; } from = from || 0; if (from < 0) { from += this.length; } var ret = new Yallist$1(); if (to < from || to < 0) { return ret } if (from < 0) { from = 0; } if (to > this.length) { to = this.length; } for (var i = 0, walker = this.head; walker !== null && i < from; i++) { walker = walker.next; } for (; walker !== null && i < to; i++, walker = walker.next) { ret.push(walker.value); } return ret }; Yallist$1.prototype.sliceReverse = function (from, to) { to = to || this.length; if (to < 0) { to += this.length; } from = from || 0; if (from < 0) { from += this.length; } var ret = new Yallist$1(); if (to < from || to < 0) { return ret } if (from < 0) { from = 0; } if (to > this.length) { to = this.length; } for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { walker = walker.prev; } for (; walker !== null && i > from; i--, walker = walker.prev) { ret.push(walker.value); } return ret }; Yallist$1.prototype.splice = function (start, deleteCount /*, ...nodes */) { if (start > this.length) { start = this.length - 1; } if (start < 0) { start = this.length + start; } for (var i = 0, walker = this.head; walker !== null && i < start; i++) { walker = walker.next; } var ret = []; for (var i = 0; walker && i < deleteCount; i++) { ret.push(walker.value); walker = this.removeNode(walker); } if (walker === null) { walker = this.tail; } if (walker !== this.head && walker !== this.tail) { walker = walker.prev; } for (var i = 2; i < arguments.length; i++) { walker = insert(this, walker, arguments[i]); } return ret; }; Yallist$1.prototype.reverse = function () { var head = this.head; var tail = this.tail; for (var walker = head; walker !== null; walker = walker.prev) { var p = walker.prev; walker.prev = walker.next; walker.next = p; } this.head = tail; this.tail = head; return this }; function insert (self, node, value) { var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self); if (inserted.next === null) { self.tail = inserted; } if (inserted.prev === null) { self.head = inserted; } self.length++; return inserted } function push (self, item) { self.tail = new Node(item, self.tail, null, self); if (!self.head) { self.head = self.tail; } self.length++; } function unshift (self, item) { self.head = new Node(item, null, self.head, self); if (!self.tail) { self.tail = self.head; } self.length++; } function Node (value, prev, next, list) { if (!(this instanceof Node)) { return new Node(value, prev, next, list) } this.list = list; this.value = value; if (prev) { prev.next = this; this.prev = prev; } else { this.prev = null; } if (next) { next.prev = this; this.next = next; } else { this.next = null; } } try { // add if support for Symbol.iterator is present requireIterator()(Yallist$1); } catch (er) {} // A linked list to keep track of recently-used-ness const Yallist = yallist; const MAX = Symbol('max'); const LENGTH = Symbol('length'); const LENGTH_CALCULATOR = Symbol('lengthCalculator'); const ALLOW_STALE = Symbol('allowStale'); const MAX_AGE = Symbol('maxAge'); const DISPOSE = Symbol('dispose'); const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); const LRU_LIST = Symbol('lruList'); const CACHE = Symbol('cache'); const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); const naiveLength = () => 1; // lruList is a yallist where the head is the youngest // item, and the tail is the oldest. the list contains the Hit // objects as the entries. // Each Hit object has a reference to its Yallist.Node. This // never changes. // // cache is a Map (or PseudoMap) that matches the keys to // the Yallist.Node object. class LRUCache { constructor (options) { if (typeof options === 'number') options = { max: options }; if (!options) options = {}; if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number') // Kind of weird to have a default max of Infinity, but oh well. this[MAX] = options.max || Infinity; const lc = options.length || naiveLength; this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc; this[ALLOW_STALE] = options.stale || false; if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number') this[MAX_AGE] = options.maxAge || 0; this[DISPOSE] = options.dispose; this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; this.reset(); } // resize the cache when the max changes. set max (mL) { if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number') this[MAX] = mL || Infinity; trim(this); } get max () { return this[MAX] } set allowStale (allowStale) { this[ALLOW_STALE] = !!allowStale; } get allowStale () { return this[ALLOW_STALE] } set maxAge (mA) { if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number') this[MAX_AGE] = mA; trim(this); } get maxAge () { return this[MAX_AGE] } // resize the cache when the lengthCalculator changes. set lengthCalculator (lC) { if (typeof lC !== 'function') lC = naiveLength; if (lC !== this[LENGTH_CALCULATOR]) { this[LENGTH_CALCULATOR] = lC; this[LENGTH] = 0; this[LRU_LIST].forEach(hit => { hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); this[LENGTH] += hit.length; }); } trim(this); } get lengthCalculator () { return this[LENGTH_CALCULATOR] } get length () { return this[LENGTH] } get itemCount () { return this[LRU_LIST].length } rforEach (fn, thisp) { thisp = thisp || this; for (let walker = this[LRU_LIST].tail; walker !== null;) { const prev = walker.prev; forEachStep(this, fn, walker, thisp); walker = prev; } } forEach (fn, thisp) { thisp = thisp || this; for (let walker = this[LRU_LIST].head; walker !== null;) { const next = walker.next; forEachStep(this, fn, walker, thisp); walker = next; } } keys () { return this[LRU_LIST].toArray().map(k => k.key) } values () { return this[LRU_LIST].toArray().map(k => k.value) } reset () { if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); } this[CACHE] = new Map(); // hash of items by key this[LRU_LIST] = new Yallist(); // list of items in order of use recency this[LENGTH] = 0; // length of items in the list } dump () { return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { k: hit.key, v: hit.value, e: hit.now + (hit.maxAge || 0) }).toArray().filter(h => h) } dumpLru () { return this[LRU_LIST] } set (key, value, maxAge) { maxAge = maxAge || this[MAX_AGE]; if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number') const now = maxAge ? Date.now() : 0; const len = this[LENGTH_CALCULATOR](value, key); if (this[CACHE].has(key)) { if (len > this[MAX]) { del(this, this[CACHE].get(key)); return false } const node = this[CACHE].get(key); const item = node.value; // dispose of the old one before overwriting // split out into 2 ifs for better coverage tracking if (this[DISPOSE]) { if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value); } item.now = now; item.maxAge = maxAge; item.value = value; this[LENGTH] += len - item.length; item.length = len; this.get(key); trim(this); return true } const hit = new Entry(key, value, len, now, maxAge); // oversized objects fall out of cache automatically. if (hit.length > this[MAX]) { if (this[DISPOSE]) this[DISPOSE](key, value); return false } this[LENGTH] += hit.length; this[LRU_LIST].unshift(hit); this[CACHE].set(key, this[LRU_LIST].head); trim(this); return true } has (key) { if (!this[CACHE].has(key)) return false const hit = this[CACHE].get(key).value; return !isStale(this, hit) } get (key) { return get(this, key, true) } peek (key) { return get(this, key, false) } pop () { const node = this[LRU_LIST].tail; if (!node) return null del(this, node); return node.value } del (key) { del(this, this[CACHE].get(key)); } load (arr) { // reset the cache this.reset(); const now = Date.now(); // A previous serialized cache has the most recent items first for (let l = arr.length - 1; l >= 0; l--) { const hit = arr[l]; const expiresAt = hit.e || 0; if (expiresAt === 0) // the item was created without expiration in a non aged cache this.set(hit.k, hit.v); else { const maxAge = expiresAt - now; // dont add already expired items if (maxAge > 0) { this.set(hit.k, hit.v, maxAge); } } } } prune () { this[CACHE].forEach((value, key) => get(this, key, false)); } } const get = (self, key, doUse) => { const node = self[CACHE].get(key); if (node) { const hit = node.value; if (isStale(self, hit)) { del(self, node); if (!self[ALLOW_STALE]) return undefined } else { if (doUse) { if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now(); self[LRU_LIST].unshiftNode(node); } } return hit.value } }; const isStale = (self, hit) => { if (!hit || (!hit.maxAge && !self[MAX_AGE])) return false const diff = Date.now() - hit.now; return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && (diff > self[MAX_AGE]) }; const trim = self => { if (self[LENGTH] > self[MAX]) { for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { // We know that we're about to delete this one, and also // what the next least recently used key will be, so just // go ahead and set it now. const prev = walker.prev; del(self, walker); walker = prev; } } }; const del = (self, node) => { if (node) { const hit = node.value; if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value); self[LENGTH] -= hit.length; self[CACHE].delete(hit.key); self[LRU_LIST].removeNode(node); } }; class Entry { constructor (key, value, length, now, maxAge) { this.key = key; this.value = value; this.length = length; this.now = now; this.maxAge = maxAge || 0; } } const forEachStep = (self, fn, node, thisp) => { let hit = node.value; if (isStale(self, hit)) { del(self, node); if (!self[ALLOW_STALE]) hit = undefined; } if (hit) fn.call(thisp, hit.value, hit.key, self); }; var lruCache = LRUCache; var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; function encode(decoded) { var sourceFileIndex = 0; // second field var sourceCodeLine = 0; // third field var sourceCodeColumn = 0; // fourth field var nameIndex = 0; // fifth field var mappings = ''; for (var i = 0; i < decoded.length; i++) { var line = decoded[i]; if (i > 0) mappings += ';'; if (line.length === 0) continue; var generatedCodeColumn = 0; // first field var lineMappings = []; for (var _i = 0, line_1 = line; _i < line_1.length; _i++) { var segment = line_1[_i]; var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn); generatedCodeColumn = segment[0]; if (segment.length > 1) { segmentMappings += encodeInteger(segment[1] - sourceFileIndex) + encodeInteger(segment[2] - sourceCodeLine) + encodeInteger(segment[3] - sourceCodeColumn); sourceFileIndex = segment[1]; sourceCodeLine = segment[2]; sourceCodeColumn = segment[3]; } if (segment.length === 5) { segmentMappings += encodeInteger(segment[4] - nameIndex); nameIndex = segment[4]; } lineMappings.push(segmentMappings); } mappings += lineMappings.join(','); } return mappings; } function encodeInteger(num) { var result = ''; num = num < 0 ? (-num << 1) | 1 : num << 1; do { var clamped = num & 31; num >>>= 5; if (num > 0) { clamped |= 32; } result += chars[clamped]; } while (num > 0); return result; } var BitSet = function BitSet(arg) { this.bits = arg instanceof BitSet ? arg.bits.slice() : []; }; BitSet.prototype.add = function add (n) { this.bits[n >> 5] |= 1 << (n & 31); }; BitSet.prototype.has = function has (n) { return !!(this.bits[n >> 5] & (1 << (n & 31))); }; var Chunk = function Chunk(start, end, content) { this.start = start; this.end = end; this.original = content; this.intro = ''; this.outro = ''; this.content = content; this.storeName = false; this.edited = false; // we make these non-enumerable, for sanity while debugging Object.defineProperties(this, { previous: { writable: true, value: null }, next: { writable: true, value: null }, }); }; Chunk.prototype.appendLeft = function appendLeft (content) { this.outro += content; }; Chunk.prototype.appendRight = function appendRight (content) { this.intro = this.intro + content; }; Chunk.prototype.clone = function clone () { var chunk = new Chunk(this.start, this.end, this.original); chunk.intro = this.intro; chunk.outro = this.outro; chunk.content = this.content; chunk.storeName = this.storeName; chunk.edited = this.edited; return chunk; }; Chunk.prototype.contains = function contains (index) { return this.start < index && index < this.end; }; Chunk.prototype.eachNext = function eachNext (fn) { var chunk = this; while (chunk) { fn(chunk); chunk = chunk.next; } }; Chunk.prototype.eachPrevious = function eachPrevious (fn) { var chunk = this; while (chunk) { fn(chunk); chunk = chunk.previous; } }; Chunk.prototype.edit = function edit (content, storeName, contentOnly) { this.content = content; if (!contentOnly) { this.intro = ''; this.outro = ''; } this.storeName = storeName; this.edited = true; return this; }; Chunk.prototype.prependLeft = function prependLeft (content) { this.outro = content + this.outro; }; Chunk.prototype.prependRight = function prependRight (content) { this.intro = content + this.intro; }; Chunk.prototype.split = function split (index) { var sliceIndex = index - this.start; var originalBefore = this.original.slice(0, sliceIndex); var originalAfter = this.original.slice(sliceIndex); this.original = originalBefore; var newChunk = new Chunk(index, this.end, originalAfter); newChunk.outro = this.outro; this.outro = ''; this.end = index; if (this.edited) { // TODO is this block necessary?... newChunk.edit('', false); this.content = ''; } else { this.content = originalBefore; } newChunk.next = this.next; if (newChunk.next) { newChunk.next.previous = newChunk; } newChunk.previous = this; this.next = newChunk; return newChunk; }; Chunk.prototype.toString = function toString () { return this.intro + this.content + this.outro; }; Chunk.prototype.trimEnd = function trimEnd (rx) { this.outro = this.outro.replace(rx, ''); if (this.outro.length) { return true; } var trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.start + trimmed.length).edit('', undefined, true); } return true; } else { this.edit('', undefined, true); this.intro = this.intro.replace(rx, ''); if (this.intro.length) { return true; } } }; Chunk.prototype.trimStart = function trimStart (rx) { this.intro = this.intro.replace(rx, ''); if (this.intro.length) { return true; } var trimmed = this.content.replace(rx, ''); if (trimmed.length) { if (trimmed !== this.content) { this.split(this.end - trimmed.length); this.edit('', undefined, true); } return true; } else { this.edit('', undefined, true); this.outro = this.outro.replace(rx, ''); if (this.outro.length) { return true; } } }; var btoa = function () { throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); }; if (typeof window !== 'undefined' && typeof window.btoa === 'function') { btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); }; } else if (typeof Buffer === 'function') { btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); }; } var SourceMap = function SourceMap(properties) { this.version = 3; this.file = properties.file; this.sources = properties.sources; this.sourcesContent = properties.sourcesContent; this.names = properties.names; this.mappings = encode(properties.mappings); }; SourceMap.prototype.toString = function toString () { return JSON.stringify(this); }; SourceMap.prototype.toUrl = function toUrl () { return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString()); }; function guessIndent(code) { var lines = code.split('\n'); var tabbed = lines.filter(function (line) { return /^\t+/.test(line); }); var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); }); if (tabbed.length === 0 && spaced.length === 0) { return null; } // More lines tabbed than spaced? Assume tabs, and // default to tabs in the case of a tie (or nothing // to go on) if (tabbed.length >= spaced.length) { return '\t'; } // Otherwise, we need to guess the multiple var min = spaced.reduce(function (previous, current) { var numSpaces = /^ +/.exec(current)[0].length; return Math.min(numSpaces, previous); }, Infinity); return new Array(min + 1).join(' '); } function getRelativePath(from, to) { var fromParts = from.split(/[/\\]/); var toParts = to.split(/[/\\]/); fromParts.pop(); // get dirname while (fromParts[0] === toParts[0]) { fromParts.shift(); toParts.shift(); } if (fromParts.length) { var i = fromParts.length; while (i--) { fromParts[i] = '..'; } } return fromParts.concat(toParts).join('/'); } var toString = Object.prototype.toString; function isObject(thing) { return toString.call(thing) === '[object Object]'; } function getLocator(source) { var originalLines = source.split('\n'); var lineOffsets = []; for (var i = 0, pos = 0; i < originalLines.length; i++) { lineOffsets.push(pos); pos += originalLines[i].length + 1; } return function locate(index) { var i = 0; var j = lineOffsets.length; while (i < j) { var m = (i + j) >> 1; if (index < lineOffsets[m]) { j = m; } else { i = m + 1; } } var line = i - 1; var column = index - lineOffsets[line]; return { line: line, column: column }; }; } var Mappings = function Mappings(hires) { this.hires = hires; this.generatedCodeLine = 0; this.generatedCodeColumn = 0; this.raw = []; this.rawSegments = this.raw[this.generatedCodeLine] = []; this.pending = null; }; Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) { if (content.length) { var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; if (nameIndex >= 0) { segment.push(nameIndex); } this.rawSegments.push(segment); } else if (this.pending) { this.rawSegments.push(this.pending); } this.advance(content); this.pending = null; }; Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) { var originalCharIndex = chunk.start; var first = true; while (originalCharIndex < chunk.end) { if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]); } if (original[originalCharIndex] === '\n') { loc.line += 1; loc.column = 0; this.generatedCodeLine += 1; this.raw[this.generatedCodeLine] = this.rawSegments = []; this.generatedCodeColumn = 0; first = true; } else { loc.column += 1; this.generatedCodeColumn += 1; first = false; } originalCharIndex += 1; } this.pending = null; }; Mappings.prototype.advance = function advance (str) { if (!str) { return; } var lines = str.split('\n'); if (lines.length > 1) { for (var i = 0; i < lines.length - 1; i++) { this.generatedCodeLine++; this.raw[this.generatedCodeLine] = this.rawSegments = []; } this.generatedCodeColumn = 0; } this.generatedCodeColumn += lines[lines.length - 1].length; }; var n = '\n'; var warned = { insertLeft: false, insertRight: false, storeName: false, }; var MagicString = function MagicString(string, options) { if ( options === void 0 ) options = {}; var chunk = new Chunk(0, string.length, string); Object.defineProperties(this, { original: { writable: true, value: string }, outro: { writable: true, value: '' }, intro: { writable: true, value: '' }, firstChunk: { writable: true, value: chunk }, lastChunk: { writable: true, value: chunk }, lastSearchedChunk: { writable: true, value: chunk }, byStart: { writable: true, value: {} }, byEnd: { writable: true, value: {} }, filename: { writable: true, value: options.filename }, indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, sourcemapLocations: { writable: true, value: new BitSet() }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: guessIndent(string) }, }); this.byStart[0] = chunk; this.byEnd[string.length] = chunk; }; MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) { this.sourcemapLocations.add(char); }; MagicString.prototype.append = function append (content) { if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } this.outro += content; return this; }; MagicString.prototype.appendLeft = function appendLeft (index, content) { if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } this._split(index); var chunk = this.byEnd[index]; if (chunk) { chunk.appendLeft(content); } else { this.intro += content; } return this; }; MagicString.prototype.appendRight = function appendRight (index, content) { if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } this._split(index); var chunk = this.byStart[index]; if (chunk) { chunk.appendRight(content); } else { this.outro += content; } return this; }; MagicString.prototype.clone = function clone () { var cloned = new MagicString(this.original, { filename: this.filename }); var originalChunk = this.firstChunk; var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); while (originalChunk) { cloned.byStart[clonedChunk.start] = clonedChunk; cloned.byEnd[clonedChunk.end] = clonedChunk; var nextOriginalChunk = originalChunk.next; var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); if (nextClonedChunk) { clonedChunk.next = nextClonedChunk; nextClonedChunk.previous = clonedChunk; clonedChunk = nextClonedChunk; } originalChunk = nextOriginalChunk; } cloned.lastChunk = clonedChunk; if (this.indentExclusionRanges) { cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); } cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); cloned.intro = this.intro; cloned.outro = this.outro; return cloned; }; MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) { var this$1$1 = this; options = options || {}; var sourceIndex = 0; var names = Object.keys(this.storedNames); var mappings = new Mappings(options.hires); var locate = getLocator(this.original); if (this.intro) { mappings.advance(this.intro); } this.firstChunk.eachNext(function (chunk) { var loc = locate(chunk.start); if (chunk.intro.length) { mappings.advance(chunk.intro); } if (chunk.edited) { mappings.addEdit( sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1 ); } else { mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations); } if (chunk.outro.length) { mappings.advance(chunk.outro); } }); return { file: options.file ? options.file.split(/[/\\]/).pop() : null, sources: [options.source ? getRelativePath(options.file || '', options.source) : null], sourcesContent: options.includeContent ? [this.original] : [null], names: names, mappings: mappings.raw, }; }; MagicString.prototype.generateMap = function generateMap (options) { return new SourceMap(this.generateDecodedMap(options)); }; MagicString.prototype.getIndentString = function getIndentString () { return this.indentStr === null ? '\t' : this.indentStr; }; MagicString.prototype.indent = function indent (indentStr, options) { var pattern = /^[^\r\n]/gm; if (isObject(indentStr)) { options = indentStr; indentStr = undefined; } indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t'; if (indentStr === '') { return this; } // noop options = options || {}; // Process exclusion ranges var isExcluded = {}; if (options.exclude) { var exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; exclusions.forEach(function (exclusion) { for (var i = exclusion[0]; i < exclusion[1]; i += 1) { isExcluded[i] = true; } }); } var shouldIndentNextCharacter = options.indentStart !== false; var replacer = function (match) { if (shouldIndentNextCharacter) { return ("" + indentStr + match); } shouldIndentNextCharacter = true; return match; }; this.intro = this.intro.replace(pattern, replacer); var charIndex = 0; var chunk = this.firstChunk; while (chunk) { var end = chunk.end; if (chunk.edited) { if (!isExcluded[charIndex]) { chunk.content = chunk.content.replace(pattern, replacer); if (chunk.content.length) { shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; } } } else { charIndex = chunk.start; while (charIndex < end) { if (!isExcluded[charIndex]) { var char = this.original[charIndex]; if (char === '\n') { shouldIndentNextCharacter = true; } else if (char !== '\r' && shouldIndentNextCharacter) { shouldIndentNextCharacter = false; if (charIndex === chunk.start) { chunk.prependRight(indentStr); } else { this._splitChunk(chunk, charIndex); chunk = chunk.next; chunk.prependRight(indentStr); } } } charIndex += 1; } } charIndex = chunk.end; chunk = chunk.next; } this.outro = this.outro.replace(pattern, replacer); return this; }; MagicString.prototype.insert = function insert () { throw new Error( 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' ); }; MagicString.prototype.insertLeft = function insertLeft (index, content) { if (!warned.insertLeft) { console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' ); // eslint-disable-line no-console warned.insertLeft = true; } return this.appendLeft(index, content); }; MagicString.prototype.insertRight = function insertRight (index, content) { if (!warned.insertRight) { console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' ); // eslint-disable-line no-console warned.insertRight = true; } return this.prependRight(index, content); }; MagicString.prototype.move = function move (start, end, index) { if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); } this._split(start); this._split(end); this._split(index); var first = this.byStart[start]; var last = this.byEnd[end]; var oldLeft = first.previous; var oldRight = last.next; var newRight = this.byStart[index]; if (!newRight && last === this.lastChunk) { return this; } var newLeft = newRight ? newRight.previous : this.lastChunk; if (oldLeft) { oldLeft.next = oldRight; } if (oldRight) { oldRight.previous = oldLeft; } if (newLeft) { newLeft.next = first; } if (newRight) { newRight.previous = last; } if (!first.previous) { this.firstChunk = last.next; } if (!last.next) { this.lastChunk = first.previous; this.lastChunk.next = null; } first.previous = newLeft; last.next = newRight || null; if (!newLeft) { this.firstChunk = first; } if (!newRight) { this.lastChunk = last; } return this; }; MagicString.prototype.overwrite = function overwrite (start, end, content, options) { if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); } while (start < 0) { start += this.original.length; } while (end < 0) { end += this.original.length; } if (end > this.original.length) { throw new Error('end is out of bounds'); } if (start === end) { throw new Error( 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' ); } this._split(start); this._split(end); if (options === true) { if (!warned.storeName) { console.warn( 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string' ); // eslint-disable-line no-console warned.storeName = true; } options = { storeName: true }; } var storeName = options !== undefined ? options.storeName : false; var contentOnly = options !== undefined ? options.contentOnly : false; if (storeName) { var original = this.original.slice(start, end); Object.defineProperty(this.storedNames, original, { writable: true, value: true, enumerable: true }); } var first = this.byStart[start]; var last = this.byEnd[end]; if (first) { var chunk = first; while (chunk !== last) { if (chunk.next !== this.byStart[chunk.end]) { throw new Error('Cannot overwrite across a split point'); } chunk = chunk.next; chunk.edit('', false); } first.edit(content, storeName, contentOnly); } else { // must be inserting at the end var newChunk = new Chunk(start, end, '').edit(content, storeName); // TODO last chunk in the array may not be the last chunk, if it's moved... last.next = newChunk; newChunk.previous = last; } return this; }; MagicString.prototype.prepend = function prepend (content) { if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); } this.intro = content + this.intro; return this; }; MagicString.prototype.prependLeft = function prependLeft (index, content) { if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } this._split(index); var chunk = this.byEnd[index]; if (chunk) { chunk.prependLeft(content); } else { this.intro = content + this.intro; } return this; }; MagicString.prototype.prependRight = function prependRight (index, content) { if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); } this._split(index); var chunk = this.byStart[index]; if (chunk) { chunk.prependRight(content); } else { this.outro = content + this.outro; } return this; }; MagicString.prototype.remove = function remove (start, end) { while (start < 0) { start += this.original.length; } while (end < 0) { end += this.original.length; } if (start === end) { return this; } if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); } if (start > end) { throw new Error('end must be greater than start'); } this._split(start); this._split(end); var chunk = this.byStart[start]; while (chunk) { chunk.intro = ''; chunk.outro = ''; chunk.edit(''); chunk = end > chunk.end ? this.byStart[chunk.end] : null; } return this; }; MagicString.prototype.lastChar = function lastChar () { if (this.outro.length) { return this.outro[this.outro.length - 1]; } var chunk = this.lastChunk; do { if (chunk.outro.length) { return chunk.outro[chunk.outro.length - 1]; } if (chunk.content.length) { return chunk.content[chunk.content.length - 1]; } if (chunk.intro.length) { return chunk.intro[chunk.intro.length - 1]; } } while ((chunk = chunk.previous)); if (this.intro.length) { return this.intro[this.intro.length - 1]; } return ''; }; MagicString.prototype.lastLine = function lastLine () { var lineIndex = this.outro.lastIndexOf(n); if (lineIndex !== -1) { return this.outro.substr(lineIndex + 1); } var lineStr = this.outro; var chunk = this.lastChunk; do { if (chunk.outro.length > 0) { lineIndex = chunk.outro.lastIndexOf(n); if (lineIndex !== -1) { return chunk.outro.substr(lineIndex + 1) + lineStr; } lineStr = chunk.outro + lineStr; } if (chunk.content.length > 0) { lineIndex = chunk.content.lastIndexOf(n); if (lineIndex !== -1) { return chunk.content.substr(lineIndex + 1) + lineStr; } lineStr = chunk.content + lineStr; } if (chunk.intro.length > 0) { lineIndex = chunk.intro.lastIndexOf(n); if (lineIndex !== -1) { return chunk.intro.substr(lineIndex + 1) + lineStr; } lineStr = chunk.intro + lineStr; } } while ((chunk = chunk.previous)); lineIndex = this.intro.lastIndexOf(n); if (lineIndex !== -1) { return this.intro.substr(lineIndex + 1) + lineStr; } return this.intro + lineStr; }; MagicString.prototype.slice = function slice (start, end) { if ( start === void 0 ) start = 0; if ( end === void 0 ) end = this.original.length; while (start < 0) { start += this.original.length; } while (end < 0) { end += this.original.length; } var result = ''; // find start chunk var chunk = this.firstChunk; while (chunk && (chunk.start > start || chunk.end <= start)) { // found end chunk before start if (chunk.start < end && chunk.end >= end) { return result; } chunk = chunk.next; } if (chunk && chunk.edited && chunk.start !== start) { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); } var startChunk = chunk; while (chunk) { if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { result += chunk.intro; } var containsEnd = chunk.start < end && chunk.end >= end; if (containsEnd && chunk.edited && chunk.end !== end) { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); } var sliceStart = startChunk === chunk ? start - chunk.start : 0; var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; result += chunk.content.slice(sliceStart, sliceEnd); if (chunk.outro && (!containsEnd || chunk.end === end)) { result += chunk.outro; } if (containsEnd) { break; } chunk = chunk.next; } return result; }; // TODO deprecate this? not really very useful MagicString.prototype.snip = function snip (start, end) { var clone = this.clone(); clone.remove(0, start); clone.remove(end, clone.original.length); return clone; }; MagicString.prototype._split = function _split (index) { if (this.byStart[index] || this.byEnd[index]) { return; } var chunk = this.lastSearchedChunk; var searchForward = index > chunk.end; while (chunk) { if (chunk.contains(index)) { return this._splitChunk(chunk, index); } chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; } }; MagicString.prototype._splitChunk = function _splitChunk (chunk, index) { if (chunk.edited && chunk.content.length) { // zero-length edited chunks are a special case (overlapping replacements) var loc = getLocator(this.original)(index); throw new Error( ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") ); } var newChunk = chunk.split(index); this.byEnd[index] = chunk; this.byStart[index] = newChunk; this.byEnd[newChunk.end] = newChunk; if (chunk === this.lastChunk) { this.lastChunk = newChunk; } this.lastSearchedChunk = chunk; return true; }; MagicString.prototype.toString = function toString () { var str = this.intro; var chunk = this.firstChunk; while (chunk) { str += chunk.toString(); chunk = chunk.next; } return str + this.outro; }; MagicString.prototype.isEmpty = function isEmpty () { var chunk = this.firstChunk; do { if ( (chunk.intro.length && chunk.intro.trim()) || (chunk.content.length && chunk.content.trim()) || (chunk.outro.length && chunk.outro.trim()) ) { return false; } } while ((chunk = chunk.next)); return true; }; MagicString.prototype.length = function length () { var chunk = this.firstChunk; var length = 0; do { length += chunk.intro.length + chunk.content.length + chunk.outro.length; } while ((chunk = chunk.next)); return length; }; MagicString.prototype.trimLines = function trimLines () { return this.trim('[\\r\\n]'); }; MagicString.prototype.trim = function trim (charType) { return this.trimStart(charType).trimEnd(charType); }; MagicString.prototype.trimEndAborted = function trimEndAborted (charType) { var rx = new RegExp((charType || '\\s') + '+$'); this.outro = this.outro.replace(rx, ''); if (this.outro.length) { return true; } var chunk = this.lastChunk; do { var end = chunk.end; var aborted = chunk.trimEnd(rx); // if chunk was trimmed, we have a new lastChunk if (chunk.end !== end) { if (this.lastChunk === chunk) { this.lastChunk = chunk.next; } this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) { return true; } chunk = chunk.previous; } while (chunk); return false; }; MagicString.prototype.trimEnd = function trimEnd (charType) { this.trimEndAborted(charType); return this; }; MagicString.prototype.trimStartAborted = function trimStartAborted (charType) { var rx = new RegExp('^' + (charType || '\\s') + '+'); this.intro = this.intro.replace(rx, ''); if (this.intro.length) { return true; } var chunk = this.firstChunk; do { var end = chunk.end; var aborted = chunk.trimStart(rx); if (chunk.end !== end) { // special case... if (chunk === this.lastChunk) { this.lastChunk = chunk.next; } this.byEnd[chunk.end] = chunk; this.byStart[chunk.next.start] = chunk.next; this.byEnd[chunk.next.end] = chunk.next; } if (aborted) { return true; } chunk = chunk.next; } while (chunk); return false; }; MagicString.prototype.trimStart = function trimStart (charType) { this.trimStartAborted(charType); return this; }; // @ts-check /** @typedef { import('estree').BaseNode} BaseNode */ /** @typedef {{ skip: () => void; remove: () => void; replace: (node: BaseNode) => void; }} WalkerContext */ class WalkerBase { constructor() { /** @type {boolean} */ this.should_skip = false; /** @type {boolean} */ this.should_remove = false; /** @type {BaseNode | null} */ this.replacement = null; /** @type {WalkerContext} */ this.context = { skip: () => (this.should_skip = true), remove: () => (this.should_remove = true), replace: (node) => (this.replacement = node) }; } /** * * @param {any} parent * @param {string} prop * @param {number} index * @param {BaseNode} node */ replace(parent, prop, index, node) { if (parent) { if (index !== null) { parent[prop][index] = node; } else { parent[prop] = node; } } } /** * * @param {any} parent * @param {string} prop * @param {number} index */ remove(parent, prop, index) { if (parent) { if (index !== null) { parent[prop].splice(index, 1); } else { delete parent[prop]; } } } } // @ts-check /** @typedef { import('estree').BaseNode} BaseNode */ /** @typedef { import('./walker.js').WalkerContext} WalkerContext */ /** @typedef {( * this: WalkerContext, * node: BaseNode, * parent: BaseNode, * key: string, * index: number * ) => void} SyncHandler */ class SyncWalker extends WalkerBase { /** * * @param {SyncHandler} enter * @param {SyncHandler} leave */ constructor(enter, leave) { super(); /** @type {SyncHandler} */ this.enter = enter; /** @type {SyncHandler} */ this.leave = leave; } /** * * @param {BaseNode} node * @param {BaseNode} parent * @param {string} [prop] * @param {number} [index] * @returns {BaseNode} */ visit(node, parent, prop, index) { if (node) { if (this.enter) { const _should_skip = this.should_skip; const _should_remove = this.should_remove; const _replacement = this.replacement; this.should_skip = false; this.should_remove = false; this.replacement = null; this.enter.call(this.context, node, parent, prop, index); if (this.replacement) { node = this.replacement; this.replace(parent, prop, index, node); } if (this.should_remove) { this.remove(parent, prop, index); } const skipped = this.should_skip; const removed = this.should_remove; this.should_skip = _should_skip; this.should_remove = _should_remove; this.replacement = _replacement; if (skipped) return node; if (removed) return null; } for (const key in node) { const value = node[key]; if (typeof value !== "object") { continue; } else if (Array.isArray(value)) { for (let i = 0; i < value.length; i += 1) { if (value[i] !== null && typeof value[i].type === 'string') { if (!this.visit(value[i], node, key, i)) { // removed i--; } } } } else if (value !== null && typeof value.type === "string") { this.visit(value, node, key, null); } } if (this.leave) { const _replacement = this.replacement; const _should_remove = this.should_remove; this.replacement = null; this.should_remove = false; this.leave.call(this.context, node, parent, prop, index); if (this.replacement) { node = this.replacement; this.replace(parent, prop, index, node); } if (this.should_remove) { this.remove(parent, prop, index); } const removed = this.should_remove; this.replacement = _replacement; this.should_remove = _should_remove; if (removed) return null; } } return node; } } // @ts-check /** @typedef { import('estree').BaseNode} BaseNode */ /** @typedef { import('./sync.js').SyncHandler} SyncHandler */ /** @typedef { import('./async.js').AsyncHandler} AsyncHandler */ /** * * @param {BaseNode} ast * @param {{ * enter?: SyncHandler * leave?: SyncHandler * }} walker * @returns {BaseNode} */ function walk$1(ast, { enter, leave }) { const instance = new SyncWalker(enter, leave); return instance.visit(ast, null); } // https://github.com/vuejs/core/blob/main/packages/compiler-core/src/babelUtils.ts function walkIdentifiers(root, onIdentifier, onNode) { const parentStack = []; const knownIds = Object.create(null); const rootExp = root.type === 'Program' && root.body[0].type === 'ExpressionStatement' && root.body[0].expression; walk$1(root, { enter(node, parent) { parent && parentStack.push(parent); if (parent && parent.type.startsWith('TS') && parent.type !== 'TSAsExpression' && parent.type !== 'TSNonNullExpression' && parent.type !== 'TSTypeAssertion') { return this.skip(); } if (onNode) onNode(node); if (node.type === 'Identifier') { const isLocal = !!knownIds[node.name]; const isRefed = isReferencedIdentifier(node, parent, parentStack); if ((isRefed && !isLocal)) { onIdentifier(node, parent, parentStack, isRefed, isLocal); } } else if (node.type === 'ObjectProperty' && parent.type === 'ObjectPattern') { node.inPattern = true; } else if (isFunctionType(node)) { // walk function expressions and add its arguments to known identifiers // so that we don't prefix them walkFunctionParams(node, id => markScopeIdentifier(node, id, knownIds)); } else if (node.type === 'BlockStatement') { // #3445 record block-level local variables walkBlockDeclarations(node, id => markScopeIdentifier(node, id, knownIds)); } }, leave(node, parent) { parent && parentStack.pop(); if (node !== rootExp && node.scopeIds) { for (const id of node.scopeIds) { knownIds[id]--; if (knownIds[id] === 0) { delete knownIds[id]; } } } } }); } function isReferencedIdentifier(id, parent, parentStack) { if (!parent) { return true; } // is a special keyword but parsed as identifier if (id.name === 'arguments') { return false; } if (isReferenced(id, parent)) { return true; } // babel's isReferenced check returns false for ids being assigned to, so we // need to cover those cases here switch (parent.type) { case 'AssignmentExpression': case 'AssignmentPattern': return true; case 'ObjectPattern': case 'ArrayPattern': return isInDestructureAssignment(parent, parentStack); } return false; } function isInDestructureAssignment(parent, parentStack) { if (parent && (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) { let i = parentStack.length; while (i--) { const p = parentStack[i]; if (p.type === 'AssignmentExpression') { return true; } else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) { break; } } } return false; } function walkFunctionParams(node, onIdent) { for (const p of node.params) { for (const id of extractIdentifiers(p)) { onIdent(id); } } } function walkBlockDeclarations(block, onIdent) { for (const stmt of block.body) { if (stmt.type === 'VariableDeclaration') { if (stmt.declare) continue; for (const decl of stmt.declarations) { for (const id of extractIdentifiers(decl.id)) { onIdent(id); } } } else if (stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration') { if (stmt.declare || !stmt.id) continue; onIdent(stmt.id); } } } function extractIdentifiers(param, nodes = []) { switch (param.type) { case 'Identifier': nodes.push(param); break; case 'MemberExpression': let object = param; while (object.type === 'MemberExpression') { object = object.object; } nodes.push(object); break; case 'ObjectPattern': for (const prop of param.properties) { if (prop.type === 'RestElement') { extractIdentifiers(prop.argument, nodes); } else { extractIdentifiers(prop.value, nodes); } } break; case 'ArrayPattern': param.elements.forEach(element => { if (element) extractIdentifiers(element, nodes); }); break; case 'RestElement': extractIdentifiers(param.argument, nodes); break; case 'AssignmentPattern': extractIdentifiers(param.left, nodes); break; } return nodes; } function markScopeIdentifier(node, child, knownIds) { const { name } = child; if (node.scopeIds && node.scopeIds.has(name)) { return; } if (name in knownIds) { knownIds[name]++; } else { knownIds[name] = 1; } (node.scopeIds || (node.scopeIds = new Set())).add(name); } const isFunctionType = (node) => { return /Function(?:Expression|Declaration)$|Method$/.test(node.type); }; const isStaticProperty = (node) => node && (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') && !node.computed; /** * Copied from https://github.com/babel/babel/blob/main/packages/babel-types/src/validators/isReferenced.ts * To avoid runtime dependency on @babel/types (which includes process references) * This file should not change very often in babel but we may need to keep it * up-to-date from time to time. * * https://github.com/babel/babel/blob/main/LICENSE * */ function isReferenced(node, parent, grandparent) { switch (parent.type) { // yes: PARENT[NODE] // yes: NODE.child // no: parent.NODE case 'MemberExpression': case 'OptionalMemberExpression': if (parent.property === node) { return !!parent.computed; } return parent.object === node; case 'JSXMemberExpression': return parent.object === node; // no: let NODE = init; // yes: let id = NODE; case 'VariableDeclarator': return parent.init === node; // yes: () => NODE // no: (NODE) => {} case 'ArrowFunctionExpression': return parent.body === node; // no: class { #NODE; } // no: class { get #NODE() {} } // no: class { #NODE() {} } // no: class { fn() { return this.#NODE; } } case 'PrivateName': return false; // no: class { NODE() {} } // yes: class { [NODE]() {} } // no: class { foo(NODE) {} } case 'ClassMethod': case 'ClassPrivateMethod': case 'ObjectMethod': if (parent.key === node) { return !!parent.computed; } return false; // yes: { [NODE]: "" } // no: { NODE: "" } // depends: { NODE } // depends: { key: NODE } case 'ObjectProperty': if (parent.key === node) { return !!parent.computed; } // parent.value === node return !grandparent || grandparent.type !== 'ObjectPattern'; // no: class { NODE = value; } // yes: class { [NODE] = value; } // yes: class { key = NODE; } case 'ClassProperty': if (parent.key === node) { return !!parent.computed; } return true; case 'ClassPrivateProperty': return parent.key !== node; // no: class NODE {} // yes: class Foo extends NODE {} case 'ClassDeclaration': case 'ClassExpression': return parent.superClass === node; // yes: left = NODE; // no: NODE = right; case 'AssignmentExpression': return parent.right === node; // no: [NODE = foo] = []; // yes: [foo = NODE] = []; case 'AssignmentPattern': return parent.right === node; // no: NODE: for (;;) {} case 'LabeledStatement': return false; // no: try {} catch (NODE) {} case 'CatchClause': return false; // no: function foo(...NODE) {} case 'RestElement': return false; case 'BreakStatement': case 'ContinueStatement': return false; // no: function NODE() {} // no: function foo(NODE) {} case 'FunctionDeclaration': case 'FunctionExpression': return false; // no: export NODE from "foo"; // no: export * as NODE from "foo"; case 'ExportNamespaceSpecifier': case 'ExportDefaultSpecifier': return false; // no: export { foo as NODE }; // yes: export { NODE as foo }; // no: export { NODE as foo } from "foo"; case 'ExportSpecifier': // @ts-expect-error if (grandparent === null || grandparent === void 0 ? void 0 : grandparent.source) { return false; } return parent.local === node; // no: import NODE from "foo"; // no: import * as NODE from "foo"; // no: import { NODE as foo } from "foo"; // no: import { foo as NODE } from "foo"; // no: import NODE from "bar"; case 'ImportDefaultSpecifier': case 'ImportNamespaceSpecifier': case 'ImportSpecifier': return false; // no: import "foo" assert { NODE: "json" } case 'ImportAttribute': return false; // no:
case 'JSXAttribute': return false; // no: [NODE] = []; // no: ({ NODE }) = []; case 'ObjectPattern': case 'ArrayPattern': return false; // no: new.NODE // no: NODE.target case 'MetaProperty': return false; // yes: type X = { someProperty: NODE } // no: type X = { NODE: OtherType } case 'ObjectTypeProperty': return parent.key !== node; // yes: enum X { Foo = NODE } // no: enum X { NODE } case 'TSEnumMember': return parent.id !== node; // yes: { [NODE]: value } // no: { NODE: value } case 'TSPropertySignature': if (parent.key === node) { return !!parent.computed; } return true; } return true; } const range = 2; function generateCodeFrame(source, start = 0, end = source.length) { const lines = source.split(/\r?\n/); let count = 0; const res = []; for (let i = 0; i < lines.length; i++) { count += lines[i].length + 1; if (count >= start) { for (let j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) continue; res.push(`${j + 1}${repeat(` `, 3 - String(j + 1).length)}| ${lines[j]}`); const lineLength = lines[j].length; if (j === i) { // push underline const pad = start - (count - lineLength) + 1; const length = end > count ? lineLength - pad : end - start; res.push(` | ` + repeat(` `, pad) + repeat(`^`, length)); } else if (j > i) { if (end > count) { const length = Math.min(end - count, lineLength); res.push(` | ` + repeat(`^`, length)); } count += lineLength + 1; } } break; } } return res.join('\n'); } function repeat(str, n) { let result = ''; if (n > 0) { // eslint-disable-next-line no-constant-condition while (true) { // eslint-disable-line if (n & 1) result += str; n >>>= 1; if (n <= 0) break; str += str; } } return result; } // can we use __proto__? const hasProto = '__proto__' in {}; // Browser environment sniffing const inBrowser = typeof window !== 'undefined'; const UA = inBrowser && window.navigator.userAgent.toLowerCase(); const isIE = UA && /msie|trident/.test(UA); UA && UA.indexOf('msie 9.0') > 0; const isEdge = UA && UA.indexOf('edge/') > 0; UA && UA.indexOf('android') > 0; UA && /iphone|ipad|ipod|ios/.test(UA); UA && /chrome\/\d+/.test(UA) && !isEdge; UA && /phantomjs/.test(UA); UA && UA.match(/firefox\/(\d+)/); // Firefox has a "watch" function on Object.prototype... // @ts-expect-error firebox support const nativeWatch = {}.watch; let supportsPassive = false; if (inBrowser) { try { const opts = {}; Object.defineProperty(opts, 'passive', { get() { /* istanbul ignore next */ supportsPassive = true; } }); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) { } } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV let _isServer; const isServerRendering = () => { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'] && global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer; }; /* istanbul ignore next */ function isNative(Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()); } const hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); let _Set; // $flow-disable-line /* istanbul ignore if */ if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = class Set { constructor() { this.set = Object.create(null); } has(key) { return this.set[key] === true; } add(key) { this.set[key] = true; } clear() { this.set = Object.create(null); } }; } const ASSET_TYPES = ['component', 'directive', 'filter']; const LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated', 'errorCaptured', 'serverPrefetch', 'renderTracked', 'renderTriggered' ]; var config = { /** * Option merge strategies (used in core/util/options) */ // $flow-disable-line optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: process.env.NODE_ENV !== 'production', /** * Whether to enable devtools */ devtools: process.env.NODE_ENV !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Warn handler for watcher warns */ warnHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ // $flow-disable-line keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Perform updates asynchronously. Intended to be used by Vue Test Utils * This will significantly reduce performance if set to false. */ async: true, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS }; let currentInstance = null; /** * @internal */ function setCurrentInstance(vm = null) { if (!vm) currentInstance && currentInstance._scope.off(); currentInstance = vm; vm && vm._scope.on(); } /** * @internal */ class VNode { constructor(tag, data, children, text, elm, context, componentOptions, asyncFactory) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.fnContext = undefined; this.fnOptions = undefined; this.fnScopeId = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; this.asyncFactory = asyncFactory; this.asyncMeta = undefined; this.isAsyncPlaceholder = false; } // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ get child() { return this.componentInstance; } } const createEmptyVNode = (text = '') => { const node = new VNode(); node.text = text; node.isComment = true; return node; }; function createTextVNode(val) { return new VNode(undefined, undefined, undefined, String(val)); } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode(vnode) { const cloned = new VNode(vnode.tag, vnode.data, // #7975 // clone children array to avoid mutating original in case of cloning // a child. vnode.children && vnode.children.slice(), vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.fnContext = vnode.fnContext; cloned.fnOptions = vnode.fnOptions; cloned.fnScopeId = vnode.fnScopeId; cloned.asyncMeta = vnode.asyncMeta; cloned.isCloned = true; return cloned; } /* not type checking this file because flow doesn't play well with Proxy */ if (process.env.NODE_ENV !== 'production') { makeMap('Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,' + 'require' // for Webpack/Browserify ); const hasProxy = typeof Proxy !== 'undefined' && isNative(Proxy); if (hasProxy) { const isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); config.keyCodes = new Proxy(config.keyCodes, { set(target, key, value) { if (isBuiltInModifier(key)) { warn$3(`Avoid overwriting built-in modifier in config.keyCodes: .${key}`); return false; } else { target[key] = value; return true; } } }); } } let uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. * @internal */ class Dep { constructor() { // pending subs cleanup this._pending = false; this.id = uid++; this.subs = []; } addSub(sub) { this.subs.push(sub); } removeSub(sub) { // #12696 deps with massive amount of subscribers are extremely slow to // clean up in Chromium // to workaround this, we unset the sub for now, and clear them on // next scheduler flush. this.subs[this.subs.indexOf(sub)] = null; if (!this._pending) { this._pending = true; } } depend(info) { if (Dep.target) { Dep.target.addDep(this); if (process.env.NODE_ENV !== 'production' && info && Dep.target.onTrack) { Dep.target.onTrack(Object.assign({ effect: Dep.target }, info)); } } } notify(info) { // stabilize the subscriber list first const subs = this.subs.filter(s => s); if (process.env.NODE_ENV !== 'production' && !config.async) { // subs aren't sorted in scheduler if not running async // we need to sort them now to make sure they fire in correct // order subs.sort((a, b) => a.id - b.id); } for (let i = 0, l = subs.length; i < l; i++) { const sub = subs[i]; if (process.env.NODE_ENV !== 'production' && info) { sub.onTrigger && sub.onTrigger(Object.assign({ effect: subs[i] }, info)); } sub.update(); } } } // The current target watcher being evaluated. // This is globally unique because only one watcher // can be evaluated at a time. Dep.target = null; const targetStack = []; function pushTarget(target) { targetStack.push(target); Dep.target = target; } function popTarget() { targetStack.pop(); Dep.target = targetStack[targetStack.length - 1]; } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ const arrayProto = Array.prototype; const arrayMethods = Object.create(arrayProto); const methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ]; /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { // cache original method const original = arrayProto[method]; def(arrayMethods, method, function mutator(...args) { const result = original.apply(this, args); const ob = this.__ob__; let inserted; switch (method) { case 'push': case 'unshift': inserted = args; break; case 'splice': inserted = args.slice(2); break; } if (inserted) ob.observeArray(inserted); // notify change if (process.env.NODE_ENV !== 'production') { ob.dep.notify({ type: "array mutation" /* TriggerOpTypes.ARRAY_MUTATION */, target: this, key: method }); } else { ob.dep.notify(); } return result; }); }); const arrayKeys = Object.getOwnPropertyNames(arrayMethods); const NO_INITIAL_VALUE = {}; /** * In some cases we may want to disable observation inside a component's * update computation. */ let shouldObserve = true; function toggleObserving(value) { shouldObserve = value; } // ssr mock dep const mockDep = { notify: noop, depend: noop, addSub: noop, removeSub: noop }; /** * Observer class that is attached to each observed * object. Once attached, the observer converts the target * object's property keys into getter/setters that * collect dependencies and dispatch updates. */ class Observer { constructor(value, shallow = false, mock = false) { this.value = value; this.shallow = shallow; this.mock = mock; // this.value = value this.dep = mock ? mockDep : new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (isArray(value)) { if (!mock) { if (hasProto) { value.__proto__ = arrayMethods; /* eslint-enable no-proto */ } else { for (let i = 0, l = arrayKeys.length; i < l; i++) { const key = arrayKeys[i]; def(value, key, arrayMethods[key]); } } } if (!shallow) { this.observeArray(value); } } else { /** * Walk through all properties and convert them into * getter/setters. This method should only be called when * value type is Object. */ const keys = Object.keys(value); for (let i = 0; i < keys.length; i++) { const key = keys[i]; defineReactive(value, key, NO_INITIAL_VALUE, undefined, shallow, mock); } } } /** * Observe a list of Array items. */ observeArray(value) { for (let i = 0, l = value.length; i < l; i++) { observe(value[i], false, this.mock); } } } // helpers /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe(value, shallow, ssrMockReactivity) { if (value && hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { return value.__ob__; } if (shouldObserve && (ssrMockReactivity || !isServerRendering()) && (isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value.__v_skip /* ReactiveFlags.SKIP */ && !isRef(value) && !(value instanceof VNode)) { return new Observer(value, shallow, ssrMockReactivity); } } /** * Define a reactive property on an Object. */ function defineReactive(obj, key, val, customSetter, shallow, mock, observeEvenIfShallow = false) { const dep = new Dep(); const property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return; } // cater for pre-defined getter/setters const getter = property && property.get; const setter = property && property.set; if ((!getter || setter) && (val === NO_INITIAL_VALUE || arguments.length === 2)) { val = obj[key]; } let childOb = shallow ? val && val.__ob__ : observe(val, false, mock); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter() { const value = getter ? getter.call(obj) : val; if (Dep.target) { if (process.env.NODE_ENV !== 'production') { dep.depend({ target: obj, type: "get" /* TrackOpTypes.GET */, key }); } else { dep.depend(); } if (childOb) { childOb.dep.depend(); if (isArray(value)) { dependArray(value); } } } return isRef(value) && !shallow ? value.value : value; }, set: function reactiveSetter(newVal) { const value = getter ? getter.call(obj) : val; if (!hasChanged(value, newVal)) { return; } if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else if (getter) { // #7981: for accessor properties without setter return; } else if (!shallow && isRef(value) && !isRef(newVal)) { value.value = newVal; return; } else { val = newVal; } childOb = shallow ? newVal && newVal.__ob__ : observe(newVal, false, mock); if (process.env.NODE_ENV !== 'production') { dep.notify({ type: "set" /* TriggerOpTypes.SET */, target: obj, key, newValue: newVal, oldValue: value }); } else { dep.notify(); } } }); return dep; } function set(target, key, val) { if (process.env.NODE_ENV !== 'production' && (isUndef(target) || isPrimitive(target))) { warn$3(`Cannot set reactive property on undefined, null, or primitive value: ${target}`); } if (isReadonly(target)) { process.env.NODE_ENV !== 'production' && warn$3(`Set operation on key "${key}" failed: target is readonly.`); return; } const ob = target.__ob__; if (isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); // when mocking for SSR, array methods are not hijacked if (ob && !ob.shallow && ob.mock) { observe(val, false, true); } return val; } if (key in target && !(key in Object.prototype)) { target[key] = val; return val; } if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn$3('Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.'); return val; } if (!ob) { target[key] = val; return val; } defineReactive(ob.value, key, val, undefined, ob.shallow, ob.mock); if (process.env.NODE_ENV !== 'production') { ob.dep.notify({ type: "add" /* TriggerOpTypes.ADD */, target: target, key, newValue: val, oldValue: undefined }); } else { ob.dep.notify(); } return val; } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray(value) { for (let e, i = 0, l = value.length; i < l; i++) { e = value[i]; if (e && e.__ob__) { e.__ob__.dep.depend(); } if (isArray(e)) { dependArray(e); } } } function isReadonly(value) { return !!(value && value.__v_isReadonly); } function isRef(r) { return !!(r && r.__v_isRef === true); } if (process.env.NODE_ENV !== 'production') ; const normalizeEvent = cached((name) => { const passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; const once = name.charAt(0) === '~'; // Prefixed last, checked first name = once ? name.slice(1) : name; const capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name, once, capture, passive }; }); function createFnInvoker(fns, vm) { function invoker() { const fns = invoker.fns; if (isArray(fns)) { const cloned = fns.slice(); for (let i = 0; i < cloned.length; i++) { invokeWithErrorHandling(cloned[i], null, arguments, vm, `v-on handler`); } } else { // return handler return value for single handlers return invokeWithErrorHandling(fns, null, arguments, vm, `v-on handler`); } } invoker.fns = fns; return invoker; } function updateListeners(on, oldOn, add, remove, createOnceHandler, vm) { let name, cur, old, event; for (name in on) { cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (isUndef(cur)) { process.env.NODE_ENV !== 'production' && warn$3(`Invalid handler for event "${event.name}": got ` + String(cur), vm); } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur, vm); } if (isTrue(event.once)) { cur = on[name] = createOnceHandler(event.name, cur, event.capture); } add(event.name, cur, event.capture, event.passive, event.params); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove(event.name, oldOn[name], event.capture); } } } function extractPropsFromVNodeData(data, Ctor, tag) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. const propOptions = Ctor.options.props; if (isUndef(propOptions)) { return; } const res = {}; const { attrs, props } = data; if (isDef(attrs) || isDef(props)) { for (const key in propOptions) { const altKey = hyphenate(key); if (process.env.NODE_ENV !== 'production') { const keyInLowerCase = key.toLowerCase(); if (key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase)) { tip(`Prop "${keyInLowerCase}" is passed to component ` + `${formatComponentName( // @ts-expect-error tag is string tag || Ctor)}, but the declared prop name is` + ` "${key}". ` + `Note that HTML attributes are case-insensitive and camelCased ` + `props need to use their kebab-case equivalents when using in-DOM ` + `templates. You should probably use "${altKey}" instead of "${key}".`); } } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res; } function checkProp(res, hash, key, altKey, preserve) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true; } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true; } } return false; } // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren(children) { for (let i = 0; i < children.length; i++) { if (isArray(children[i])) { return Array.prototype.concat.apply([], children); } } return children; } // 2. When the children contains constructs that always generated nested Arrays, // e.g.