botframework-webchat 4.18.1-main.20250127.e44c342 → 4.18.1-main.20250129.b40802d
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/botframework-webchat.es5.js +1 -1
- package/dist/botframework-webchat.es5.mjs +1 -1
- package/dist/botframework-webchat.js +1 -1
- package/dist/botframework-webchat.minimal.js +1 -1
- package/dist/botframework-webchat.minimal.mjs +1 -1
- package/dist/botframework-webchat.mjs +1 -1
- package/dist/{chunk-ASV62R53.mjs → chunk-2KQWLCLT.mjs} +3 -3
- package/dist/{chunk-E2QTQNYP.js → chunk-5MUSNARN.js} +3 -3
- package/dist/{chunk-E2QTQNYP.js.map → chunk-5MUSNARN.js.map} +1 -1
- package/dist/{chunk-3OAYAR43.js → chunk-7WMTUZ5O.js} +10 -10
- package/dist/{chunk-3OAYAR43.js.map → chunk-7WMTUZ5O.js.map} +1 -1
- package/dist/{chunk-BRCX6KNE.mjs → chunk-V775MBEJ.mjs} +3 -3
- package/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/webchat-es5.js +5 -5
- package/dist/webchat-minimal.js +4 -4
- package/dist/webchat.js +5 -5
- package/package.json +8 -8
- /package/dist/{chunk-3OAYAR43.js.LEGAL.txt → chunk-2KQWLCLT.mjs.LEGAL.txt} +0 -0
- /package/dist/{chunk-ASV62R53.mjs.map → chunk-2KQWLCLT.mjs.map} +0 -0
- /package/dist/{chunk-ASV62R53.mjs.LEGAL.txt → chunk-5MUSNARN.js.LEGAL.txt} +0 -0
- /package/dist/{chunk-BRCX6KNE.mjs.LEGAL.txt → chunk-7WMTUZ5O.js.LEGAL.txt} +0 -0
- /package/dist/{chunk-E2QTQNYP.js.LEGAL.txt → chunk-V775MBEJ.mjs.LEGAL.txt} +0 -0
- /package/dist/{chunk-BRCX6KNE.mjs.map → chunk-V775MBEJ.mjs.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/__w/1/s/BotFramework-WebChat/packages/bundle/dist/chunk-3OAYAR43.js","../../../node_modules/requires-port/index.js","../../../node_modules/querystringify/index.js","../../../node_modules/url-parse/index.js","../src/FullComposer.tsx","../src/AddFullBundle.tsx","../src/adaptiveCards/AdaptiveCardsComposer.tsx","../src/adaptiveCards/AdaptiveCardsContext.ts","../src/codeHighlighter/ShikiComposer.tsx","../../../node_modules/@shikijs/types/dist/index.mjs","../../../node_modules/@shikijs/engine-oniguruma/dist/index.mjs","../../../node_modules/@shikijs/core/dist/shared/core.afb6276c.mjs","../../../node_modules/@shikijs/vscode-textmate/dist/index.mjs","../../../node_modules/property-information/lib/html.js","../../../node_modules/hast-util-to-html/lib/handle/element.js","../../../node_modules/regex/src/utils.js","../../../node_modules/regex/src/atomic.js","../../../node_modules/regex/src/backcompat.js","../../../node_modules/regex/src/flag-n.js","../../../node_modules/regex/src/flag-x.js","../../../node_modules/regex/src/subroutines.js","../../../node_modules/oniguruma-to-js/dist/shared/oniguruma-to-js.2969e22d.mjs","../../../node_modules/@shikijs/core/dist/index.mjs","../../../node_modules/shiki/dist/themes/github-dark-default.mjs","../src/markdown/private/respectCRLF.ts","../../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/Queue.ts","../../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/AudioOutputStream.ts","../../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/WebsocketMessageFormatter.ts","../../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/ServiceTelemetryListener.Internal.ts","../../../node_modules/web-speech-cognitive-services/src/SpeechServices/patchOptions.ts","../../../node_modules/web-speech-cognitive-services/src/SpeechServices/TextToSpeech/buildSSML.js","../src/createCognitiveServicesSpeechServicesPonyfillFactory.ts"],"names":["require_requires_port","__commonJSMin","exports","module","port","protocol","require_querystringify","has","undef","decode","input","encode","querystring","query","parser","result","part","key","value","querystringify","obj","prefix","pairs","require_url_parse","required","qs","controlOrWhitespace","CRHTLF","slashes","protocolre","windowsDriveLetter","trimLeft","str","rules","address","url","isSpecial","ignore","lolcation","loc","globalVar","location","finaldestination","type","Url","scheme","extractProtocol","match","forwardSlashes","otherSlashes","slashesCount","rest","resolve","relative","base","path","i","last","unshift","up","extracted","parse","instruction","index","instructions","set","fn","char","ins","toString","stringify","host","AdaptiveCardsContext","createContext","AdaptiveCardsContext_default","AdaptiveCardsComposer","adaptiveCardsHostConfig","adaptiveCardsPackage","children","patchedAdaptiveCardsPackage","useMemo","defaultAdaptiveCardsPackage","adaptiveCardsContext","React","AdaptiveCardsComposer_default","ShikiError","message","getHeapMax","_emscripten_get_now","alignUp","x","multiple","main","init","wasmMemory","buffer","binding","updateGlobalBufferAndViews","buf","_emscripten_memcpy_big","dest","src","num","emscripten_realloc_buffer","size","_emscripten_resize_heap","requestedSize","oldSize","maxHeapSize","cutDown","overGrownHeapSize","newSize","UTF8Decoder","UTF8ArrayToString","heapOrArray","idx","maxBytesToRead","endIdx","endPtr","u0","u1","u2","ch","UTF8ToString","ptr","asmLibraryArg","createWasm","onigBinding","throwLastOnigError","UtfString","_UtfString","__publicField","utf16Length","utf8Length","computeIndicesMapping","utf16OffsetToUtf8","utf8OffsetToUtf16","utf8Value","i8","i16","charCode","codePoint","wasSurrogatePair","nextCharCode","len","codepoint","_OnigString","utfString","utf8Offset","utf16Offset","OnigString","OnigScanner","patterns","strPtrsArr","strLenArr","strPtrsPtr","strLenPtr","scannerPtr","string","startPosition","arg","options","debugCall","resultPtr","HEAPU32","offset","count","captureIndices","beg","end","isInstantiatorOptionsObject","dataOrOptions","isInstantiatorModule","isDataOptionsObject","isResponse","isArrayBuffer","data","_a","initPromise","loadWasm","_load","info","instance","_makeResponseStreamingLoader","_makeResponseNonStreamingLoader","_makeArrayBufferLoader","importObject","arrayBuffer","_defaultWasmLoader","getDefaultWasmLoader","createOnigurumaEngine","s","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AA;AfzEi8a;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AeuKl8a;AfrKk8a;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AgB0Dz7a;AhBxDy7a;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AgB0D98a,WAAA;AhBxD88a;AiB9Cz8a;AjBgDy8a;AACA;AiB9Cz8a,SAAA;AjBgDy8a;AiB9C57a,oBAAA;AjBgD47a;AACA;AkBvDz8a;AACb;AlByDs9a;AACA;AACA;AmBvDz8a;AnByDy8a;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AmBvDp9a,EAAA;AnByDo9a;AmBvDz8a,SAAA;AnByDy8a;AACA;AmB7Bz9a;AC3BgB;AACb;AACiB,oBAAA;ApB2Dq8a;AACA;AACA;AqBmD98a;ACmciC;ACxkBpB;ACGwC,EAAA;AAAS;ACmF5E,EAAA;AC2CE,0EAAA;ACtHM;AAcyC;A3BmE26a;A4BgIx9a;AClKb;AC3CqC,mBAAA;AAGpC,oBAAA;AACO,MAAA;A9B+E69a;AACA;A+BlC95a,QAAA;A/BoC85a","file":"/__w/1/s/BotFramework-WebChat/packages/bundle/dist/chunk-3OAYAR43.js","sourcesContent":[null,"'use strict';\n\n/**\n * Check if we're required to add a port number.\n *\n * @see https://url.spec.whatwg.org/#default-port\n * @param {Number|String} port Port number we need to check\n * @param {String} protocol Protocol we need to check against.\n * @returns {Boolean} Is it a default port for the given protocol\n * @api private\n */\nmodule.exports = function required(port, protocol) {\n protocol = protocol.split(':')[0];\n port = +port;\n\n if (!port) return false;\n\n switch (protocol) {\n case 'http':\n case 'ws':\n return port !== 80;\n\n case 'https':\n case 'wss':\n return port !== 443;\n\n case 'ftp':\n return port !== 21;\n\n case 'gopher':\n return port !== 70;\n\n case 'file':\n return false;\n }\n\n return port !== 0;\n};\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , undef;\n\n/**\n * Decode a URI encoded string.\n *\n * @param {String} input The URI encoded string.\n * @returns {String|Null} The decoded string.\n * @api private\n */\nfunction decode(input) {\n try {\n return decodeURIComponent(input.replace(/\\+/g, ' '));\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Attempts to encode a given input.\n *\n * @param {String} input The string that needs to be encoded.\n * @returns {String|Null} The encoded string.\n * @api private\n */\nfunction encode(input) {\n try {\n return encodeURIComponent(input);\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Simple query string parser.\n *\n * @param {String} query The query string that needs to be parsed.\n * @returns {Object}\n * @api public\n */\nfunction querystring(query) {\n var parser = /([^=?#&]+)=?([^&]*)/g\n , result = {}\n , part;\n\n while (part = parser.exec(query)) {\n var key = decode(part[1])\n , value = decode(part[2]);\n\n //\n // Prevent overriding of existing properties. This ensures that build-in\n // methods like `toString` or __proto__ are not overriden by malicious\n // querystrings.\n //\n // In the case if failed decoding, we want to omit the key/value pairs\n // from the result.\n //\n if (key === null || value === null || key in result) continue;\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Transform a query string to an object.\n *\n * @param {Object} obj Object that should be transformed.\n * @param {String} prefix Optional prefix.\n * @returns {String}\n * @api public\n */\nfunction querystringify(obj, prefix) {\n prefix = prefix || '';\n\n var pairs = []\n , value\n , key;\n\n //\n // Optionally prefix with a '?' if needed\n //\n if ('string' !== typeof prefix) prefix = '?';\n\n for (key in obj) {\n if (has.call(obj, key)) {\n value = obj[key];\n\n //\n // Edge cases where we actually want to encode the value to an empty\n // string instead of the stringified value.\n //\n if (!value && (value === null || value === undef || isNaN(value))) {\n value = '';\n }\n\n key = encode(key);\n value = encode(value);\n\n //\n // If we failed to encode the strings, we should bail out as we don't\n // want to add invalid strings to the query.\n //\n if (key === null || value === null) continue;\n pairs.push(key +'='+ value);\n }\n }\n\n return pairs.length ? prefix + pairs.join('&') : '';\n}\n\n//\n// Expose the module.\n//\nexports.stringify = querystringify;\nexports.parse = querystring;\n","'use strict';\n\nvar required = require('requires-port')\n , qs = require('querystringify')\n , controlOrWhitespace = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/\n , CRHTLF = /[\\n\\r\\t]/g\n , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//\n , port = /:\\d+$/\n , protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i\n , windowsDriveLetter = /^[a-zA-Z]:/;\n\n/**\n * Remove control characters and whitespace from the beginning of a string.\n *\n * @param {Object|String} str String to trim.\n * @returns {String} A new string representing `str` stripped of control\n * characters and whitespace from its beginning.\n * @public\n */\nfunction trimLeft(str) {\n return (str ? str : '').toString().replace(controlOrWhitespace, '');\n}\n\n/**\n * These are the parse rules for the URL parser, it informs the parser\n * about:\n *\n * 0. The char it Needs to parse, if it's a string it should be done using\n * indexOf, RegExp using exec and NaN means set as current value.\n * 1. The property we should set when parsing this value.\n * 2. Indication if it's backwards or forward parsing, when set as number it's\n * the value of extra chars that should be split off.\n * 3. Inherit from location if non existing in the parser.\n * 4. `toLowerCase` the resulting value.\n */\nvar rules = [\n ['#', 'hash'], // Extract from the back.\n ['?', 'query'], // Extract from the back.\n function sanitize(address, url) { // Sanitize what is left of the address\n return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n },\n ['/', 'pathname'], // Extract from the back.\n ['@', 'auth', 1], // Extract from the front.\n [NaN, 'host', undefined, 1, 1], // Set left over value.\n [/:(\\d*)$/, 'port', undefined, 1], // RegExp the back.\n [NaN, 'hostname', undefined, 1, 1] // Set left over.\n];\n\n/**\n * These properties should not be copied or inherited from. This is only needed\n * for all non blob URL's as a blob URL does not include a hash, only the\n * origin.\n *\n * @type {Object}\n * @private\n */\nvar ignore = { hash: 1, query: 1 };\n\n/**\n * The location object differs when your code is loaded through a normal page,\n * Worker or through a worker using a blob. And with the blobble begins the\n * trouble as the location object will contain the URL of the blob, not the\n * location of the page where our code is loaded in. The actual origin is\n * encoded in the `pathname` so we can thankfully generate a good \"default\"\n * location from it so we can generate proper relative URL's again.\n *\n * @param {Object|String} loc Optional default location object.\n * @returns {Object} lolcation object.\n * @public\n */\nfunction lolcation(loc) {\n var globalVar;\n\n if (typeof window !== 'undefined') globalVar = window;\n else if (typeof global !== 'undefined') globalVar = global;\n else if (typeof self !== 'undefined') globalVar = self;\n else globalVar = {};\n\n var location = globalVar.location || {};\n loc = loc || location;\n\n var finaldestination = {}\n , type = typeof loc\n , key;\n\n if ('blob:' === loc.protocol) {\n finaldestination = new Url(unescape(loc.pathname), {});\n } else if ('string' === type) {\n finaldestination = new Url(loc, {});\n for (key in ignore) delete finaldestination[key];\n } else if ('object' === type) {\n for (key in loc) {\n if (key in ignore) continue;\n finaldestination[key] = loc[key];\n }\n\n if (finaldestination.slashes === undefined) {\n finaldestination.slashes = slashes.test(loc.href);\n }\n }\n\n return finaldestination;\n}\n\n/**\n * Check whether a protocol scheme is special.\n *\n * @param {String} The protocol scheme of the URL\n * @return {Boolean} `true` if the protocol scheme is special, else `false`\n * @private\n */\nfunction isSpecial(scheme) {\n return (\n scheme === 'file:' ||\n scheme === 'ftp:' ||\n scheme === 'http:' ||\n scheme === 'https:' ||\n scheme === 'ws:' ||\n scheme === 'wss:'\n );\n}\n\n/**\n * @typedef ProtocolExtract\n * @type Object\n * @property {String} protocol Protocol matched in the URL, in lowercase.\n * @property {Boolean} slashes `true` if protocol is followed by \"//\", else `false`.\n * @property {String} rest Rest of the URL that is not part of the protocol.\n */\n\n/**\n * Extract protocol information from a URL with/without double slash (\"//\").\n *\n * @param {String} address URL we want to extract from.\n * @param {Object} location\n * @return {ProtocolExtract} Extracted information.\n * @private\n */\nfunction extractProtocol(address, location) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n location = location || {};\n\n var match = protocolre.exec(address);\n var protocol = match[1] ? match[1].toLowerCase() : '';\n var forwardSlashes = !!match[2];\n var otherSlashes = !!match[3];\n var slashesCount = 0;\n var rest;\n\n if (forwardSlashes) {\n if (otherSlashes) {\n rest = match[2] + match[3] + match[4];\n slashesCount = match[2].length + match[3].length;\n } else {\n rest = match[2] + match[4];\n slashesCount = match[2].length;\n }\n } else {\n if (otherSlashes) {\n rest = match[3] + match[4];\n slashesCount = match[3].length;\n } else {\n rest = match[4]\n }\n }\n\n if (protocol === 'file:') {\n if (slashesCount >= 2) {\n rest = rest.slice(2);\n }\n } else if (isSpecial(protocol)) {\n rest = match[4];\n } else if (protocol) {\n if (forwardSlashes) {\n rest = rest.slice(2);\n }\n } else if (slashesCount >= 2 && isSpecial(location.protocol)) {\n rest = match[4];\n }\n\n return {\n protocol: protocol,\n slashes: forwardSlashes || isSpecial(protocol),\n slashesCount: slashesCount,\n rest: rest\n };\n}\n\n/**\n * Resolve a relative URL pathname against a base URL pathname.\n *\n * @param {String} relative Pathname of the relative URL.\n * @param {String} base Pathname of the base URL.\n * @return {String} Resolved pathname.\n * @private\n */\nfunction resolve(relative, base) {\n if (relative === '') return base;\n\n var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))\n , i = path.length\n , last = path[i - 1]\n , unshift = false\n , up = 0;\n\n while (i--) {\n if (path[i] === '.') {\n path.splice(i, 1);\n } else if (path[i] === '..') {\n path.splice(i, 1);\n up++;\n } else if (up) {\n if (i === 0) unshift = true;\n path.splice(i, 1);\n up--;\n }\n }\n\n if (unshift) path.unshift('');\n if (last === '.' || last === '..') path.push('');\n\n return path.join('/');\n}\n\n/**\n * The actual URL instance. Instead of returning an object we've opted-in to\n * create an actual constructor as it's much more memory efficient and\n * faster and it pleases my OCD.\n *\n * It is worth noting that we should not use `URL` as class name to prevent\n * clashes with the global URL instance that got introduced in browsers.\n *\n * @constructor\n * @param {String} address URL we want to parse.\n * @param {Object|String} [location] Location defaults for relative paths.\n * @param {Boolean|Function} [parser] Parser for the query string.\n * @private\n */\nfunction Url(address, location, parser) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n\n if (!(this instanceof Url)) {\n return new Url(address, location, parser);\n }\n\n var relative, extracted, parse, instruction, index, key\n , instructions = rules.slice()\n , type = typeof location\n , url = this\n , i = 0;\n\n //\n // The following if statements allows this module two have compatibility with\n // 2 different API:\n //\n // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n // where the boolean indicates that the query string should also be parsed.\n //\n // 2. The `URL` interface of the browser which accepts a URL, object as\n // arguments. The supplied object will be used as default values / fall-back\n // for relative paths.\n //\n if ('object' !== type && 'string' !== type) {\n parser = location;\n location = null;\n }\n\n if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n location = lolcation(location);\n\n //\n // Extract protocol information before running the instructions.\n //\n extracted = extractProtocol(address || '', location);\n relative = !extracted.protocol && !extracted.slashes;\n url.slashes = extracted.slashes || relative && location.slashes;\n url.protocol = extracted.protocol || location.protocol || '';\n address = extracted.rest;\n\n //\n // When the authority component is absent the URL starts with a path\n // component.\n //\n if (\n extracted.protocol === 'file:' && (\n extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n (!extracted.slashes &&\n (extracted.protocol ||\n extracted.slashesCount < 2 ||\n !isSpecial(url.protocol)))\n ) {\n instructions[3] = [/(.*)/, 'pathname'];\n }\n\n for (; i < instructions.length; i++) {\n instruction = instructions[i];\n\n if (typeof instruction === 'function') {\n address = instruction(address, url);\n continue;\n }\n\n parse = instruction[0];\n key = instruction[1];\n\n if (parse !== parse) {\n url[key] = address;\n } else if ('string' === typeof parse) {\n index = parse === '@'\n ? address.lastIndexOf(parse)\n : address.indexOf(parse);\n\n if (~index) {\n if ('number' === typeof instruction[2]) {\n url[key] = address.slice(0, index);\n address = address.slice(index + instruction[2]);\n } else {\n url[key] = address.slice(index);\n address = address.slice(0, index);\n }\n }\n } else if ((index = parse.exec(address))) {\n url[key] = index[1];\n address = address.slice(0, index.index);\n }\n\n url[key] = url[key] || (\n relative && instruction[3] ? location[key] || '' : ''\n );\n\n //\n // Hostname, host and protocol should be lowercased so they can be used to\n // create a proper `origin`.\n //\n if (instruction[4]) url[key] = url[key].toLowerCase();\n }\n\n //\n // Also parse the supplied query string in to an object. If we're supplied\n // with a custom parser as function use that instead of the default build-in\n // parser.\n //\n if (parser) url.query = parser(url.query);\n\n //\n // If the URL is relative, resolve the pathname against the base URL.\n //\n if (\n relative\n && location.slashes\n && url.pathname.charAt(0) !== '/'\n && (url.pathname !== '' || location.pathname !== '')\n ) {\n url.pathname = resolve(url.pathname, location.pathname);\n }\n\n //\n // Default to a / for pathname if none exists. This normalizes the URL\n // to always have a /\n //\n if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n url.pathname = '/' + url.pathname;\n }\n\n //\n // We should not add port numbers if they are already the default port number\n // for a given protocol. As the host also contains the port number we're going\n // override it with the hostname which contains no port number.\n //\n if (!required(url.port, url.protocol)) {\n url.host = url.hostname;\n url.port = '';\n }\n\n //\n // Parse down the `auth` for the username and password.\n //\n url.username = url.password = '';\n\n if (url.auth) {\n index = url.auth.indexOf(':');\n\n if (~index) {\n url.username = url.auth.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = url.auth.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password))\n } else {\n url.username = encodeURIComponent(decodeURIComponent(url.auth));\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n }\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n //\n // The href is just the compiled result.\n //\n url.href = url.toString();\n}\n\n/**\n * This is convenience method for changing properties in the URL instance to\n * insure that they all propagate correctly.\n *\n * @param {String} part Property we need to adjust.\n * @param {Mixed} value The newly assigned value.\n * @param {Boolean|Function} fn When setting the query, it will be the function\n * used to parse the query.\n * When setting the protocol, double slash will be\n * removed from the final url if it is true.\n * @returns {URL} URL instance for chaining.\n * @public\n */\nfunction set(part, value, fn) {\n var url = this;\n\n switch (part) {\n case 'query':\n if ('string' === typeof value && value.length) {\n value = (fn || qs.parse)(value);\n }\n\n url[part] = value;\n break;\n\n case 'port':\n url[part] = value;\n\n if (!required(value, url.protocol)) {\n url.host = url.hostname;\n url[part] = '';\n } else if (value) {\n url.host = url.hostname +':'+ value;\n }\n\n break;\n\n case 'hostname':\n url[part] = value;\n\n if (url.port) value += ':'+ url.port;\n url.host = value;\n break;\n\n case 'host':\n url[part] = value;\n\n if (port.test(value)) {\n value = value.split(':');\n url.port = value.pop();\n url.hostname = value.join(':');\n } else {\n url.hostname = value;\n url.port = '';\n }\n\n break;\n\n case 'protocol':\n url.protocol = value.toLowerCase();\n url.slashes = !fn;\n break;\n\n case 'pathname':\n case 'hash':\n if (value) {\n var char = part === 'pathname' ? '/' : '#';\n url[part] = value.charAt(0) !== char ? char + value : value;\n } else {\n url[part] = value;\n }\n break;\n\n case 'username':\n case 'password':\n url[part] = encodeURIComponent(value);\n break;\n\n case 'auth':\n var index = value.indexOf(':');\n\n if (~index) {\n url.username = value.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = value.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password));\n } else {\n url.username = encodeURIComponent(decodeURIComponent(value));\n }\n }\n\n for (var i = 0; i < rules.length; i++) {\n var ins = rules[i];\n\n if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n url.href = url.toString();\n\n return url;\n}\n\n/**\n * Transform the properties back in to a valid and full URL string.\n *\n * @param {Function} stringify Optional query stringify function.\n * @returns {String} Compiled version of the URL.\n * @public\n */\nfunction toString(stringify) {\n if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n var query\n , url = this\n , host = url.host\n , protocol = url.protocol;\n\n if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n var result =\n protocol +\n ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n if (url.username) {\n result += url.username;\n if (url.password) result += ':'+ url.password;\n result += '@';\n } else if (url.password) {\n result += ':'+ url.password;\n result += '@';\n } else if (\n url.protocol !== 'file:' &&\n isSpecial(url.protocol) &&\n !host &&\n url.pathname !== '/'\n ) {\n //\n // Add back the empty userinfo, otherwise the original invalid URL\n // might be transformed into a valid one with `url.pathname` as host.\n //\n result += '@';\n }\n\n //\n // Trailing colon is removed from `url.host` when it is parsed. If it still\n // ends with a colon, then add back the trailing colon that was removed. This\n // prevents an invalid URL from being transformed into a valid one.\n //\n if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {\n host += ':';\n }\n\n result += host + url.pathname;\n\n query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n if (url.hash) result += url.hash;\n\n return result;\n}\n\nUrl.prototype = { set: set, toString: toString };\n\n//\n// Expose the URL parser and some additional properties that might be useful for\n// others or testing.\n//\nUrl.extractProtocol = extractProtocol;\nUrl.location = lolcation;\nUrl.trimLeft = trimLeft;\nUrl.qs = qs;\n\nmodule.exports = Url;\n","import { Components, type ComposerProps } from 'botframework-webchat-component';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport AddFullBundle, { type AddFullBundleProps } from './AddFullBundle';\n\nconst { Composer } = Components;\n\ntype FullComposerProps = ComposerProps & AddFullBundleProps;\n\nconst FullComposer = (props: FullComposerProps) => (\n <AddFullBundle {...props}>\n {extraProps => (\n <Composer {...props} {...extraProps}>\n {/* We need to spread, thus, we cannot we destructuring assignment. */}\n {/* eslint-disable-next-line react/destructuring-assignment */}\n {props.children}\n </Composer>\n )}\n </AddFullBundle>\n);\n\nFullComposer.defaultProps = {\n ...Composer.defaultProps,\n adaptiveCardsHostConfig: undefined,\n adaptiveCardsPackage: undefined,\n children: undefined\n};\n\nFullComposer.propTypes = {\n ...Composer.propTypes,\n adaptiveCardsHostConfig: PropTypes.any,\n adaptiveCardsPackage: PropTypes.any,\n children: PropTypes.any\n};\n\nexport default FullComposer;\n\nexport type { FullComposerProps };\n","import {\n type AttachmentForScreenReaderMiddleware,\n type AttachmentMiddleware,\n type StyleOptions\n} from 'botframework-webchat-api';\nimport { type HTMLContentTransformMiddleware } from 'botframework-webchat-component';\nimport { singleToArray, warnOnce, type OneOrMany } from 'botframework-webchat-core';\nimport React, { memo, type ReactNode } from 'react';\n\nimport AdaptiveCardsComposer from './adaptiveCards/AdaptiveCardsComposer';\nimport { type AdaptiveCardsStyleOptions } from './adaptiveCards/AdaptiveCardsStyleOptions';\nimport ShikiComposer from './codeHighlighter/ShikiComposer';\nimport { type AdaptiveCardsPackage } from './types/AdaptiveCardsPackage';\nimport { type StrictFullBundleStyleOptions } from './types/FullBundleStyleOptions';\nimport useComposerProps from './useComposerProps';\n\ntype AddFullBundleProps = Readonly<{\n adaptiveCardsHostConfig?: any;\n adaptiveCardsPackage?: AdaptiveCardsPackage;\n attachmentForScreenReaderMiddleware?: OneOrMany<AttachmentForScreenReaderMiddleware>;\n attachmentMiddleware?: OneOrMany<AttachmentMiddleware>;\n children: ({ extraStyleSet }: { extraStyleSet: any }) => ReactNode;\n htmlContentTransformMiddleware?: HTMLContentTransformMiddleware[];\n renderMarkdown?: (\n markdown: string,\n newLineOptions: { markdownRespectCRLF: boolean },\n linkOptions: { externalLinkAlt: string }\n ) => string;\n styleOptions?: StyleOptions & AdaptiveCardsStyleOptions;\n styleSet?: any & { options: StrictFullBundleStyleOptions };\n\n /** @deprecated Rename to \"adaptiveCardsHostConfig\" */\n adaptiveCardHostConfig?: any;\n}>;\n\nconst adaptiveCardHostConfigDeprecation = warnOnce(\n '\"adaptiveCardHostConfig\" is deprecated. Please use \"adaptiveCardsHostConfig\" instead. \"adaptiveCardHostConfig\" will be removed on or after 2022-01-01.'\n);\n\nfunction AddFullBundle({\n adaptiveCardHostConfig,\n adaptiveCardsHostConfig,\n adaptiveCardsPackage,\n attachmentForScreenReaderMiddleware,\n attachmentMiddleware,\n children,\n htmlContentTransformMiddleware,\n renderMarkdown,\n styleOptions,\n styleSet\n}: AddFullBundleProps) {\n adaptiveCardHostConfig && adaptiveCardHostConfigDeprecation();\n\n const patchedProps = useComposerProps({\n attachmentForScreenReaderMiddleware: singleToArray(attachmentForScreenReaderMiddleware),\n attachmentMiddleware: singleToArray(attachmentMiddleware),\n htmlContentTransformMiddleware,\n renderMarkdown,\n styleOptions,\n styleSet\n });\n\n return (\n <ShikiComposer>\n <AdaptiveCardsComposer\n adaptiveCardsHostConfig={adaptiveCardHostConfig || adaptiveCardsHostConfig}\n adaptiveCardsPackage={adaptiveCardsPackage}\n >\n {children(patchedProps)}\n </AdaptiveCardsComposer>\n </ShikiComposer>\n );\n}\n\nexport default memo(AddFullBundle);\n\nexport type { AddFullBundleProps };\n","import * as defaultAdaptiveCardsPackage from 'adaptivecards';\nimport React, { useMemo, type ReactNode } from 'react';\n\nimport { type AdaptiveCardsPackage } from '../types/AdaptiveCardsPackage';\nimport AdaptiveCardsContext from './AdaptiveCardsContext';\n\ntype AdaptiveCardsComposerProps = Readonly<{\n adaptiveCardsHostConfig: any;\n adaptiveCardsPackage: AdaptiveCardsPackage;\n children?: ReactNode | undefined;\n}>;\n\nconst AdaptiveCardsComposer = ({\n adaptiveCardsHostConfig,\n adaptiveCardsPackage,\n children\n}: AdaptiveCardsComposerProps) => {\n const patchedAdaptiveCardsPackage = useMemo(\n () => adaptiveCardsPackage || defaultAdaptiveCardsPackage,\n [adaptiveCardsPackage]\n );\n\n const adaptiveCardsContext = useMemo(\n () => ({\n adaptiveCardsPackage: patchedAdaptiveCardsPackage,\n hostConfigFromProps: adaptiveCardsHostConfig\n }),\n [adaptiveCardsHostConfig, patchedAdaptiveCardsPackage]\n );\n\n return <AdaptiveCardsContext.Provider value={adaptiveCardsContext}>{children}</AdaptiveCardsContext.Provider>;\n};\n\nexport default AdaptiveCardsComposer;\n","import { createContext } from 'react';\n\nimport { type AdaptiveCardsPackage } from '../types/AdaptiveCardsPackage';\n\ntype AdaptiveCardsContextType = {\n adaptiveCardsPackage: AdaptiveCardsPackage;\n hostConfigFromProps: any;\n};\n\nconst AdaptiveCardsContext = createContext<AdaptiveCardsContextType>(undefined);\n\nexport default AdaptiveCardsContext;\nexport type { AdaptiveCardsContextType };\n","import { CodeHighlighterComposer, type HighlightCodeFn } from 'botframework-webchat-component/internal';\nimport React, { memo, ReactNode, useEffect, useState } from 'react';\nimport { type HighlighterCore } from 'shiki';\n\nimport createHighlighter from './shiki';\n\nconst createHighligtCodeWithShiki =\n (shikiHiglighter: HighlighterCore): HighlightCodeFn =>\n (code, language, options) =>\n shikiHiglighter.codeToHtml(code, {\n lang: language,\n theme: options.theme\n });\n\nfunction ShikiComposer({ children }: { readonly children: ReactNode | undefined }) {\n const [highlightProps, setHighlightProps] = useState<Readonly<{ highlightCode: HighlightCodeFn }>>();\n\n useEffect(() => {\n let isMounted = true;\n (async () =>\n isMounted &&\n setHighlightProps(\n Object.freeze({\n highlightCode: createHighligtCodeWithShiki(await createHighlighter())\n })\n ))();\n return () => {\n isMounted = false;\n };\n }, []);\n\n return <CodeHighlighterComposer {...highlightProps}>{children}</CodeHighlighterComposer>;\n}\n\nexport default memo(ShikiComposer);\n","class ShikiError extends Error {\n constructor(message) {\n super(message);\n this.name = \"ShikiError\";\n }\n}\n\nexport { ShikiError };\n","class ShikiError extends Error {\n constructor(message) {\n super(message);\n this.name = 'ShikiError';\n }\n}\n\nfunction getHeapMax() {\n return 2147483648;\n}\nfunction _emscripten_get_now() {\n return typeof performance !== 'undefined' ? performance.now() : Date.now();\n}\nconst alignUp = (x, multiple) => x + ((multiple - (x % multiple)) % multiple);\nasync function main(init) {\n let wasmMemory;\n let buffer;\n const binding = {};\n function updateGlobalBufferAndViews(buf) {\n buffer = buf;\n binding.HEAPU8 = new Uint8Array(buf);\n binding.HEAPU32 = new Uint32Array(buf);\n }\n function _emscripten_memcpy_big(dest, src, num) {\n binding.HEAPU8.copyWithin(dest, src, src + num);\n }\n function emscripten_realloc_buffer(size) {\n try {\n wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16);\n updateGlobalBufferAndViews(wasmMemory.buffer);\n return 1;\n }\n catch { }\n }\n function _emscripten_resize_heap(requestedSize) {\n const oldSize = binding.HEAPU8.length;\n requestedSize = requestedSize >>> 0;\n const maxHeapSize = getHeapMax();\n if (requestedSize > maxHeapSize)\n return false;\n for (let cutDown = 1; cutDown <= 4; cutDown *= 2) {\n let overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);\n overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);\n const newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536));\n const replacement = emscripten_realloc_buffer(newSize);\n if (replacement)\n return true;\n }\n return false;\n }\n const UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf8') : undefined;\n function UTF8ArrayToString(heapOrArray, idx, maxBytesToRead = 1024) {\n const endIdx = idx + maxBytesToRead;\n let endPtr = idx;\n while (heapOrArray[endPtr] && !(endPtr >= endIdx))\n ++endPtr;\n if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {\n return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));\n }\n let str = '';\n while (idx < endPtr) {\n let u0 = heapOrArray[idx++];\n if (!(u0 & 128)) {\n str += String.fromCharCode(u0);\n continue;\n }\n const u1 = heapOrArray[idx++] & 63;\n if ((u0 & 224) === 192) {\n str += String.fromCharCode(((u0 & 31) << 6) | u1);\n continue;\n }\n const u2 = heapOrArray[idx++] & 63;\n if ((u0 & 240) === 224) {\n u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;\n }\n else {\n u0 = ((u0 & 7) << 18)\n | (u1 << 12)\n | (u2 << 6)\n | (heapOrArray[idx++] & 63);\n }\n if (u0 < 65536) {\n str += String.fromCharCode(u0);\n }\n else {\n const ch = u0 - 65536;\n str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023));\n }\n }\n return str;\n }\n function UTF8ToString(ptr, maxBytesToRead) {\n return ptr ? UTF8ArrayToString(binding.HEAPU8, ptr, maxBytesToRead) : '';\n }\n const asmLibraryArg = {\n emscripten_get_now: _emscripten_get_now,\n emscripten_memcpy_big: _emscripten_memcpy_big,\n emscripten_resize_heap: _emscripten_resize_heap,\n fd_write: () => 0,\n };\n async function createWasm() {\n const info = {\n env: asmLibraryArg,\n wasi_snapshot_preview1: asmLibraryArg,\n };\n const exports = await init(info);\n wasmMemory = exports.memory;\n updateGlobalBufferAndViews(wasmMemory.buffer);\n Object.assign(binding, exports);\n binding.UTF8ToString = UTF8ToString;\n }\n await createWasm();\n return binding;\n}\n\n/* ---------------------------------------------------------\n * Copyright (C) Microsoft Corporation. All rights reserved.\n *-------------------------------------------------------- */\nlet onigBinding = null;\n// let defaultDebugCall = false\nfunction throwLastOnigError(onigBinding) {\n throw new ShikiError(onigBinding.UTF8ToString(onigBinding.getLastOnigError()));\n}\nclass UtfString {\n static _utf8ByteLength(str) {\n let result = 0;\n for (let i = 0, len = str.length; i < len; i++) {\n const charCode = str.charCodeAt(i);\n let codepoint = charCode;\n let wasSurrogatePair = false;\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n // Hit a high surrogate, try to look for a matching low surrogate\n if (i + 1 < len) {\n const nextCharCode = str.charCodeAt(i + 1);\n if (nextCharCode >= 0xDC00 && nextCharCode <= 0xDFFF) {\n // Found the matching low surrogate\n codepoint = (((charCode - 0xD800) << 10) + 0x10000) | (nextCharCode - 0xDC00);\n wasSurrogatePair = true;\n }\n }\n }\n if (codepoint <= 0x7F)\n result += 1;\n else if (codepoint <= 0x7FF)\n result += 2;\n else if (codepoint <= 0xFFFF)\n result += 3;\n else\n result += 4;\n if (wasSurrogatePair)\n i++;\n }\n return result;\n }\n utf16Length;\n utf8Length;\n utf16Value;\n utf8Value;\n utf16OffsetToUtf8;\n utf8OffsetToUtf16;\n constructor(str) {\n const utf16Length = str.length;\n const utf8Length = UtfString._utf8ByteLength(str);\n const computeIndicesMapping = (utf8Length !== utf16Length);\n const utf16OffsetToUtf8 = computeIndicesMapping ? new Uint32Array(utf16Length + 1) : null;\n if (computeIndicesMapping)\n utf16OffsetToUtf8[utf16Length] = utf8Length;\n const utf8OffsetToUtf16 = computeIndicesMapping ? new Uint32Array(utf8Length + 1) : null;\n if (computeIndicesMapping)\n utf8OffsetToUtf16[utf8Length] = utf16Length;\n const utf8Value = new Uint8Array(utf8Length);\n let i8 = 0;\n for (let i16 = 0; i16 < utf16Length; i16++) {\n const charCode = str.charCodeAt(i16);\n let codePoint = charCode;\n let wasSurrogatePair = false;\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n // Hit a high surrogate, try to look for a matching low surrogate\n if (i16 + 1 < utf16Length) {\n const nextCharCode = str.charCodeAt(i16 + 1);\n if (nextCharCode >= 0xDC00 && nextCharCode <= 0xDFFF) {\n // Found the matching low surrogate\n codePoint = (((charCode - 0xD800) << 10) + 0x10000) | (nextCharCode - 0xDC00);\n wasSurrogatePair = true;\n }\n }\n }\n if (computeIndicesMapping) {\n utf16OffsetToUtf8[i16] = i8;\n if (wasSurrogatePair)\n utf16OffsetToUtf8[i16 + 1] = i8;\n if (codePoint <= 0x7F) {\n utf8OffsetToUtf16[i8 + 0] = i16;\n }\n else if (codePoint <= 0x7FF) {\n utf8OffsetToUtf16[i8 + 0] = i16;\n utf8OffsetToUtf16[i8 + 1] = i16;\n }\n else if (codePoint <= 0xFFFF) {\n utf8OffsetToUtf16[i8 + 0] = i16;\n utf8OffsetToUtf16[i8 + 1] = i16;\n utf8OffsetToUtf16[i8 + 2] = i16;\n }\n else {\n utf8OffsetToUtf16[i8 + 0] = i16;\n utf8OffsetToUtf16[i8 + 1] = i16;\n utf8OffsetToUtf16[i8 + 2] = i16;\n utf8OffsetToUtf16[i8 + 3] = i16;\n }\n }\n if (codePoint <= 0x7F) {\n utf8Value[i8++] = codePoint;\n }\n else if (codePoint <= 0x7FF) {\n utf8Value[i8++] = 0b11000000 | ((codePoint & 0b00000000000000000000011111000000) >>> 6);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n }\n else if (codePoint <= 0xFFFF) {\n utf8Value[i8++] = 0b11100000 | ((codePoint & 0b00000000000000001111000000000000) >>> 12);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n }\n else {\n utf8Value[i8++] = 0b11110000 | ((codePoint & 0b00000000000111000000000000000000) >>> 18);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000111111000000000000) >>> 12);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n }\n if (wasSurrogatePair)\n i16++;\n }\n this.utf16Length = utf16Length;\n this.utf8Length = utf8Length;\n this.utf16Value = str;\n this.utf8Value = utf8Value;\n this.utf16OffsetToUtf8 = utf16OffsetToUtf8;\n this.utf8OffsetToUtf16 = utf8OffsetToUtf16;\n }\n createString(onigBinding) {\n const result = onigBinding.omalloc(this.utf8Length);\n onigBinding.HEAPU8.set(this.utf8Value, result);\n return result;\n }\n}\nclass OnigString {\n static LAST_ID = 0;\n static _sharedPtr = 0; // a pointer to a string of 10000 bytes\n static _sharedPtrInUse = false;\n id = (++OnigString.LAST_ID);\n _onigBinding;\n content;\n utf16Length;\n utf8Length;\n utf16OffsetToUtf8;\n utf8OffsetToUtf16;\n ptr;\n constructor(str) {\n if (!onigBinding)\n throw new ShikiError('Must invoke loadWasm first.');\n this._onigBinding = onigBinding;\n this.content = str;\n const utfString = new UtfString(str);\n this.utf16Length = utfString.utf16Length;\n this.utf8Length = utfString.utf8Length;\n this.utf16OffsetToUtf8 = utfString.utf16OffsetToUtf8;\n this.utf8OffsetToUtf16 = utfString.utf8OffsetToUtf16;\n if (this.utf8Length < 10000 && !OnigString._sharedPtrInUse) {\n if (!OnigString._sharedPtr)\n OnigString._sharedPtr = onigBinding.omalloc(10000);\n OnigString._sharedPtrInUse = true;\n onigBinding.HEAPU8.set(utfString.utf8Value, OnigString._sharedPtr);\n this.ptr = OnigString._sharedPtr;\n }\n else {\n this.ptr = utfString.createString(onigBinding);\n }\n }\n convertUtf8OffsetToUtf16(utf8Offset) {\n if (this.utf8OffsetToUtf16) {\n if (utf8Offset < 0)\n return 0;\n if (utf8Offset > this.utf8Length)\n return this.utf16Length;\n return this.utf8OffsetToUtf16[utf8Offset];\n }\n return utf8Offset;\n }\n convertUtf16OffsetToUtf8(utf16Offset) {\n if (this.utf16OffsetToUtf8) {\n if (utf16Offset < 0)\n return 0;\n if (utf16Offset > this.utf16Length)\n return this.utf8Length;\n return this.utf16OffsetToUtf8[utf16Offset];\n }\n return utf16Offset;\n }\n dispose() {\n if (this.ptr === OnigString._sharedPtr)\n OnigString._sharedPtrInUse = false;\n else\n this._onigBinding.ofree(this.ptr);\n }\n}\nclass OnigScanner {\n _onigBinding;\n _ptr;\n constructor(patterns) {\n if (!onigBinding)\n throw new ShikiError('Must invoke loadWasm first.');\n const strPtrsArr = [];\n const strLenArr = [];\n for (let i = 0, len = patterns.length; i < len; i++) {\n const utfString = new UtfString(patterns[i]);\n strPtrsArr[i] = utfString.createString(onigBinding);\n strLenArr[i] = utfString.utf8Length;\n }\n const strPtrsPtr = onigBinding.omalloc(4 * patterns.length);\n onigBinding.HEAPU32.set(strPtrsArr, strPtrsPtr / 4);\n const strLenPtr = onigBinding.omalloc(4 * patterns.length);\n onigBinding.HEAPU32.set(strLenArr, strLenPtr / 4);\n const scannerPtr = onigBinding.createOnigScanner(strPtrsPtr, strLenPtr, patterns.length);\n for (let i = 0, len = patterns.length; i < len; i++)\n onigBinding.ofree(strPtrsArr[i]);\n onigBinding.ofree(strLenPtr);\n onigBinding.ofree(strPtrsPtr);\n if (scannerPtr === 0)\n throwLastOnigError(onigBinding);\n this._onigBinding = onigBinding;\n this._ptr = scannerPtr;\n }\n dispose() {\n this._onigBinding.freeOnigScanner(this._ptr);\n }\n findNextMatchSync(string, startPosition, arg) {\n // let debugCall = defaultDebugCall\n let options = 0 /* FindOption.None */;\n if (typeof arg === 'number') {\n // if (arg & FindOption.DebugCall)\n // debugCall = true\n options = arg;\n }\n if (typeof string === 'string') {\n string = new OnigString(string);\n const result = this._findNextMatchSync(string, startPosition, false, options);\n string.dispose();\n return result;\n }\n return this._findNextMatchSync(string, startPosition, false, options);\n }\n _findNextMatchSync(string, startPosition, debugCall, options) {\n const onigBinding = this._onigBinding;\n // let resultPtr: Pointer\n // if (debugCall)\n // resultPtr = onigBinding.findNextOnigScannerMatchDbg(this._ptr, string.id, string.ptr, string.utf8Length, string.convertUtf16OffsetToUtf8(startPosition), options)\n // else\n const resultPtr = onigBinding.findNextOnigScannerMatch(this._ptr, string.id, string.ptr, string.utf8Length, string.convertUtf16OffsetToUtf8(startPosition), options);\n if (resultPtr === 0) {\n // no match\n return null;\n }\n const HEAPU32 = onigBinding.HEAPU32;\n let offset = resultPtr / 4; // byte offset -> uint32 offset\n const index = HEAPU32[offset++];\n const count = HEAPU32[offset++];\n const captureIndices = [];\n for (let i = 0; i < count; i++) {\n const beg = string.convertUtf8OffsetToUtf16(HEAPU32[offset++]);\n const end = string.convertUtf8OffsetToUtf16(HEAPU32[offset++]);\n captureIndices[i] = {\n start: beg,\n end,\n length: end - beg,\n };\n }\n return {\n index,\n captureIndices,\n };\n }\n}\nfunction isInstantiatorOptionsObject(dataOrOptions) {\n return (typeof dataOrOptions.instantiator === 'function');\n}\nfunction isInstantiatorModule(dataOrOptions) {\n return (typeof dataOrOptions.default === 'function');\n}\nfunction isDataOptionsObject(dataOrOptions) {\n return (typeof dataOrOptions.data !== 'undefined');\n}\nfunction isResponse(dataOrOptions) {\n return (typeof Response !== 'undefined' && dataOrOptions instanceof Response);\n}\nfunction isArrayBuffer(data) {\n return (typeof ArrayBuffer !== 'undefined' && (data instanceof ArrayBuffer || ArrayBuffer.isView(data)))\n // eslint-disable-next-line node/prefer-global/buffer\n || (typeof Buffer !== 'undefined' && Buffer.isBuffer?.(data))\n || (typeof SharedArrayBuffer !== 'undefined' && data instanceof SharedArrayBuffer)\n || (typeof Uint32Array !== 'undefined' && data instanceof Uint32Array);\n}\nlet initPromise;\nfunction loadWasm(options) {\n if (initPromise)\n return initPromise;\n async function _load() {\n onigBinding = await main(async (info) => {\n let instance = options;\n instance = await instance;\n if (typeof instance === 'function')\n instance = await instance(info);\n if (typeof instance === 'function')\n instance = await instance(info);\n if (isInstantiatorOptionsObject(instance)) {\n instance = await instance.instantiator(info);\n }\n else if (isInstantiatorModule(instance)) {\n instance = await instance.default(info);\n }\n else {\n if (isDataOptionsObject(instance))\n instance = instance.data;\n if (isResponse(instance)) {\n if (typeof WebAssembly.instantiateStreaming === 'function')\n instance = await _makeResponseStreamingLoader(instance)(info);\n else\n instance = await _makeResponseNonStreamingLoader(instance)(info);\n }\n else if (isArrayBuffer(instance)) {\n instance = await _makeArrayBufferLoader(instance)(info);\n }\n // import(\"shiki/onig.wasm\") returns `{ default: WebAssembly.Module }` on cloudflare workers\n // https://developers.cloudflare.com/workers/wrangler/bundling/\n else if (instance instanceof WebAssembly.Module) {\n instance = await _makeArrayBufferLoader(instance)(info);\n }\n else if ('default' in instance && instance.default instanceof WebAssembly.Module) {\n instance = await _makeArrayBufferLoader(instance.default)(info);\n }\n }\n if ('instance' in instance)\n instance = instance.instance;\n if ('exports' in instance)\n instance = instance.exports;\n return instance;\n });\n }\n initPromise = _load();\n return initPromise;\n}\nfunction _makeArrayBufferLoader(data) {\n return importObject => WebAssembly.instantiate(data, importObject);\n}\nfunction _makeResponseStreamingLoader(data) {\n return importObject => WebAssembly.instantiateStreaming(data, importObject);\n}\nfunction _makeResponseNonStreamingLoader(data) {\n return async (importObject) => {\n const arrayBuffer = await data.arrayBuffer();\n return WebAssembly.instantiate(arrayBuffer, importObject);\n };\n}\n// export function createOnigString(str: string) {\n// return new OnigString(str)\n// }\n// export function createOnigScanner(patterns: string[]) {\n// return new OnigScanner(patterns)\n// }\n// export function setDefaultDebugCall(_defaultDebugCall: boolean): void {\n// defaultDebugCall = _defaultDebugCall\n// }\n\nlet _defaultWasmLoader;\n/**\n * Set the default wasm loader for `loadWasm`.\n * @internal\n */\nfunction setDefaultWasmLoader(_loader) {\n _defaultWasmLoader = _loader;\n}\n/**\n * @internal\n */\nfunction getDefaultWasmLoader() {\n return _defaultWasmLoader;\n}\nasync function createOnigurumaEngine(options) {\n if (options)\n await loadWasm(options);\n return {\n createScanner(patterns) {\n return new OnigScanner(patterns);\n },\n createString(s) {\n return new OnigString(s);\n },\n };\n}\n/**\n * Deprecated. Use `createOnigurumaEngine` instead.\n */\nasync function createWasmOnigEngine(options) {\n return createOnigurumaEngine(options);\n}\n\nexport { createOnigurumaEngine, createWasmOnigEngine, getDefaultWasmLoader, loadWasm, setDefaultWasmLoader };\n","let emitDeprecation = false;\nfunction enableDeprecationWarnings(value = true) {\n emitDeprecation = value;\n}\nfunction warnDeprecated(message) {\n if (emitDeprecation)\n console.trace(`[SHIKI DEPRECATE]: ${message}`);\n}\n\nexport { enableDeprecationWarnings as e, warnDeprecated as w };\n","// src/utils.ts\nfunction clone(something) {\n return doClone(something);\n}\nfunction doClone(something) {\n if (Array.isArray(something)) {\n return cloneArray(something);\n }\n if (typeof something === \"object\") {\n return cloneObj(something);\n }\n return something;\n}\nfunction cloneArray(arr) {\n let r = [];\n for (let i = 0, len = arr.length; i < len; i++) {\n r[i] = doClone(arr[i]);\n }\n return r;\n}\nfunction cloneObj(obj) {\n let r = {};\n for (let key in obj) {\n r[key] = doClone(obj[key]);\n }\n return r;\n}\nfunction mergeObjects(target, ...sources) {\n sources.forEach((source) => {\n for (let key in source) {\n target[key] = source[key];\n }\n });\n return target;\n}\nfunction basename(path) {\n const idx = ~path.lastIndexOf(\"/\") || ~path.lastIndexOf(\"\\\\\");\n if (idx === 0) {\n return path;\n } else if (~idx === path.length - 1) {\n return basename(path.substring(0, path.length - 1));\n } else {\n return path.substr(~idx + 1);\n }\n}\nvar CAPTURING_REGEX_SOURCE = /\\$(\\d+)|\\${(\\d+):\\/(downcase|upcase)}/g;\nvar RegexSource = class {\n static hasCaptures(regexSource) {\n if (regexSource === null) {\n return false;\n }\n CAPTURING_REGEX_SOURCE.lastIndex = 0;\n return CAPTURING_REGEX_SOURCE.test(regexSource);\n }\n static replaceCaptures(regexSource, captureSource, captureIndices) {\n return regexSource.replace(CAPTURING_REGEX_SOURCE, (match, index, commandIndex, command) => {\n let capture = captureIndices[parseInt(index || commandIndex, 10)];\n if (capture) {\n let result = captureSource.substring(capture.start, capture.end);\n while (result[0] === \".\") {\n result = result.substring(1);\n }\n switch (command) {\n case \"downcase\":\n return result.toLowerCase();\n case \"upcase\":\n return result.toUpperCase();\n default:\n return result;\n }\n } else {\n return match;\n }\n });\n }\n};\nfunction strcmp(a, b) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n}\nfunction strArrCmp(a, b) {\n if (a === null && b === null) {\n return 0;\n }\n if (!a) {\n return -1;\n }\n if (!b) {\n return 1;\n }\n let len1 = a.length;\n let len2 = b.length;\n if (len1 === len2) {\n for (let i = 0; i < len1; i++) {\n let res = strcmp(a[i], b[i]);\n if (res !== 0) {\n return res;\n }\n }\n return 0;\n }\n return len1 - len2;\n}\nfunction isValidHexColor(hex) {\n if (/^#[0-9a-f]{6}$/i.test(hex)) {\n return true;\n }\n if (/^#[0-9a-f]{8}$/i.test(hex)) {\n return true;\n }\n if (/^#[0-9a-f]{3}$/i.test(hex)) {\n return true;\n }\n if (/^#[0-9a-f]{4}$/i.test(hex)) {\n return true;\n }\n return false;\n}\nfunction escapeRegExpCharacters(value) {\n return value.replace(/[\\-\\\\\\{\\}\\*\\+\\?\\|\\^\\$\\.\\,\\[\\]\\(\\)\\#\\s]/g, \"\\\\$&\");\n}\nvar CachedFn = class {\n constructor(fn) {\n this.fn = fn;\n this.cache = /* @__PURE__ */ new Map();\n }\n get(key) {\n if (this.cache.has(key)) {\n return this.cache.get(key);\n }\n const value = this.fn(key);\n this.cache.set(key, value);\n return value;\n }\n};\n\n// src/theme.ts\nvar Theme = class {\n constructor(_colorMap, _defaults, _root) {\n this._colorMap = _colorMap;\n this._defaults = _defaults;\n this._root = _root;\n this._cachedMatchRoot = new CachedFn(\n (scopeName) => this._root.match(scopeName)\n );\n }\n static createFromRawTheme(source, colorMap) {\n return this.createFromParsedTheme(parseTheme(source), colorMap);\n }\n static createFromParsedTheme(source, colorMap) {\n return resolveParsedThemeRules(source, colorMap);\n }\n getColorMap() {\n return this._colorMap.getColorMap();\n }\n getDefaults() {\n return this._defaults;\n }\n match(scopePath) {\n if (scopePath === null) {\n return this._defaults;\n }\n const scopeName = scopePath.scopeName;\n const matchingTrieElements = this._cachedMatchRoot.get(scopeName);\n const effectiveRule = matchingTrieElements.find(\n (v) => _scopePathMatchesParentScopes(scopePath.parent, v.parentScopes)\n );\n if (!effectiveRule) {\n return null;\n }\n return new StyleAttributes(\n effectiveRule.fontStyle,\n effectiveRule.foreground,\n effectiveRule.background\n );\n }\n};\nvar ScopeStack = class _ScopeStack {\n constructor(parent, scopeName) {\n this.parent = parent;\n this.scopeName = scopeName;\n }\n static push(path, scopeNames) {\n for (const name of scopeNames) {\n path = new _ScopeStack(path, name);\n }\n return path;\n }\n static from(...segments) {\n let result = null;\n for (let i = 0; i < segments.length; i++) {\n result = new _ScopeStack(result, segments[i]);\n }\n return result;\n }\n push(scopeName) {\n return new _ScopeStack(this, scopeName);\n }\n getSegments() {\n let item = this;\n const result = [];\n while (item) {\n result.push(item.scopeName);\n item = item.parent;\n }\n result.reverse();\n return result;\n }\n toString() {\n return this.getSegments().join(\" \");\n }\n extends(other) {\n if (this === other) {\n return true;\n }\n if (this.parent === null) {\n return false;\n }\n return this.parent.extends(other);\n }\n getExtensionIfDefined(base) {\n const result = [];\n let item = this;\n while (item && item !== base) {\n result.push(item.scopeName);\n item = item.parent;\n }\n return item === base ? result.reverse() : void 0;\n }\n};\nfunction _scopePathMatchesParentScopes(scopePath, parentScopes) {\n if (parentScopes.length === 0) {\n return true;\n }\n for (let index = 0; index < parentScopes.length; index++) {\n let scopePattern = parentScopes[index];\n let scopeMustMatch = false;\n if (scopePattern === \">\") {\n if (index === parentScopes.length - 1) {\n return false;\n }\n scopePattern = parentScopes[++index];\n scopeMustMatch = true;\n }\n while (scopePath) {\n if (_matchesScope(scopePath.scopeName, scopePattern)) {\n break;\n }\n if (scopeMustMatch) {\n return false;\n }\n scopePath = scopePath.parent;\n }\n if (!scopePath) {\n return false;\n }\n scopePath = scopePath.parent;\n }\n return true;\n}\nfunction _matchesScope(scopeName, scopePattern) {\n return scopePattern === scopeName || scopeName.startsWith(scopePattern) && scopeName[scopePattern.length] === \".\";\n}\nvar StyleAttributes = class {\n constructor(fontStyle, foregroundId, backgroundId) {\n this.fontStyle = fontStyle;\n this.foregroundId = foregroundId;\n this.backgroundId = backgroundId;\n }\n};\nfunction parseTheme(source) {\n if (!source) {\n return [];\n }\n if (!source.settings || !Array.isArray(source.settings)) {\n return [];\n }\n let settings = source.settings;\n let result = [], resultLen = 0;\n for (let i = 0, len = settings.length; i < len; i++) {\n let entry = settings[i];\n if (!entry.settings) {\n continue;\n }\n let scopes;\n if (typeof entry.scope === \"string\") {\n let _scope = entry.scope;\n _scope = _scope.replace(/^[,]+/, \"\");\n _scope = _scope.replace(/[,]+$/, \"\");\n scopes = _scope.split(\",\");\n } else if (Array.isArray(entry.scope)) {\n scopes = entry.scope;\n } else {\n scopes = [\"\"];\n }\n let fontStyle = -1 /* NotSet */;\n if (typeof entry.settings.fontStyle === \"string\") {\n fontStyle = 0 /* None */;\n let segments = entry.settings.fontStyle.split(\" \");\n for (let j = 0, lenJ = segments.length; j < lenJ; j++) {\n let segment = segments[j];\n switch (segment) {\n case \"italic\":\n fontStyle = fontStyle | 1 /* Italic */;\n break;\n case \"bold\":\n fontStyle = fontStyle | 2 /* Bold */;\n break;\n case \"underline\":\n fontStyle = fontStyle | 4 /* Underline */;\n break;\n case \"strikethrough\":\n fontStyle = fontStyle | 8 /* Strikethrough */;\n break;\n }\n }\n }\n let foreground = null;\n if (typeof entry.settings.foreground === \"string\" && isValidHexColor(entry.settings.foreground)) {\n foreground = entry.settings.foreground;\n }\n let background = null;\n if (typeof entry.settings.background === \"string\" && isValidHexColor(entry.settings.background)) {\n background = entry.settings.background;\n }\n for (let j = 0, lenJ = scopes.length; j < lenJ; j++) {\n let _scope = scopes[j].trim();\n let segments = _scope.split(\" \");\n let scope = segments[segments.length - 1];\n let parentScopes = null;\n if (segments.length > 1) {\n parentScopes = segments.slice(0, segments.length - 1);\n parentScopes.reverse();\n }\n result[resultLen++] = new ParsedThemeRule(\n scope,\n parentScopes,\n i,\n fontStyle,\n foreground,\n background\n );\n }\n }\n return result;\n}\nvar ParsedThemeRule = class {\n constructor(scope, parentScopes, index, fontStyle, foreground, background) {\n this.scope = scope;\n this.parentScopes = parentScopes;\n this.index = index;\n this.fontStyle = fontStyle;\n this.foreground = foreground;\n this.background = background;\n }\n};\nvar FontStyle = /* @__PURE__ */ ((FontStyle2) => {\n FontStyle2[FontStyle2[\"NotSet\"] = -1] = \"NotSet\";\n FontStyle2[FontStyle2[\"None\"] = 0] = \"None\";\n FontStyle2[FontStyle2[\"Italic\"] = 1] = \"Italic\";\n FontStyle2[FontStyle2[\"Bold\"] = 2] = \"Bold\";\n FontStyle2[FontStyle2[\"Underline\"] = 4] = \"Underline\";\n FontStyle2[FontStyle2[\"Strikethrough\"] = 8] = \"Strikethrough\";\n return FontStyle2;\n})(FontStyle || {});\nfunction resolveParsedThemeRules(parsedThemeRules, _colorMap) {\n parsedThemeRules.sort((a, b) => {\n let r = strcmp(a.scope, b.scope);\n if (r !== 0) {\n return r;\n }\n r = strArrCmp(a.parentScopes, b.parentScopes);\n if (r !== 0) {\n return r;\n }\n return a.index - b.index;\n });\n let defaultFontStyle = 0 /* None */;\n let defaultForeground = \"#000000\";\n let defaultBackground = \"#ffffff\";\n while (parsedThemeRules.length >= 1 && parsedThemeRules[0].scope === \"\") {\n let incomingDefaults = parsedThemeRules.shift();\n if (incomingDefaults.fontStyle !== -1 /* NotSet */) {\n defaultFontStyle = incomingDefaults.fontStyle;\n }\n if (incomingDefaults.foreground !== null) {\n defaultForeground = incomingDefaults.foreground;\n }\n if (incomingDefaults.background !== null) {\n defaultBackground = incomingDefaults.background;\n }\n }\n let colorMap = new ColorMap(_colorMap);\n let defaults = new StyleAttributes(defaultFontStyle, colorMap.getId(defaultForeground), colorMap.getId(defaultBackground));\n let root = new ThemeTrieElement(new ThemeTrieElementRule(0, null, -1 /* NotSet */, 0, 0), []);\n for (let i = 0, len = parsedThemeRules.length; i < len; i++) {\n let rule = parsedThemeRules[i];\n root.insert(0, rule.scope, rule.parentScopes, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));\n }\n return new Theme(colorMap, defaults, root);\n}\nvar ColorMap = class {\n constructor(_colorMap) {\n this._lastColorId = 0;\n this._id2color = [];\n this._color2id = /* @__PURE__ */ Object.create(null);\n if (Array.isArray(_colorMap)) {\n this._isFrozen = true;\n for (let i = 0, len = _colorMap.length; i < len; i++) {\n this._color2id[_colorMap[i]] = i;\n this._id2color[i] = _colorMap[i];\n }\n } else {\n this._isFrozen = false;\n }\n }\n getId(color) {\n if (color === null) {\n return 0;\n }\n color = color.toUpperCase();\n let value = this._color2id[color];\n if (value) {\n return value;\n }\n if (this._isFrozen) {\n throw new Error(`Missing color in color map - ${color}`);\n }\n value = ++this._lastColorId;\n this._color2id[color] = value;\n this._id2color[value] = color;\n return value;\n }\n getColorMap() {\n return this._id2color.slice(0);\n }\n};\nvar emptyParentScopes = Object.freeze([]);\nvar ThemeTrieElementRule = class _ThemeTrieElementRule {\n constructor(scopeDepth, parentScopes, fontStyle, foreground, background) {\n this.scopeDepth = scopeDepth;\n this.parentScopes = parentScopes || emptyParentScopes;\n this.fontStyle = fontStyle;\n this.foreground = foreground;\n this.background = background;\n }\n clone() {\n return new _ThemeTrieElementRule(this.scopeDepth, this.parentScopes, this.fontStyle, this.foreground, this.background);\n }\n static cloneArr(arr) {\n let r = [];\n for (let i = 0, len = arr.length; i < len; i++) {\n r[i] = arr[i].clone();\n }\n return r;\n }\n acceptOverwrite(scopeDepth, fontStyle, foreground, background) {\n if (this.scopeDepth > scopeDepth) {\n console.log(\"how did this happen?\");\n } else {\n this.scopeDepth = scopeDepth;\n }\n if (fontStyle !== -1 /* NotSet */) {\n this.fontStyle = fontStyle;\n }\n if (foreground !== 0) {\n this.foreground = foreground;\n }\n if (background !== 0) {\n this.background = background;\n }\n }\n};\nvar ThemeTrieElement = class _ThemeTrieElement {\n constructor(_mainRule, rulesWithParentScopes = [], _children = {}) {\n this._mainRule = _mainRule;\n this._children = _children;\n this._rulesWithParentScopes = rulesWithParentScopes;\n }\n static _cmpBySpecificity(a, b) {\n if (a.scopeDepth !== b.scopeDepth) {\n return b.scopeDepth - a.scopeDepth;\n }\n let aParentIndex = 0;\n let bParentIndex = 0;\n while (true) {\n if (a.parentScopes[aParentIndex] === \">\") {\n aParentIndex++;\n }\n if (b.parentScopes[bParentIndex] === \">\") {\n bParentIndex++;\n }\n if (aParentIndex >= a.parentScopes.length || bParentIndex >= b.parentScopes.length) {\n break;\n }\n const parentScopeLengthDiff = b.parentScopes[bParentIndex].length - a.parentScopes[aParentIndex].length;\n if (parentScopeLengthDiff !== 0) {\n return parentScopeLengthDiff;\n }\n aParentIndex++;\n bParentIndex++;\n }\n return b.parentScopes.length - a.parentScopes.length;\n }\n match(scope) {\n if (scope !== \"\") {\n let dotIndex = scope.indexOf(\".\");\n let head;\n let tail;\n if (dotIndex === -1) {\n head = scope;\n tail = \"\";\n } else {\n head = scope.substring(0, dotIndex);\n tail = scope.substring(dotIndex + 1);\n }\n if (this._children.hasOwnProperty(head)) {\n return this._children[head].match(tail);\n }\n }\n const rules = this._rulesWithParentScopes.concat(this._mainRule);\n rules.sort(_ThemeTrieElement._cmpBySpecificity);\n return rules;\n }\n insert(scopeDepth, scope, parentScopes, fontStyle, foreground, background) {\n if (scope === \"\") {\n this._doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background);\n return;\n }\n let dotIndex = scope.indexOf(\".\");\n let head;\n let tail;\n if (dotIndex === -1) {\n head = scope;\n tail = \"\";\n } else {\n head = scope.substring(0, dotIndex);\n tail = scope.substring(dotIndex + 1);\n }\n let child;\n if (this._children.hasOwnProperty(head)) {\n child = this._children[head];\n } else {\n child = new _ThemeTrieElement(this._mainRule.clone(), ThemeTrieElementRule.cloneArr(this._rulesWithParentScopes));\n this._children[head] = child;\n }\n child.insert(scopeDepth + 1, tail, parentScopes, fontStyle, foreground, background);\n }\n _doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background) {\n if (parentScopes === null) {\n this._mainRule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);\n return;\n }\n for (let i = 0, len = this._rulesWithParentScopes.length; i < len; i++) {\n let rule = this._rulesWithParentScopes[i];\n if (strArrCmp(rule.parentScopes, parentScopes) === 0) {\n rule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);\n return;\n }\n }\n if (fontStyle === -1 /* NotSet */) {\n fontStyle = this._mainRule.fontStyle;\n }\n if (foreground === 0) {\n foreground = this._mainRule.foreground;\n }\n if (background === 0) {\n background = this._mainRule.background;\n }\n this._rulesWithParentScopes.push(new ThemeTrieElementRule(scopeDepth, parentScopes, fontStyle, foreground, background));\n }\n};\n\n// src/encodedTokenAttributes.ts\nvar EncodedTokenMetadata = class _EncodedTokenMetadata {\n static toBinaryStr(encodedTokenAttributes) {\n return encodedTokenAttributes.toString(2).padStart(32, \"0\");\n }\n static print(encodedTokenAttributes) {\n const languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);\n const tokenType = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);\n const fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);\n const foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);\n const background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);\n console.log({\n languageId,\n tokenType,\n fontStyle,\n foreground,\n background\n });\n }\n static getLanguageId(encodedTokenAttributes) {\n return (encodedTokenAttributes & 255 /* LANGUAGEID_MASK */) >>> 0 /* LANGUAGEID_OFFSET */;\n }\n static getTokenType(encodedTokenAttributes) {\n return (encodedTokenAttributes & 768 /* TOKEN_TYPE_MASK */) >>> 8 /* TOKEN_TYPE_OFFSET */;\n }\n static containsBalancedBrackets(encodedTokenAttributes) {\n return (encodedTokenAttributes & 1024 /* BALANCED_BRACKETS_MASK */) !== 0;\n }\n static getFontStyle(encodedTokenAttributes) {\n return (encodedTokenAttributes & 30720 /* FONT_STYLE_MASK */) >>> 11 /* FONT_STYLE_OFFSET */;\n }\n static getForeground(encodedTokenAttributes) {\n return (encodedTokenAttributes & 16744448 /* FOREGROUND_MASK */) >>> 15 /* FOREGROUND_OFFSET */;\n }\n static getBackground(encodedTokenAttributes) {\n return (encodedTokenAttributes & 4278190080 /* BACKGROUND_MASK */) >>> 24 /* BACKGROUND_OFFSET */;\n }\n /**\n * Updates the fields in `metadata`.\n * A value of `0`, `NotSet` or `null` indicates that the corresponding field should be left as is.\n */\n static set(encodedTokenAttributes, languageId, tokenType, containsBalancedBrackets, fontStyle, foreground, background) {\n let _languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);\n let _tokenType = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);\n let _containsBalancedBracketsBit = _EncodedTokenMetadata.containsBalancedBrackets(encodedTokenAttributes) ? 1 : 0;\n let _fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);\n let _foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);\n let _background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);\n if (languageId !== 0) {\n _languageId = languageId;\n }\n if (tokenType !== 8 /* NotSet */) {\n _tokenType = fromOptionalTokenType(tokenType);\n }\n if (containsBalancedBrackets !== null) {\n _containsBalancedBracketsBit = containsBalancedBrackets ? 1 : 0;\n }\n if (fontStyle !== -1 /* NotSet */) {\n _fontStyle = fontStyle;\n }\n if (foreground !== 0) {\n _foreground = foreground;\n }\n if (background !== 0) {\n _background = background;\n }\n return (_languageId << 0 /* LANGUAGEID_OFFSET */ | _tokenType << 8 /* TOKEN_TYPE_OFFSET */ | _containsBalancedBracketsBit << 10 /* BALANCED_BRACKETS_OFFSET */ | _fontStyle << 11 /* FONT_STYLE_OFFSET */ | _foreground << 15 /* FOREGROUND_OFFSET */ | _background << 24 /* BACKGROUND_OFFSET */) >>> 0;\n }\n};\nfunction toOptionalTokenType(standardType) {\n return standardType;\n}\nfunction fromOptionalTokenType(standardType) {\n return standardType;\n}\n\n// src/matcher.ts\nfunction createMatchers(selector, matchesName) {\n const results = [];\n const tokenizer = newTokenizer(selector);\n let token = tokenizer.next();\n while (token !== null) {\n let priority = 0;\n if (token.length === 2 && token.charAt(1) === \":\") {\n switch (token.charAt(0)) {\n case \"R\":\n priority = 1;\n break;\n case \"L\":\n priority = -1;\n break;\n default:\n console.log(`Unknown priority ${token} in scope selector`);\n }\n token = tokenizer.next();\n }\n let matcher = parseConjunction();\n results.push({ matcher, priority });\n if (token !== \",\") {\n break;\n }\n token = tokenizer.next();\n }\n return results;\n function parseOperand() {\n if (token === \"-\") {\n token = tokenizer.next();\n const expressionToNegate = parseOperand();\n return (matcherInput) => !!expressionToNegate && !expressionToNegate(matcherInput);\n }\n if (token === \"(\") {\n token = tokenizer.next();\n const expressionInParents = parseInnerExpression();\n if (token === \")\") {\n token = tokenizer.next();\n }\n return expressionInParents;\n }\n if (isIdentifier(token)) {\n const identifiers = [];\n do {\n identifiers.push(token);\n token = tokenizer.next();\n } while (isIdentifier(token));\n return (matcherInput) => matchesName(identifiers, matcherInput);\n }\n return null;\n }\n function parseConjunction() {\n const matchers = [];\n let matcher = parseOperand();\n while (matcher) {\n matchers.push(matcher);\n matcher = parseOperand();\n }\n return (matcherInput) => matchers.every((matcher2) => matcher2(matcherInput));\n }\n function parseInnerExpression() {\n const matchers = [];\n let matcher = parseConjunction();\n while (matcher) {\n matchers.push(matcher);\n if (token === \"|\" || token === \",\") {\n do {\n token = tokenizer.next();\n } while (token === \"|\" || token === \",\");\n } else {\n break;\n }\n matcher = parseConjunction();\n }\n return (matcherInput) => matchers.some((matcher2) => matcher2(matcherInput));\n }\n}\nfunction isIdentifier(token) {\n return !!token && !!token.match(/[\\w\\.:]+/);\n}\nfunction newTokenizer(input) {\n let regex = /([LR]:|[\\w\\.:][\\w\\.:\\-]*|[\\,\\|\\-\\(\\)])/g;\n let match = regex.exec(input);\n return {\n next: () => {\n if (!match) {\n return null;\n }\n const res = match[0];\n match = regex.exec(input);\n return res;\n }\n };\n}\n\n// src/onigLib.ts\nvar FindOption = /* @__PURE__ */ ((FindOption2) => {\n FindOption2[FindOption2[\"None\"] = 0] = \"None\";\n FindOption2[FindOption2[\"NotBeginString\"] = 1] = \"NotBeginString\";\n FindOption2[FindOption2[\"NotEndString\"] = 2] = \"NotEndString\";\n FindOption2[FindOption2[\"NotBeginPosition\"] = 4] = \"NotBeginPosition\";\n FindOption2[FindOption2[\"DebugCall\"] = 8] = \"DebugCall\";\n return FindOption2;\n})(FindOption || {});\nfunction disposeOnigString(str) {\n if (typeof str.dispose === \"function\") {\n str.dispose();\n }\n}\n\n// src/grammar/grammarDependencies.ts\nvar TopLevelRuleReference = class {\n constructor(scopeName) {\n this.scopeName = scopeName;\n }\n toKey() {\n return this.scopeName;\n }\n};\nvar TopLevelRepositoryRuleReference = class {\n constructor(scopeName, ruleName) {\n this.scopeName = scopeName;\n this.ruleName = ruleName;\n }\n toKey() {\n return `${this.scopeName}#${this.ruleName}`;\n }\n};\nvar ExternalReferenceCollector = class {\n constructor() {\n this._references = [];\n this._seenReferenceKeys = /* @__PURE__ */ new Set();\n this.visitedRule = /* @__PURE__ */ new Set();\n }\n get references() {\n return this._references;\n }\n add(reference) {\n const key = reference.toKey();\n if (this._seenReferenceKeys.has(key)) {\n return;\n }\n this._seenReferenceKeys.add(key);\n this._references.push(reference);\n }\n};\nvar ScopeDependencyProcessor = class {\n constructor(repo, initialScopeName) {\n this.repo = repo;\n this.initialScopeName = initialScopeName;\n this.seenFullScopeRequests = /* @__PURE__ */ new Set();\n this.seenPartialScopeRequests = /* @__PURE__ */ new Set();\n this.seenFullScopeRequests.add(this.initialScopeName);\n this.Q = [new TopLevelRuleReference(this.initialScopeName)];\n }\n processQueue() {\n const q = this.Q;\n this.Q = [];\n const deps = new ExternalReferenceCollector();\n for (const dep of q) {\n collectReferencesOfReference(dep, this.initialScopeName, this.repo, deps);\n }\n for (const dep of deps.references) {\n if (dep instanceof TopLevelRuleReference) {\n if (this.seenFullScopeRequests.has(dep.scopeName)) {\n continue;\n }\n this.seenFullScopeRequests.add(dep.scopeName);\n this.Q.push(dep);\n } else {\n if (this.seenFullScopeRequests.has(dep.scopeName)) {\n continue;\n }\n if (this.seenPartialScopeRequests.has(dep.toKey())) {\n continue;\n }\n this.seenPartialScopeRequests.add(dep.toKey());\n this.Q.push(dep);\n }\n }\n }\n};\nfunction collectReferencesOfReference(reference, baseGrammarScopeName, repo, result) {\n const selfGrammar = repo.lookup(reference.scopeName);\n if (!selfGrammar) {\n if (reference.scopeName === baseGrammarScopeName) {\n throw new Error(`No grammar provided for <${baseGrammarScopeName}>`);\n }\n return;\n }\n const baseGrammar = repo.lookup(baseGrammarScopeName);\n if (reference instanceof TopLevelRuleReference) {\n collectExternalReferencesInTopLevelRule({ baseGrammar, selfGrammar }, result);\n } else {\n collectExternalReferencesInTopLevelRepositoryRule(\n reference.ruleName,\n { baseGrammar, selfGrammar, repository: selfGrammar.repository },\n result\n );\n }\n const injections = repo.injections(reference.scopeName);\n if (injections) {\n for (const injection of injections) {\n result.add(new TopLevelRuleReference(injection));\n }\n }\n}\nfunction collectExternalReferencesInTopLevelRepositoryRule(ruleName, context, result) {\n if (context.repository && context.repository[ruleName]) {\n const rule = context.repository[ruleName];\n collectExternalReferencesInRules([rule], context, result);\n }\n}\nfunction collectExternalReferencesInTopLevelRule(context, result) {\n if (context.selfGrammar.patterns && Array.isArray(context.selfGrammar.patterns)) {\n collectExternalReferencesInRules(\n context.selfGrammar.patterns,\n { ...context, repository: context.selfGrammar.repository },\n result\n );\n }\n if (context.selfGrammar.injections) {\n collectExternalReferencesInRules(\n Object.values(context.selfGrammar.injections),\n { ...context, repository: context.selfGrammar.repository },\n result\n );\n }\n}\nfunction collectExternalReferencesInRules(rules, context, result) {\n for (const rule of rules) {\n if (result.visitedRule.has(rule)) {\n continue;\n }\n result.visitedRule.add(rule);\n const patternRepository = rule.repository ? mergeObjects({}, context.repository, rule.repository) : context.repository;\n if (Array.isArray(rule.patterns)) {\n collectExternalReferencesInRules(rule.patterns, { ...context, repository: patternRepository }, result);\n }\n const include = rule.include;\n if (!include) {\n continue;\n }\n const reference = parseInclude(include);\n switch (reference.kind) {\n case 0 /* Base */:\n collectExternalReferencesInTopLevelRule({ ...context, selfGrammar: context.baseGrammar }, result);\n break;\n case 1 /* Self */:\n collectExternalReferencesInTopLevelRule(context, result);\n break;\n case 2 /* RelativeReference */:\n collectExternalReferencesInTopLevelRepositoryRule(reference.ruleName, { ...context, repository: patternRepository }, result);\n break;\n case 3 /* TopLevelReference */:\n case 4 /* TopLevelRepositoryReference */:\n const selfGrammar = reference.scopeName === context.selfGrammar.scopeName ? context.selfGrammar : reference.scopeName === context.baseGrammar.scopeName ? context.baseGrammar : void 0;\n if (selfGrammar) {\n const newContext = { baseGrammar: context.baseGrammar, selfGrammar, repository: patternRepository };\n if (reference.kind === 4 /* TopLevelRepositoryReference */) {\n collectExternalReferencesInTopLevelRepositoryRule(reference.ruleName, newContext, result);\n } else {\n collectExternalReferencesInTopLevelRule(newContext, result);\n }\n } else {\n if (reference.kind === 4 /* TopLevelRepositoryReference */) {\n result.add(new TopLevelRepositoryRuleReference(reference.scopeName, reference.ruleName));\n } else {\n result.add(new TopLevelRuleReference(reference.scopeName));\n }\n }\n break;\n }\n }\n}\nvar BaseReference = class {\n constructor() {\n this.kind = 0 /* Base */;\n }\n};\nvar SelfReference = class {\n constructor() {\n this.kind = 1 /* Self */;\n }\n};\nvar RelativeReference = class {\n constructor(ruleName) {\n this.ruleName = ruleName;\n this.kind = 2 /* RelativeReference */;\n }\n};\nvar TopLevelReference = class {\n constructor(scopeName) {\n this.scopeName = scopeName;\n this.kind = 3 /* TopLevelReference */;\n }\n};\nvar TopLevelRepositoryReference = class {\n constructor(scopeName, ruleName) {\n this.scopeName = scopeName;\n this.ruleName = ruleName;\n this.kind = 4 /* TopLevelRepositoryReference */;\n }\n};\nfunction parseInclude(include) {\n if (include === \"$base\") {\n return new BaseReference();\n } else if (include === \"$self\") {\n return new SelfReference();\n }\n const indexOfSharp = include.indexOf(\"#\");\n if (indexOfSharp === -1) {\n return new TopLevelReference(include);\n } else if (indexOfSharp === 0) {\n return new RelativeReference(include.substring(1));\n } else {\n const scopeName = include.substring(0, indexOfSharp);\n const ruleName = include.substring(indexOfSharp + 1);\n return new TopLevelRepositoryReference(scopeName, ruleName);\n }\n}\n\n// src/rule.ts\nvar HAS_BACK_REFERENCES = /\\\\(\\d+)/;\nvar BACK_REFERENCING_END = /\\\\(\\d+)/g;\nvar ruleIdSymbol = Symbol(\"RuleId\");\nvar endRuleId = -1;\nvar whileRuleId = -2;\nfunction ruleIdFromNumber(id) {\n return id;\n}\nfunction ruleIdToNumber(id) {\n return id;\n}\nvar Rule = class {\n constructor($location, id, name, contentName) {\n this.$location = $location;\n this.id = id;\n this._name = name || null;\n this._nameIsCapturing = RegexSource.hasCaptures(this._name);\n this._contentName = contentName || null;\n this._contentNameIsCapturing = RegexSource.hasCaptures(this._contentName);\n }\n get debugName() {\n const location = this.$location ? `${basename(this.$location.filename)}:${this.$location.line}` : \"unknown\";\n return `${this.constructor.name}#${this.id} @ ${location}`;\n }\n getName(lineText, captureIndices) {\n if (!this._nameIsCapturing || this._name === null || lineText === null || captureIndices === null) {\n return this._name;\n }\n return RegexSource.replaceCaptures(this._name, lineText, captureIndices);\n }\n getContentName(lineText, captureIndices) {\n if (!this._contentNameIsCapturing || this._contentName === null) {\n return this._contentName;\n }\n return RegexSource.replaceCaptures(this._contentName, lineText, captureIndices);\n }\n};\nvar CaptureRule = class extends Rule {\n constructor($location, id, name, contentName, retokenizeCapturedWithRuleId) {\n super($location, id, name, contentName);\n this.retokenizeCapturedWithRuleId = retokenizeCapturedWithRuleId;\n }\n dispose() {\n }\n collectPatterns(grammar, out) {\n throw new Error(\"Not supported!\");\n }\n compile(grammar, endRegexSource) {\n throw new Error(\"Not supported!\");\n }\n compileAG(grammar, endRegexSource, allowA, allowG) {\n throw new Error(\"Not supported!\");\n }\n};\nvar MatchRule = class extends Rule {\n constructor($location, id, name, match, captures) {\n super($location, id, name, null);\n this._match = new RegExpSource(match, this.id);\n this.captures = captures;\n this._cachedCompiledPatterns = null;\n }\n dispose() {\n if (this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns.dispose();\n this._cachedCompiledPatterns = null;\n }\n }\n get debugMatchRegExp() {\n return `${this._match.source}`;\n }\n collectPatterns(grammar, out) {\n out.push(this._match);\n }\n compile(grammar, endRegexSource) {\n return this._getCachedCompiledPatterns(grammar).compile(grammar);\n }\n compileAG(grammar, endRegexSource, allowA, allowG) {\n return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);\n }\n _getCachedCompiledPatterns(grammar) {\n if (!this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns = new RegExpSourceList();\n this.collectPatterns(grammar, this._cachedCompiledPatterns);\n }\n return this._cachedCompiledPatterns;\n }\n};\nvar IncludeOnlyRule = class extends Rule {\n constructor($location, id, name, contentName, patterns) {\n super($location, id, name, contentName);\n this.patterns = patterns.patterns;\n this.hasMissingPatterns = patterns.hasMissingPatterns;\n this._cachedCompiledPatterns = null;\n }\n dispose() {\n if (this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns.dispose();\n this._cachedCompiledPatterns = null;\n }\n }\n collectPatterns(grammar, out) {\n for (const pattern of this.patterns) {\n const rule = grammar.getRule(pattern);\n rule.collectPatterns(grammar, out);\n }\n }\n compile(grammar, endRegexSource) {\n return this._getCachedCompiledPatterns(grammar).compile(grammar);\n }\n compileAG(grammar, endRegexSource, allowA, allowG) {\n return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);\n }\n _getCachedCompiledPatterns(grammar) {\n if (!this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns = new RegExpSourceList();\n this.collectPatterns(grammar, this._cachedCompiledPatterns);\n }\n return this._cachedCompiledPatterns;\n }\n};\nvar BeginEndRule = class extends Rule {\n constructor($location, id, name, contentName, begin, beginCaptures, end, endCaptures, applyEndPatternLast, patterns) {\n super($location, id, name, contentName);\n this._begin = new RegExpSource(begin, this.id);\n this.beginCaptures = beginCaptures;\n this._end = new RegExpSource(end ? end : \"\\uFFFF\", -1);\n this.endHasBackReferences = this._end.hasBackReferences;\n this.endCaptures = endCaptures;\n this.applyEndPatternLast = applyEndPatternLast || false;\n this.patterns = patterns.patterns;\n this.hasMissingPatterns = patterns.hasMissingPatterns;\n this._cachedCompiledPatterns = null;\n }\n dispose() {\n if (this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns.dispose();\n this._cachedCompiledPatterns = null;\n }\n }\n get debugBeginRegExp() {\n return `${this._begin.source}`;\n }\n get debugEndRegExp() {\n return `${this._end.source}`;\n }\n getEndWithResolvedBackReferences(lineText, captureIndices) {\n return this._end.resolveBackReferences(lineText, captureIndices);\n }\n collectPatterns(grammar, out) {\n out.push(this._begin);\n }\n compile(grammar, endRegexSource) {\n return this._getCachedCompiledPatterns(grammar, endRegexSource).compile(grammar);\n }\n compileAG(grammar, endRegexSource, allowA, allowG) {\n return this._getCachedCompiledPatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);\n }\n _getCachedCompiledPatterns(grammar, endRegexSource) {\n if (!this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns = new RegExpSourceList();\n for (const pattern of this.patterns) {\n const rule = grammar.getRule(pattern);\n rule.collectPatterns(grammar, this._cachedCompiledPatterns);\n }\n if (this.applyEndPatternLast) {\n this._cachedCompiledPatterns.push(this._end.hasBackReferences ? this._end.clone() : this._end);\n } else {\n this._cachedCompiledPatterns.unshift(this._end.hasBackReferences ? this._end.clone() : this._end);\n }\n }\n if (this._end.hasBackReferences) {\n if (this.applyEndPatternLast) {\n this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length() - 1, endRegexSource);\n } else {\n this._cachedCompiledPatterns.setSource(0, endRegexSource);\n }\n }\n return this._cachedCompiledPatterns;\n }\n};\nvar BeginWhileRule = class extends Rule {\n constructor($location, id, name, contentName, begin, beginCaptures, _while, whileCaptures, patterns) {\n super($location, id, name, contentName);\n this._begin = new RegExpSource(begin, this.id);\n this.beginCaptures = beginCaptures;\n this.whileCaptures = whileCaptures;\n this._while = new RegExpSource(_while, whileRuleId);\n this.whileHasBackReferences = this._while.hasBackReferences;\n this.patterns = patterns.patterns;\n this.hasMissingPatterns = patterns.hasMissingPatterns;\n this._cachedCompiledPatterns = null;\n this._cachedCompiledWhilePatterns = null;\n }\n dispose() {\n if (this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns.dispose();\n this._cachedCompiledPatterns = null;\n }\n if (this._cachedCompiledWhilePatterns) {\n this._cachedCompiledWhilePatterns.dispose();\n this._cachedCompiledWhilePatterns = null;\n }\n }\n get debugBeginRegExp() {\n return `${this._begin.source}`;\n }\n get debugWhileRegExp() {\n return `${this._while.source}`;\n }\n getWhileWithResolvedBackReferences(lineText, captureIndices) {\n return this._while.resolveBackReferences(lineText, captureIndices);\n }\n collectPatterns(grammar, out) {\n out.push(this._begin);\n }\n compile(grammar, endRegexSource) {\n return this._getCachedCompiledPatterns(grammar).compile(grammar);\n }\n compileAG(grammar, endRegexSource, allowA, allowG) {\n return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);\n }\n _getCachedCompiledPatterns(grammar) {\n if (!this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns = new RegExpSourceList();\n for (const pattern of this.patterns) {\n const rule = grammar.getRule(pattern);\n rule.collectPatterns(grammar, this._cachedCompiledPatterns);\n }\n }\n return this._cachedCompiledPatterns;\n }\n compileWhile(grammar, endRegexSource) {\n return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compile(grammar);\n }\n compileWhileAG(grammar, endRegexSource, allowA, allowG) {\n return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);\n }\n _getCachedCompiledWhilePatterns(grammar, endRegexSource) {\n if (!this._cachedCompiledWhilePatterns) {\n this._cachedCompiledWhilePatterns = new RegExpSourceList();\n this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences ? this._while.clone() : this._while);\n }\n if (this._while.hasBackReferences) {\n this._cachedCompiledWhilePatterns.setSource(0, endRegexSource ? endRegexSource : \"\\uFFFF\");\n }\n return this._cachedCompiledWhilePatterns;\n }\n};\nvar RuleFactory = class _RuleFactory {\n static createCaptureRule(helper, $location, name, contentName, retokenizeCapturedWithRuleId) {\n return helper.registerRule((id) => {\n return new CaptureRule($location, id, name, contentName, retokenizeCapturedWithRuleId);\n });\n }\n static getCompiledRuleId(desc, helper, repository) {\n if (!desc.id) {\n helper.registerRule((id) => {\n desc.id = id;\n if (desc.match) {\n return new MatchRule(\n desc.$vscodeTextmateLocation,\n desc.id,\n desc.name,\n desc.match,\n _RuleFactory._compileCaptures(desc.captures, helper, repository)\n );\n }\n if (typeof desc.begin === \"undefined\") {\n if (desc.repository) {\n repository = mergeObjects({}, repository, desc.repository);\n }\n let patterns = desc.patterns;\n if (typeof patterns === \"undefined\" && desc.include) {\n patterns = [{ include: desc.include }];\n }\n return new IncludeOnlyRule(\n desc.$vscodeTextmateLocation,\n desc.id,\n desc.name,\n desc.contentName,\n _RuleFactory._compilePatterns(patterns, helper, repository)\n );\n }\n if (desc.while) {\n return new BeginWhileRule(\n desc.$vscodeTextmateLocation,\n desc.id,\n desc.name,\n desc.contentName,\n desc.begin,\n _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository),\n desc.while,\n _RuleFactory._compileCaptures(desc.whileCaptures || desc.captures, helper, repository),\n _RuleFactory._compilePatterns(desc.patterns, helper, repository)\n );\n }\n return new BeginEndRule(\n desc.$vscodeTextmateLocation,\n desc.id,\n desc.name,\n desc.contentName,\n desc.begin,\n _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository),\n desc.end,\n _RuleFactory._compileCaptures(desc.endCaptures || desc.captures, helper, repository),\n desc.applyEndPatternLast,\n _RuleFactory._compilePatterns(desc.patterns, helper, repository)\n );\n });\n }\n return desc.id;\n }\n static _compileCaptures(captures, helper, repository) {\n let r = [];\n if (captures) {\n let maximumCaptureId = 0;\n for (const captureId in captures) {\n if (captureId === \"$vscodeTextmateLocation\") {\n continue;\n }\n const numericCaptureId = parseInt(captureId, 10);\n if (numericCaptureId > maximumCaptureId) {\n maximumCaptureId = numericCaptureId;\n }\n }\n for (let i = 0; i <= maximumCaptureId; i++) {\n r[i] = null;\n }\n for (const captureId in captures) {\n if (captureId === \"$vscodeTextmateLocation\") {\n continue;\n }\n const numericCaptureId = parseInt(captureId, 10);\n let retokenizeCapturedWithRuleId = 0;\n if (captures[captureId].patterns) {\n retokenizeCapturedWithRuleId = _RuleFactory.getCompiledRuleId(captures[captureId], helper, repository);\n }\n r[numericCaptureId] = _RuleFactory.createCaptureRule(helper, captures[captureId].$vscodeTextmateLocation, captures[captureId].name, captures[captureId].contentName, retokenizeCapturedWithRuleId);\n }\n }\n return r;\n }\n static _compilePatterns(patterns, helper, repository) {\n let r = [];\n if (patterns) {\n for (let i = 0, len = patterns.length; i < len; i++) {\n const pattern = patterns[i];\n let ruleId = -1;\n if (pattern.include) {\n const reference = parseInclude(pattern.include);\n switch (reference.kind) {\n case 0 /* Base */:\n case 1 /* Self */:\n ruleId = _RuleFactory.getCompiledRuleId(repository[pattern.include], helper, repository);\n break;\n case 2 /* RelativeReference */:\n let localIncludedRule = repository[reference.ruleName];\n if (localIncludedRule) {\n ruleId = _RuleFactory.getCompiledRuleId(localIncludedRule, helper, repository);\n } else {\n }\n break;\n case 3 /* TopLevelReference */:\n case 4 /* TopLevelRepositoryReference */:\n const externalGrammarName = reference.scopeName;\n const externalGrammarInclude = reference.kind === 4 /* TopLevelRepositoryReference */ ? reference.ruleName : null;\n const externalGrammar = helper.getExternalGrammar(externalGrammarName, repository);\n if (externalGrammar) {\n if (externalGrammarInclude) {\n let externalIncludedRule = externalGrammar.repository[externalGrammarInclude];\n if (externalIncludedRule) {\n ruleId = _RuleFactory.getCompiledRuleId(externalIncludedRule, helper, externalGrammar.repository);\n } else {\n }\n } else {\n ruleId = _RuleFactory.getCompiledRuleId(externalGrammar.repository.$self, helper, externalGrammar.repository);\n }\n } else {\n }\n break;\n }\n } else {\n ruleId = _RuleFactory.getCompiledRuleId(pattern, helper, repository);\n }\n if (ruleId !== -1) {\n const rule = helper.getRule(ruleId);\n let skipRule = false;\n if (rule instanceof IncludeOnlyRule || rule instanceof BeginEndRule || rule instanceof BeginWhileRule) {\n if (rule.hasMissingPatterns && rule.patterns.length === 0) {\n skipRule = true;\n }\n }\n if (skipRule) {\n continue;\n }\n r.push(ruleId);\n }\n }\n }\n return {\n patterns: r,\n hasMissingPatterns: (patterns ? patterns.length : 0) !== r.length\n };\n }\n};\nvar RegExpSource = class _RegExpSource {\n constructor(regExpSource, ruleId) {\n if (regExpSource) {\n const len = regExpSource.length;\n let lastPushedPos = 0;\n let output = [];\n let hasAnchor = false;\n for (let pos = 0; pos < len; pos++) {\n const ch = regExpSource.charAt(pos);\n if (ch === \"\\\\\") {\n if (pos + 1 < len) {\n const nextCh = regExpSource.charAt(pos + 1);\n if (nextCh === \"z\") {\n output.push(regExpSource.substring(lastPushedPos, pos));\n output.push(\"$(?!\\\\n)(?<!\\\\n)\");\n lastPushedPos = pos + 2;\n } else if (nextCh === \"A\" || nextCh === \"G\") {\n hasAnchor = true;\n }\n pos++;\n }\n }\n }\n this.hasAnchor = hasAnchor;\n if (lastPushedPos === 0) {\n this.source = regExpSource;\n } else {\n output.push(regExpSource.substring(lastPushedPos, len));\n this.source = output.join(\"\");\n }\n } else {\n this.hasAnchor = false;\n this.source = regExpSource;\n }\n if (this.hasAnchor) {\n this._anchorCache = this._buildAnchorCache();\n } else {\n this._anchorCache = null;\n }\n this.ruleId = ruleId;\n this.hasBackReferences = HAS_BACK_REFERENCES.test(this.source);\n }\n clone() {\n return new _RegExpSource(this.source, this.ruleId);\n }\n setSource(newSource) {\n if (this.source === newSource) {\n return;\n }\n this.source = newSource;\n if (this.hasAnchor) {\n this._anchorCache = this._buildAnchorCache();\n }\n }\n resolveBackReferences(lineText, captureIndices) {\n let capturedValues = captureIndices.map((capture) => {\n return lineText.substring(capture.start, capture.end);\n });\n BACK_REFERENCING_END.lastIndex = 0;\n return this.source.replace(BACK_REFERENCING_END, (match, g1) => {\n return escapeRegExpCharacters(capturedValues[parseInt(g1, 10)] || \"\");\n });\n }\n _buildAnchorCache() {\n let A0_G0_result = [];\n let A0_G1_result = [];\n let A1_G0_result = [];\n let A1_G1_result = [];\n let pos, len, ch, nextCh;\n for (pos = 0, len = this.source.length; pos < len; pos++) {\n ch = this.source.charAt(pos);\n A0_G0_result[pos] = ch;\n A0_G1_result[pos] = ch;\n A1_G0_result[pos] = ch;\n A1_G1_result[pos] = ch;\n if (ch === \"\\\\\") {\n if (pos + 1 < len) {\n nextCh = this.source.charAt(pos + 1);\n if (nextCh === \"A\") {\n A0_G0_result[pos + 1] = \"\\uFFFF\";\n A0_G1_result[pos + 1] = \"\\uFFFF\";\n A1_G0_result[pos + 1] = \"A\";\n A1_G1_result[pos + 1] = \"A\";\n } else if (nextCh === \"G\") {\n A0_G0_result[pos + 1] = \"\\uFFFF\";\n A0_G1_result[pos + 1] = \"G\";\n A1_G0_result[pos + 1] = \"\\uFFFF\";\n A1_G1_result[pos + 1] = \"G\";\n } else {\n A0_G0_result[pos + 1] = nextCh;\n A0_G1_result[pos + 1] = nextCh;\n A1_G0_result[pos + 1] = nextCh;\n A1_G1_result[pos + 1] = nextCh;\n }\n pos++;\n }\n }\n }\n return {\n A0_G0: A0_G0_result.join(\"\"),\n A0_G1: A0_G1_result.join(\"\"),\n A1_G0: A1_G0_result.join(\"\"),\n A1_G1: A1_G1_result.join(\"\")\n };\n }\n resolveAnchors(allowA, allowG) {\n if (!this.hasAnchor || !this._anchorCache) {\n return this.source;\n }\n if (allowA) {\n if (allowG) {\n return this._anchorCache.A1_G1;\n } else {\n return this._anchorCache.A1_G0;\n }\n } else {\n if (allowG) {\n return this._anchorCache.A0_G1;\n } else {\n return this._anchorCache.A0_G0;\n }\n }\n }\n};\nvar RegExpSourceList = class {\n constructor() {\n this._items = [];\n this._hasAnchors = false;\n this._cached = null;\n this._anchorCache = {\n A0_G0: null,\n A0_G1: null,\n A1_G0: null,\n A1_G1: null\n };\n }\n dispose() {\n this._disposeCaches();\n }\n _disposeCaches() {\n if (this._cached) {\n this._cached.dispose();\n this._cached = null;\n }\n if (this._anchorCache.A0_G0) {\n this._anchorCache.A0_G0.dispose();\n this._anchorCache.A0_G0 = null;\n }\n if (this._anchorCache.A0_G1) {\n this._anchorCache.A0_G1.dispose();\n this._anchorCache.A0_G1 = null;\n }\n if (this._anchorCache.A1_G0) {\n this._anchorCache.A1_G0.dispose();\n this._anchorCache.A1_G0 = null;\n }\n if (this._anchorCache.A1_G1) {\n this._anchorCache.A1_G1.dispose();\n this._anchorCache.A1_G1 = null;\n }\n }\n push(item) {\n this._items.push(item);\n this._hasAnchors = this._hasAnchors || item.hasAnchor;\n }\n unshift(item) {\n this._items.unshift(item);\n this._hasAnchors = this._hasAnchors || item.hasAnchor;\n }\n length() {\n return this._items.length;\n }\n setSource(index, newSource) {\n if (this._items[index].source !== newSource) {\n this._disposeCaches();\n this._items[index].setSource(newSource);\n }\n }\n compile(onigLib) {\n if (!this._cached) {\n let regExps = this._items.map((e) => e.source);\n this._cached = new CompiledRule(onigLib, regExps, this._items.map((e) => e.ruleId));\n }\n return this._cached;\n }\n compileAG(onigLib, allowA, allowG) {\n if (!this._hasAnchors) {\n return this.compile(onigLib);\n } else {\n if (allowA) {\n if (allowG) {\n if (!this._anchorCache.A1_G1) {\n this._anchorCache.A1_G1 = this._resolveAnchors(onigLib, allowA, allowG);\n }\n return this._anchorCache.A1_G1;\n } else {\n if (!this._anchorCache.A1_G0) {\n this._anchorCache.A1_G0 = this._resolveAnchors(onigLib, allowA, allowG);\n }\n return this._anchorCache.A1_G0;\n }\n } else {\n if (allowG) {\n if (!this._anchorCache.A0_G1) {\n this._anchorCache.A0_G1 = this._resolveAnchors(onigLib, allowA, allowG);\n }\n return this._anchorCache.A0_G1;\n } else {\n if (!this._anchorCache.A0_G0) {\n this._anchorCache.A0_G0 = this._resolveAnchors(onigLib, allowA, allowG);\n }\n return this._anchorCache.A0_G0;\n }\n }\n }\n }\n _resolveAnchors(onigLib, allowA, allowG) {\n let regExps = this._items.map((e) => e.resolveAnchors(allowA, allowG));\n return new CompiledRule(onigLib, regExps, this._items.map((e) => e.ruleId));\n }\n};\nvar CompiledRule = class {\n constructor(onigLib, regExps, rules) {\n this.regExps = regExps;\n this.rules = rules;\n this.scanner = onigLib.createOnigScanner(regExps);\n }\n dispose() {\n if (typeof this.scanner.dispose === \"function\") {\n this.scanner.dispose();\n }\n }\n toString() {\n const r = [];\n for (let i = 0, len = this.rules.length; i < len; i++) {\n r.push(\" - \" + this.rules[i] + \": \" + this.regExps[i]);\n }\n return r.join(\"\\n\");\n }\n findNextMatchSync(string, startPosition, options) {\n const result = this.scanner.findNextMatchSync(string, startPosition, options);\n if (!result) {\n return null;\n }\n return {\n ruleId: this.rules[result.index],\n captureIndices: result.captureIndices\n };\n }\n};\n\n// src/grammar/basicScopesAttributeProvider.ts\nvar BasicScopeAttributes = class {\n constructor(languageId, tokenType) {\n this.languageId = languageId;\n this.tokenType = tokenType;\n }\n};\nvar _BasicScopeAttributesProvider = class _BasicScopeAttributesProvider {\n constructor(initialLanguageId, embeddedLanguages) {\n this._getBasicScopeAttributes = new CachedFn((scopeName) => {\n const languageId = this._scopeToLanguage(scopeName);\n const standardTokenType = this._toStandardTokenType(scopeName);\n return new BasicScopeAttributes(languageId, standardTokenType);\n });\n this._defaultAttributes = new BasicScopeAttributes(initialLanguageId, 8 /* NotSet */);\n this._embeddedLanguagesMatcher = new ScopeMatcher(Object.entries(embeddedLanguages || {}));\n }\n getDefaultAttributes() {\n return this._defaultAttributes;\n }\n getBasicScopeAttributes(scopeName) {\n if (scopeName === null) {\n return _BasicScopeAttributesProvider._NULL_SCOPE_METADATA;\n }\n return this._getBasicScopeAttributes.get(scopeName);\n }\n /**\n * Given a produced TM scope, return the language that token describes or null if unknown.\n * e.g. source.html => html, source.css.embedded.html => css, punctuation.definition.tag.html => null\n */\n _scopeToLanguage(scope) {\n return this._embeddedLanguagesMatcher.match(scope) || 0;\n }\n _toStandardTokenType(scopeName) {\n const m = scopeName.match(_BasicScopeAttributesProvider.STANDARD_TOKEN_TYPE_REGEXP);\n if (!m) {\n return 8 /* NotSet */;\n }\n switch (m[1]) {\n case \"comment\":\n return 1 /* Comment */;\n case \"string\":\n return 2 /* String */;\n case \"regex\":\n return 3 /* RegEx */;\n case \"meta.embedded\":\n return 0 /* Other */;\n }\n throw new Error(\"Unexpected match for standard token type!\");\n }\n};\n_BasicScopeAttributesProvider._NULL_SCOPE_METADATA = new BasicScopeAttributes(0, 0);\n_BasicScopeAttributesProvider.STANDARD_TOKEN_TYPE_REGEXP = /\\b(comment|string|regex|meta\\.embedded)\\b/;\nvar BasicScopeAttributesProvider = _BasicScopeAttributesProvider;\nvar ScopeMatcher = class {\n constructor(values) {\n if (values.length === 0) {\n this.values = null;\n this.scopesRegExp = null;\n } else {\n this.values = new Map(values);\n const escapedScopes = values.map(\n ([scopeName, value]) => escapeRegExpCharacters(scopeName)\n );\n escapedScopes.sort();\n escapedScopes.reverse();\n this.scopesRegExp = new RegExp(\n `^((${escapedScopes.join(\")|(\")}))($|\\\\.)`,\n \"\"\n );\n }\n }\n match(scope) {\n if (!this.scopesRegExp) {\n return void 0;\n }\n const m = scope.match(this.scopesRegExp);\n if (!m) {\n return void 0;\n }\n return this.values.get(m[1]);\n }\n};\n\n// src/debug.ts\nvar DebugFlags = {\n InDebugMode: typeof process !== \"undefined\" && !!process.env[\"VSCODE_TEXTMATE_DEBUG\"]\n};\nvar UseOnigurumaFindOptions = false;\n\n// src/grammar/tokenizeString.ts\nvar TokenizeStringResult = class {\n constructor(stack, stoppedEarly) {\n this.stack = stack;\n this.stoppedEarly = stoppedEarly;\n }\n};\nfunction _tokenizeString(grammar, lineText, isFirstLine, linePos, stack, lineTokens, checkWhileConditions, timeLimit) {\n const lineLength = lineText.content.length;\n let STOP = false;\n let anchorPosition = -1;\n if (checkWhileConditions) {\n const whileCheckResult = _checkWhileConditions(\n grammar,\n lineText,\n isFirstLine,\n linePos,\n stack,\n lineTokens\n );\n stack = whileCheckResult.stack;\n linePos = whileCheckResult.linePos;\n isFirstLine = whileCheckResult.isFirstLine;\n anchorPosition = whileCheckResult.anchorPosition;\n }\n const startTime = Date.now();\n while (!STOP) {\n if (timeLimit !== 0) {\n const elapsedTime = Date.now() - startTime;\n if (elapsedTime > timeLimit) {\n return new TokenizeStringResult(stack, true);\n }\n }\n scanNext();\n }\n return new TokenizeStringResult(stack, false);\n function scanNext() {\n if (false) {\n console.log(\"\");\n console.log(\n `@@scanNext ${linePos}: |${lineText.content.substr(linePos).replace(/\\n$/, \"\\\\n\")}|`\n );\n }\n const r = matchRuleOrInjections(\n grammar,\n lineText,\n isFirstLine,\n linePos,\n stack,\n anchorPosition\n );\n if (!r) {\n lineTokens.produce(stack, lineLength);\n STOP = true;\n return;\n }\n const captureIndices = r.captureIndices;\n const matchedRuleId = r.matchedRuleId;\n const hasAdvanced = captureIndices && captureIndices.length > 0 ? captureIndices[0].end > linePos : false;\n if (matchedRuleId === endRuleId) {\n const poppedRule = stack.getRule(grammar);\n if (false) {\n console.log(\n \" popping \" + poppedRule.debugName + \" - \" + poppedRule.debugEndRegExp\n );\n }\n lineTokens.produce(stack, captureIndices[0].start);\n stack = stack.withContentNameScopesList(stack.nameScopesList);\n handleCaptures(\n grammar,\n lineText,\n isFirstLine,\n stack,\n lineTokens,\n poppedRule.endCaptures,\n captureIndices\n );\n lineTokens.produce(stack, captureIndices[0].end);\n const popped = stack;\n stack = stack.parent;\n anchorPosition = popped.getAnchorPos();\n if (!hasAdvanced && popped.getEnterPos() === linePos) {\n if (false) {\n console.error(\n \"[1] - Grammar is in an endless loop - Grammar pushed & popped a rule without advancing\"\n );\n }\n stack = popped;\n lineTokens.produce(stack, lineLength);\n STOP = true;\n return;\n }\n } else {\n const _rule = grammar.getRule(matchedRuleId);\n lineTokens.produce(stack, captureIndices[0].start);\n const beforePush = stack;\n const scopeName = _rule.getName(lineText.content, captureIndices);\n const nameScopesList = stack.contentNameScopesList.pushAttributed(\n scopeName,\n grammar\n );\n stack = stack.push(\n matchedRuleId,\n linePos,\n anchorPosition,\n captureIndices[0].end === lineLength,\n null,\n nameScopesList,\n nameScopesList\n );\n if (_rule instanceof BeginEndRule) {\n const pushedRule = _rule;\n if (false) {\n console.log(\n \" pushing \" + pushedRule.debugName + \" - \" + pushedRule.debugBeginRegExp\n );\n }\n handleCaptures(\n grammar,\n lineText,\n isFirstLine,\n stack,\n lineTokens,\n pushedRule.beginCaptures,\n captureIndices\n );\n lineTokens.produce(stack, captureIndices[0].end);\n anchorPosition = captureIndices[0].end;\n const contentName = pushedRule.getContentName(\n lineText.content,\n captureIndices\n );\n const contentNameScopesList = nameScopesList.pushAttributed(\n contentName,\n grammar\n );\n stack = stack.withContentNameScopesList(contentNameScopesList);\n if (pushedRule.endHasBackReferences) {\n stack = stack.withEndRule(\n pushedRule.getEndWithResolvedBackReferences(\n lineText.content,\n captureIndices\n )\n );\n }\n if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {\n if (false) {\n console.error(\n \"[2] - Grammar is in an endless loop - Grammar pushed the same rule without advancing\"\n );\n }\n stack = stack.pop();\n lineTokens.produce(stack, lineLength);\n STOP = true;\n return;\n }\n } else if (_rule instanceof BeginWhileRule) {\n const pushedRule = _rule;\n if (false) {\n console.log(\" pushing \" + pushedRule.debugName);\n }\n handleCaptures(\n grammar,\n lineText,\n isFirstLine,\n stack,\n lineTokens,\n pushedRule.beginCaptures,\n captureIndices\n );\n lineTokens.produce(stack, captureIndices[0].end);\n anchorPosition = captureIndices[0].end;\n const contentName = pushedRule.getContentName(\n lineText.content,\n captureIndices\n );\n const contentNameScopesList = nameScopesList.pushAttributed(\n contentName,\n grammar\n );\n stack = stack.withContentNameScopesList(contentNameScopesList);\n if (pushedRule.whileHasBackReferences) {\n stack = stack.withEndRule(\n pushedRule.getWhileWithResolvedBackReferences(\n lineText.content,\n captureIndices\n )\n );\n }\n if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {\n if (false) {\n console.error(\n \"[3] - Grammar is in an endless loop - Grammar pushed the same rule without advancing\"\n );\n }\n stack = stack.pop();\n lineTokens.produce(stack, lineLength);\n STOP = true;\n return;\n }\n } else {\n const matchingRule = _rule;\n if (false) {\n console.log(\n \" matched \" + matchingRule.debugName + \" - \" + matchingRule.debugMatchRegExp\n );\n }\n handleCaptures(\n grammar,\n lineText,\n isFirstLine,\n stack,\n lineTokens,\n matchingRule.captures,\n captureIndices\n );\n lineTokens.produce(stack, captureIndices[0].end);\n stack = stack.pop();\n if (!hasAdvanced) {\n if (false) {\n console.error(\n \"[4] - Grammar is in an endless loop - Grammar is not advancing, nor is it pushing/popping\"\n );\n }\n stack = stack.safePop();\n lineTokens.produce(stack, lineLength);\n STOP = true;\n return;\n }\n }\n }\n if (captureIndices[0].end > linePos) {\n linePos = captureIndices[0].end;\n isFirstLine = false;\n }\n }\n}\nfunction _checkWhileConditions(grammar, lineText, isFirstLine, linePos, stack, lineTokens) {\n let anchorPosition = stack.beginRuleCapturedEOL ? 0 : -1;\n const whileRules = [];\n for (let node = stack; node; node = node.pop()) {\n const nodeRule = node.getRule(grammar);\n if (nodeRule instanceof BeginWhileRule) {\n whileRules.push({\n rule: nodeRule,\n stack: node\n });\n }\n }\n for (let whileRule = whileRules.pop(); whileRule; whileRule = whileRules.pop()) {\n const { ruleScanner, findOptions } = prepareRuleWhileSearch(whileRule.rule, grammar, whileRule.stack.endRule, isFirstLine, linePos === anchorPosition);\n const r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);\n if (false) {\n console.log(\" scanning for while rule\");\n console.log(ruleScanner.toString());\n }\n if (r) {\n const matchedRuleId = r.ruleId;\n if (matchedRuleId !== whileRuleId) {\n stack = whileRule.stack.pop();\n break;\n }\n if (r.captureIndices && r.captureIndices.length) {\n lineTokens.produce(whileRule.stack, r.captureIndices[0].start);\n handleCaptures(grammar, lineText, isFirstLine, whileRule.stack, lineTokens, whileRule.rule.whileCaptures, r.captureIndices);\n lineTokens.produce(whileRule.stack, r.captureIndices[0].end);\n anchorPosition = r.captureIndices[0].end;\n if (r.captureIndices[0].end > linePos) {\n linePos = r.captureIndices[0].end;\n isFirstLine = false;\n }\n }\n } else {\n if (false) {\n console.log(\" popping \" + whileRule.rule.debugName + \" - \" + whileRule.rule.debugWhileRegExp);\n }\n stack = whileRule.stack.pop();\n break;\n }\n }\n return { stack, linePos, anchorPosition, isFirstLine };\n}\nfunction matchRuleOrInjections(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {\n const matchResult = matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition);\n const injections = grammar.getInjections();\n if (injections.length === 0) {\n return matchResult;\n }\n const injectionResult = matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition);\n if (!injectionResult) {\n return matchResult;\n }\n if (!matchResult) {\n return injectionResult;\n }\n const matchResultScore = matchResult.captureIndices[0].start;\n const injectionResultScore = injectionResult.captureIndices[0].start;\n if (injectionResultScore < matchResultScore || injectionResult.priorityMatch && injectionResultScore === matchResultScore) {\n return injectionResult;\n }\n return matchResult;\n}\nfunction matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {\n const rule = stack.getRule(grammar);\n const { ruleScanner, findOptions } = prepareRuleSearch(rule, grammar, stack.endRule, isFirstLine, linePos === anchorPosition);\n const r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);\n if (r) {\n return {\n captureIndices: r.captureIndices,\n matchedRuleId: r.ruleId\n };\n }\n return null;\n}\nfunction matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {\n let bestMatchRating = Number.MAX_VALUE;\n let bestMatchCaptureIndices = null;\n let bestMatchRuleId;\n let bestMatchResultPriority = 0;\n const scopes = stack.contentNameScopesList.getScopeNames();\n for (let i = 0, len = injections.length; i < len; i++) {\n const injection = injections[i];\n if (!injection.matcher(scopes)) {\n continue;\n }\n const rule = grammar.getRule(injection.ruleId);\n const { ruleScanner, findOptions } = prepareRuleSearch(rule, grammar, null, isFirstLine, linePos === anchorPosition);\n const matchResult = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);\n if (!matchResult) {\n continue;\n }\n if (false) {\n console.log(` matched injection: ${injection.debugSelector}`);\n console.log(ruleScanner.toString());\n }\n const matchRating = matchResult.captureIndices[0].start;\n if (matchRating >= bestMatchRating) {\n continue;\n }\n bestMatchRating = matchRating;\n bestMatchCaptureIndices = matchResult.captureIndices;\n bestMatchRuleId = matchResult.ruleId;\n bestMatchResultPriority = injection.priority;\n if (bestMatchRating === linePos) {\n break;\n }\n }\n if (bestMatchCaptureIndices) {\n return {\n priorityMatch: bestMatchResultPriority === -1,\n captureIndices: bestMatchCaptureIndices,\n matchedRuleId: bestMatchRuleId\n };\n }\n return null;\n}\nfunction prepareRuleSearch(rule, grammar, endRegexSource, allowA, allowG) {\n if (UseOnigurumaFindOptions) {\n const ruleScanner2 = rule.compile(grammar, endRegexSource);\n const findOptions = getFindOptions(allowA, allowG);\n return { ruleScanner: ruleScanner2, findOptions };\n }\n const ruleScanner = rule.compileAG(grammar, endRegexSource, allowA, allowG);\n return { ruleScanner, findOptions: 0 /* None */ };\n}\nfunction prepareRuleWhileSearch(rule, grammar, endRegexSource, allowA, allowG) {\n if (UseOnigurumaFindOptions) {\n const ruleScanner2 = rule.compileWhile(grammar, endRegexSource);\n const findOptions = getFindOptions(allowA, allowG);\n return { ruleScanner: ruleScanner2, findOptions };\n }\n const ruleScanner = rule.compileWhileAG(grammar, endRegexSource, allowA, allowG);\n return { ruleScanner, findOptions: 0 /* None */ };\n}\nfunction getFindOptions(allowA, allowG) {\n let options = 0 /* None */;\n if (!allowA) {\n options |= 1 /* NotBeginString */;\n }\n if (!allowG) {\n options |= 4 /* NotBeginPosition */;\n }\n return options;\n}\nfunction handleCaptures(grammar, lineText, isFirstLine, stack, lineTokens, captures, captureIndices) {\n if (captures.length === 0) {\n return;\n }\n const lineTextContent = lineText.content;\n const len = Math.min(captures.length, captureIndices.length);\n const localStack = [];\n const maxEnd = captureIndices[0].end;\n for (let i = 0; i < len; i++) {\n const captureRule = captures[i];\n if (captureRule === null) {\n continue;\n }\n const captureIndex = captureIndices[i];\n if (captureIndex.length === 0) {\n continue;\n }\n if (captureIndex.start > maxEnd) {\n break;\n }\n while (localStack.length > 0 && localStack[localStack.length - 1].endPos <= captureIndex.start) {\n lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);\n localStack.pop();\n }\n if (localStack.length > 0) {\n lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, captureIndex.start);\n } else {\n lineTokens.produce(stack, captureIndex.start);\n }\n if (captureRule.retokenizeCapturedWithRuleId) {\n const scopeName = captureRule.getName(lineTextContent, captureIndices);\n const nameScopesList = stack.contentNameScopesList.pushAttributed(scopeName, grammar);\n const contentName = captureRule.getContentName(lineTextContent, captureIndices);\n const contentNameScopesList = nameScopesList.pushAttributed(contentName, grammar);\n const stackClone = stack.push(captureRule.retokenizeCapturedWithRuleId, captureIndex.start, -1, false, null, nameScopesList, contentNameScopesList);\n const onigSubStr = grammar.createOnigString(lineTextContent.substring(0, captureIndex.end));\n _tokenizeString(\n grammar,\n onigSubStr,\n isFirstLine && captureIndex.start === 0,\n captureIndex.start,\n stackClone,\n lineTokens,\n false,\n /* no time limit */\n 0\n );\n disposeOnigString(onigSubStr);\n continue;\n }\n const captureRuleScopeName = captureRule.getName(lineTextContent, captureIndices);\n if (captureRuleScopeName !== null) {\n const base = localStack.length > 0 ? localStack[localStack.length - 1].scopes : stack.contentNameScopesList;\n const captureRuleScopesList = base.pushAttributed(captureRuleScopeName, grammar);\n localStack.push(new LocalStackElement(captureRuleScopesList, captureIndex.end));\n }\n }\n while (localStack.length > 0) {\n lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);\n localStack.pop();\n }\n}\nvar LocalStackElement = class {\n constructor(scopes, endPos) {\n this.scopes = scopes;\n this.endPos = endPos;\n }\n};\n\n// src/grammar/grammar.ts\nfunction createGrammar(scopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, onigLib) {\n return new Grammar(\n scopeName,\n grammar,\n initialLanguage,\n embeddedLanguages,\n tokenTypes,\n balancedBracketSelectors,\n grammarRepository,\n onigLib\n );\n}\nfunction collectInjections(result, selector, rule, ruleFactoryHelper, grammar) {\n const matchers = createMatchers(selector, nameMatcher);\n const ruleId = RuleFactory.getCompiledRuleId(rule, ruleFactoryHelper, grammar.repository);\n for (const matcher of matchers) {\n result.push({\n debugSelector: selector,\n matcher: matcher.matcher,\n ruleId,\n grammar,\n priority: matcher.priority\n });\n }\n}\nfunction nameMatcher(identifers, scopes) {\n if (scopes.length < identifers.length) {\n return false;\n }\n let lastIndex = 0;\n return identifers.every((identifier) => {\n for (let i = lastIndex; i < scopes.length; i++) {\n if (scopesAreMatching(scopes[i], identifier)) {\n lastIndex = i + 1;\n return true;\n }\n }\n return false;\n });\n}\nfunction scopesAreMatching(thisScopeName, scopeName) {\n if (!thisScopeName) {\n return false;\n }\n if (thisScopeName === scopeName) {\n return true;\n }\n const len = scopeName.length;\n return thisScopeName.length > len && thisScopeName.substr(0, len) === scopeName && thisScopeName[len] === \".\";\n}\nvar Grammar = class {\n constructor(_rootScopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, _onigLib) {\n this._rootScopeName = _rootScopeName;\n this.balancedBracketSelectors = balancedBracketSelectors;\n this._onigLib = _onigLib;\n this._basicScopeAttributesProvider = new BasicScopeAttributesProvider(\n initialLanguage,\n embeddedLanguages\n );\n this._rootId = -1;\n this._lastRuleId = 0;\n this._ruleId2desc = [null];\n this._includedGrammars = {};\n this._grammarRepository = grammarRepository;\n this._grammar = initGrammar(grammar, null);\n this._injections = null;\n this._tokenTypeMatchers = [];\n if (tokenTypes) {\n for (const selector of Object.keys(tokenTypes)) {\n const matchers = createMatchers(selector, nameMatcher);\n for (const matcher of matchers) {\n this._tokenTypeMatchers.push({\n matcher: matcher.matcher,\n type: tokenTypes[selector]\n });\n }\n }\n }\n }\n get themeProvider() {\n return this._grammarRepository;\n }\n dispose() {\n for (const rule of this._ruleId2desc) {\n if (rule) {\n rule.dispose();\n }\n }\n }\n createOnigScanner(sources) {\n return this._onigLib.createOnigScanner(sources);\n }\n createOnigString(sources) {\n return this._onigLib.createOnigString(sources);\n }\n getMetadataForScope(scope) {\n return this._basicScopeAttributesProvider.getBasicScopeAttributes(scope);\n }\n _collectInjections() {\n const grammarRepository = {\n lookup: (scopeName2) => {\n if (scopeName2 === this._rootScopeName) {\n return this._grammar;\n }\n return this.getExternalGrammar(scopeName2);\n },\n injections: (scopeName2) => {\n return this._grammarRepository.injections(scopeName2);\n }\n };\n const result = [];\n const scopeName = this._rootScopeName;\n const grammar = grammarRepository.lookup(scopeName);\n if (grammar) {\n const rawInjections = grammar.injections;\n if (rawInjections) {\n for (let expression in rawInjections) {\n collectInjections(\n result,\n expression,\n rawInjections[expression],\n this,\n grammar\n );\n }\n }\n const injectionScopeNames = this._grammarRepository.injections(scopeName);\n if (injectionScopeNames) {\n injectionScopeNames.forEach((injectionScopeName) => {\n const injectionGrammar = this.getExternalGrammar(injectionScopeName);\n if (injectionGrammar) {\n const selector = injectionGrammar.injectionSelector;\n if (selector) {\n collectInjections(\n result,\n selector,\n injectionGrammar,\n this,\n injectionGrammar\n );\n }\n }\n });\n }\n }\n result.sort((i1, i2) => i1.priority - i2.priority);\n return result;\n }\n getInjections() {\n if (this._injections === null) {\n this._injections = this._collectInjections();\n }\n return this._injections;\n }\n registerRule(factory) {\n const id = ++this._lastRuleId;\n const result = factory(ruleIdFromNumber(id));\n this._ruleId2desc[id] = result;\n return result;\n }\n getRule(ruleId) {\n return this._ruleId2desc[ruleIdToNumber(ruleId)];\n }\n getExternalGrammar(scopeName, repository) {\n if (this._includedGrammars[scopeName]) {\n return this._includedGrammars[scopeName];\n } else if (this._grammarRepository) {\n const rawIncludedGrammar = this._grammarRepository.lookup(scopeName);\n if (rawIncludedGrammar) {\n this._includedGrammars[scopeName] = initGrammar(\n rawIncludedGrammar,\n repository && repository.$base\n );\n return this._includedGrammars[scopeName];\n }\n }\n return void 0;\n }\n tokenizeLine(lineText, prevState, timeLimit = 0) {\n const r = this._tokenize(lineText, prevState, false, timeLimit);\n return {\n tokens: r.lineTokens.getResult(r.ruleStack, r.lineLength),\n ruleStack: r.ruleStack,\n stoppedEarly: r.stoppedEarly\n };\n }\n tokenizeLine2(lineText, prevState, timeLimit = 0) {\n const r = this._tokenize(lineText, prevState, true, timeLimit);\n return {\n tokens: r.lineTokens.getBinaryResult(r.ruleStack, r.lineLength),\n ruleStack: r.ruleStack,\n stoppedEarly: r.stoppedEarly\n };\n }\n _tokenize(lineText, prevState, emitBinaryTokens, timeLimit) {\n if (this._rootId === -1) {\n this._rootId = RuleFactory.getCompiledRuleId(\n this._grammar.repository.$self,\n this,\n this._grammar.repository\n );\n this.getInjections();\n }\n let isFirstLine;\n if (!prevState || prevState === StateStackImpl.NULL) {\n isFirstLine = true;\n const rawDefaultMetadata = this._basicScopeAttributesProvider.getDefaultAttributes();\n const defaultStyle = this.themeProvider.getDefaults();\n const defaultMetadata = EncodedTokenMetadata.set(\n 0,\n rawDefaultMetadata.languageId,\n rawDefaultMetadata.tokenType,\n null,\n defaultStyle.fontStyle,\n defaultStyle.foregroundId,\n defaultStyle.backgroundId\n );\n const rootScopeName = this.getRule(this._rootId).getName(\n null,\n null\n );\n let scopeList;\n if (rootScopeName) {\n scopeList = AttributedScopeStack.createRootAndLookUpScopeName(\n rootScopeName,\n defaultMetadata,\n this\n );\n } else {\n scopeList = AttributedScopeStack.createRoot(\n \"unknown\",\n defaultMetadata\n );\n }\n prevState = new StateStackImpl(\n null,\n this._rootId,\n -1,\n -1,\n false,\n null,\n scopeList,\n scopeList\n );\n } else {\n isFirstLine = false;\n prevState.reset();\n }\n lineText = lineText + \"\\n\";\n const onigLineText = this.createOnigString(lineText);\n const lineLength = onigLineText.content.length;\n const lineTokens = new LineTokens(\n emitBinaryTokens,\n lineText,\n this._tokenTypeMatchers,\n this.balancedBracketSelectors\n );\n const r = _tokenizeString(\n this,\n onigLineText,\n isFirstLine,\n 0,\n prevState,\n lineTokens,\n true,\n timeLimit\n );\n disposeOnigString(onigLineText);\n return {\n lineLength,\n lineTokens,\n ruleStack: r.stack,\n stoppedEarly: r.stoppedEarly\n };\n }\n};\nfunction initGrammar(grammar, base) {\n grammar = clone(grammar);\n grammar.repository = grammar.repository || {};\n grammar.repository.$self = {\n $vscodeTextmateLocation: grammar.$vscodeTextmateLocation,\n patterns: grammar.patterns,\n name: grammar.scopeName\n };\n grammar.repository.$base = base || grammar.repository.$self;\n return grammar;\n}\nvar AttributedScopeStack = class _AttributedScopeStack {\n /**\n * Invariant:\n * ```\n * if (parent && !scopePath.extends(parent.scopePath)) {\n * \tthrow new Error();\n * }\n * ```\n */\n constructor(parent, scopePath, tokenAttributes) {\n this.parent = parent;\n this.scopePath = scopePath;\n this.tokenAttributes = tokenAttributes;\n }\n static fromExtension(namesScopeList, contentNameScopesList) {\n let current = namesScopeList;\n let scopeNames = namesScopeList?.scopePath ?? null;\n for (const frame of contentNameScopesList) {\n scopeNames = ScopeStack.push(scopeNames, frame.scopeNames);\n current = new _AttributedScopeStack(current, scopeNames, frame.encodedTokenAttributes);\n }\n return current;\n }\n static createRoot(scopeName, tokenAttributes) {\n return new _AttributedScopeStack(null, new ScopeStack(null, scopeName), tokenAttributes);\n }\n static createRootAndLookUpScopeName(scopeName, tokenAttributes, grammar) {\n const rawRootMetadata = grammar.getMetadataForScope(scopeName);\n const scopePath = new ScopeStack(null, scopeName);\n const rootStyle = grammar.themeProvider.themeMatch(scopePath);\n const resolvedTokenAttributes = _AttributedScopeStack.mergeAttributes(\n tokenAttributes,\n rawRootMetadata,\n rootStyle\n );\n return new _AttributedScopeStack(null, scopePath, resolvedTokenAttributes);\n }\n get scopeName() {\n return this.scopePath.scopeName;\n }\n toString() {\n return this.getScopeNames().join(\" \");\n }\n equals(other) {\n return _AttributedScopeStack.equals(this, other);\n }\n static equals(a, b) {\n do {\n if (a === b) {\n return true;\n }\n if (!a && !b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n if (a.scopeName !== b.scopeName || a.tokenAttributes !== b.tokenAttributes) {\n return false;\n }\n a = a.parent;\n b = b.parent;\n } while (true);\n }\n static mergeAttributes(existingTokenAttributes, basicScopeAttributes, styleAttributes) {\n let fontStyle = -1 /* NotSet */;\n let foreground = 0;\n let background = 0;\n if (styleAttributes !== null) {\n fontStyle = styleAttributes.fontStyle;\n foreground = styleAttributes.foregroundId;\n background = styleAttributes.backgroundId;\n }\n return EncodedTokenMetadata.set(\n existingTokenAttributes,\n basicScopeAttributes.languageId,\n basicScopeAttributes.tokenType,\n null,\n fontStyle,\n foreground,\n background\n );\n }\n pushAttributed(scopePath, grammar) {\n if (scopePath === null) {\n return this;\n }\n if (scopePath.indexOf(\" \") === -1) {\n return _AttributedScopeStack._pushAttributed(this, scopePath, grammar);\n }\n const scopes = scopePath.split(/ /g);\n let result = this;\n for (const scope of scopes) {\n result = _AttributedScopeStack._pushAttributed(result, scope, grammar);\n }\n return result;\n }\n static _pushAttributed(target, scopeName, grammar) {\n const rawMetadata = grammar.getMetadataForScope(scopeName);\n const newPath = target.scopePath.push(scopeName);\n const scopeThemeMatchResult = grammar.themeProvider.themeMatch(newPath);\n const metadata = _AttributedScopeStack.mergeAttributes(\n target.tokenAttributes,\n rawMetadata,\n scopeThemeMatchResult\n );\n return new _AttributedScopeStack(target, newPath, metadata);\n }\n getScopeNames() {\n return this.scopePath.getSegments();\n }\n getExtensionIfDefined(base) {\n const result = [];\n let self = this;\n while (self && self !== base) {\n result.push({\n encodedTokenAttributes: self.tokenAttributes,\n scopeNames: self.scopePath.getExtensionIfDefined(self.parent?.scopePath ?? null)\n });\n self = self.parent;\n }\n return self === base ? result.reverse() : void 0;\n }\n};\nvar _StateStackImpl = class _StateStackImpl {\n /**\n * Invariant:\n * ```\n * if (contentNameScopesList !== nameScopesList && contentNameScopesList?.parent !== nameScopesList) {\n * \tthrow new Error();\n * }\n * if (this.parent && !nameScopesList.extends(this.parent.contentNameScopesList)) {\n * \tthrow new Error();\n * }\n * ```\n */\n constructor(parent, ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {\n this.parent = parent;\n this.ruleId = ruleId;\n this.beginRuleCapturedEOL = beginRuleCapturedEOL;\n this.endRule = endRule;\n this.nameScopesList = nameScopesList;\n this.contentNameScopesList = contentNameScopesList;\n this._stackElementBrand = void 0;\n this.depth = this.parent ? this.parent.depth + 1 : 1;\n this._enterPos = enterPos;\n this._anchorPos = anchorPos;\n }\n equals(other) {\n if (other === null) {\n return false;\n }\n return _StateStackImpl._equals(this, other);\n }\n static _equals(a, b) {\n if (a === b) {\n return true;\n }\n if (!this._structuralEquals(a, b)) {\n return false;\n }\n return AttributedScopeStack.equals(a.contentNameScopesList, b.contentNameScopesList);\n }\n /**\n * A structural equals check. Does not take into account `scopes`.\n */\n static _structuralEquals(a, b) {\n do {\n if (a === b) {\n return true;\n }\n if (!a && !b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n if (a.depth !== b.depth || a.ruleId !== b.ruleId || a.endRule !== b.endRule) {\n return false;\n }\n a = a.parent;\n b = b.parent;\n } while (true);\n }\n clone() {\n return this;\n }\n static _reset(el) {\n while (el) {\n el._enterPos = -1;\n el._anchorPos = -1;\n el = el.parent;\n }\n }\n reset() {\n _StateStackImpl._reset(this);\n }\n pop() {\n return this.parent;\n }\n safePop() {\n if (this.parent) {\n return this.parent;\n }\n return this;\n }\n push(ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {\n return new _StateStackImpl(\n this,\n ruleId,\n enterPos,\n anchorPos,\n beginRuleCapturedEOL,\n endRule,\n nameScopesList,\n contentNameScopesList\n );\n }\n getEnterPos() {\n return this._enterPos;\n }\n getAnchorPos() {\n return this._anchorPos;\n }\n getRule(grammar) {\n return grammar.getRule(this.ruleId);\n }\n toString() {\n const r = [];\n this._writeString(r, 0);\n return \"[\" + r.join(\",\") + \"]\";\n }\n _writeString(res, outIndex) {\n if (this.parent) {\n outIndex = this.parent._writeString(res, outIndex);\n }\n res[outIndex++] = `(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`;\n return outIndex;\n }\n withContentNameScopesList(contentNameScopeStack) {\n if (this.contentNameScopesList === contentNameScopeStack) {\n return this;\n }\n return this.parent.push(\n this.ruleId,\n this._enterPos,\n this._anchorPos,\n this.beginRuleCapturedEOL,\n this.endRule,\n this.nameScopesList,\n contentNameScopeStack\n );\n }\n withEndRule(endRule) {\n if (this.endRule === endRule) {\n return this;\n }\n return new _StateStackImpl(\n this.parent,\n this.ruleId,\n this._enterPos,\n this._anchorPos,\n this.beginRuleCapturedEOL,\n endRule,\n this.nameScopesList,\n this.contentNameScopesList\n );\n }\n // Used to warn of endless loops\n hasSameRuleAs(other) {\n let el = this;\n while (el && el._enterPos === other._enterPos) {\n if (el.ruleId === other.ruleId) {\n return true;\n }\n el = el.parent;\n }\n return false;\n }\n toStateStackFrame() {\n return {\n ruleId: ruleIdToNumber(this.ruleId),\n beginRuleCapturedEOL: this.beginRuleCapturedEOL,\n endRule: this.endRule,\n nameScopesList: this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList ?? null) ?? [],\n contentNameScopesList: this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList) ?? []\n };\n }\n static pushFrame(self, frame) {\n const namesScopeList = AttributedScopeStack.fromExtension(self?.nameScopesList ?? null, frame.nameScopesList);\n return new _StateStackImpl(\n self,\n ruleIdFromNumber(frame.ruleId),\n frame.enterPos ?? -1,\n frame.anchorPos ?? -1,\n frame.beginRuleCapturedEOL,\n frame.endRule,\n namesScopeList,\n AttributedScopeStack.fromExtension(namesScopeList, frame.contentNameScopesList)\n );\n }\n};\n// TODO remove me\n_StateStackImpl.NULL = new _StateStackImpl(\n null,\n 0,\n 0,\n 0,\n false,\n null,\n null,\n null\n);\nvar StateStackImpl = _StateStackImpl;\nvar BalancedBracketSelectors = class {\n constructor(balancedBracketScopes, unbalancedBracketScopes) {\n this.allowAny = false;\n this.balancedBracketScopes = balancedBracketScopes.flatMap(\n (selector) => {\n if (selector === \"*\") {\n this.allowAny = true;\n return [];\n }\n return createMatchers(selector, nameMatcher).map((m) => m.matcher);\n }\n );\n this.unbalancedBracketScopes = unbalancedBracketScopes.flatMap(\n (selector) => createMatchers(selector, nameMatcher).map((m) => m.matcher)\n );\n }\n get matchesAlways() {\n return this.allowAny && this.unbalancedBracketScopes.length === 0;\n }\n get matchesNever() {\n return this.balancedBracketScopes.length === 0 && !this.allowAny;\n }\n match(scopes) {\n for (const excluder of this.unbalancedBracketScopes) {\n if (excluder(scopes)) {\n return false;\n }\n }\n for (const includer of this.balancedBracketScopes) {\n if (includer(scopes)) {\n return true;\n }\n }\n return this.allowAny;\n }\n};\nvar LineTokens = class {\n constructor(emitBinaryTokens, lineText, tokenTypeOverrides, balancedBracketSelectors) {\n this.balancedBracketSelectors = balancedBracketSelectors;\n this._emitBinaryTokens = emitBinaryTokens;\n this._tokenTypeOverrides = tokenTypeOverrides;\n if (false) {\n this._lineText = lineText;\n } else {\n this._lineText = null;\n }\n this._tokens = [];\n this._binaryTokens = [];\n this._lastTokenEndIndex = 0;\n }\n produce(stack, endIndex) {\n this.produceFromScopes(stack.contentNameScopesList, endIndex);\n }\n produceFromScopes(scopesList, endIndex) {\n if (this._lastTokenEndIndex >= endIndex) {\n return;\n }\n if (this._emitBinaryTokens) {\n let metadata = scopesList?.tokenAttributes ?? 0;\n let containsBalancedBrackets = false;\n if (this.balancedBracketSelectors?.matchesAlways) {\n containsBalancedBrackets = true;\n }\n if (this._tokenTypeOverrides.length > 0 || this.balancedBracketSelectors && !this.balancedBracketSelectors.matchesAlways && !this.balancedBracketSelectors.matchesNever) {\n const scopes2 = scopesList?.getScopeNames() ?? [];\n for (const tokenType of this._tokenTypeOverrides) {\n if (tokenType.matcher(scopes2)) {\n metadata = EncodedTokenMetadata.set(\n metadata,\n 0,\n toOptionalTokenType(tokenType.type),\n null,\n -1 /* NotSet */,\n 0,\n 0\n );\n }\n }\n if (this.balancedBracketSelectors) {\n containsBalancedBrackets = this.balancedBracketSelectors.match(scopes2);\n }\n }\n if (containsBalancedBrackets) {\n metadata = EncodedTokenMetadata.set(\n metadata,\n 0,\n 8 /* NotSet */,\n containsBalancedBrackets,\n -1 /* NotSet */,\n 0,\n 0\n );\n }\n if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 1] === metadata) {\n this._lastTokenEndIndex = endIndex;\n return;\n }\n this._binaryTokens.push(this._lastTokenEndIndex);\n this._binaryTokens.push(metadata);\n this._lastTokenEndIndex = endIndex;\n return;\n }\n const scopes = scopesList?.getScopeNames() ?? [];\n this._tokens.push({\n startIndex: this._lastTokenEndIndex,\n endIndex,\n // value: lineText.substring(lastTokenEndIndex, endIndex),\n scopes\n });\n this._lastTokenEndIndex = endIndex;\n }\n getResult(stack, lineLength) {\n if (this._tokens.length > 0 && this._tokens[this._tokens.length - 1].startIndex === lineLength - 1) {\n this._tokens.pop();\n }\n if (this._tokens.length === 0) {\n this._lastTokenEndIndex = -1;\n this.produce(stack, lineLength);\n this._tokens[this._tokens.length - 1].startIndex = 0;\n }\n return this._tokens;\n }\n getBinaryResult(stack, lineLength) {\n if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 2] === lineLength - 1) {\n this._binaryTokens.pop();\n this._binaryTokens.pop();\n }\n if (this._binaryTokens.length === 0) {\n this._lastTokenEndIndex = -1;\n this.produce(stack, lineLength);\n this._binaryTokens[this._binaryTokens.length - 2] = 0;\n }\n const result = new Uint32Array(this._binaryTokens.length);\n for (let i = 0, len = this._binaryTokens.length; i < len; i++) {\n result[i] = this._binaryTokens[i];\n }\n return result;\n }\n};\n\n// src/registry.ts\nvar SyncRegistry = class {\n constructor(theme, _onigLib) {\n this._onigLib = _onigLib;\n this._grammars = /* @__PURE__ */ new Map();\n this._rawGrammars = /* @__PURE__ */ new Map();\n this._injectionGrammars = /* @__PURE__ */ new Map();\n this._theme = theme;\n }\n dispose() {\n for (const grammar of this._grammars.values()) {\n grammar.dispose();\n }\n }\n setTheme(theme) {\n this._theme = theme;\n }\n getColorMap() {\n return this._theme.getColorMap();\n }\n /**\n * Add `grammar` to registry and return a list of referenced scope names\n */\n addGrammar(grammar, injectionScopeNames) {\n this._rawGrammars.set(grammar.scopeName, grammar);\n if (injectionScopeNames) {\n this._injectionGrammars.set(grammar.scopeName, injectionScopeNames);\n }\n }\n /**\n * Lookup a raw grammar.\n */\n lookup(scopeName) {\n return this._rawGrammars.get(scopeName);\n }\n /**\n * Returns the injections for the given grammar\n */\n injections(targetScope) {\n return this._injectionGrammars.get(targetScope);\n }\n /**\n * Get the default theme settings\n */\n getDefaults() {\n return this._theme.getDefaults();\n }\n /**\n * Match a scope in the theme.\n */\n themeMatch(scopePath) {\n return this._theme.match(scopePath);\n }\n /**\n * Lookup a grammar.\n */\n grammarForScopeName(scopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {\n if (!this._grammars.has(scopeName)) {\n let rawGrammar = this._rawGrammars.get(scopeName);\n if (!rawGrammar) {\n return null;\n }\n this._grammars.set(scopeName, createGrammar(\n scopeName,\n rawGrammar,\n initialLanguage,\n embeddedLanguages,\n tokenTypes,\n balancedBracketSelectors,\n this,\n this._onigLib\n ));\n }\n return this._grammars.get(scopeName);\n }\n};\n\n// src/index.ts\nvar Registry = class {\n constructor(options) {\n this._options = options;\n this._syncRegistry = new SyncRegistry(\n Theme.createFromRawTheme(options.theme, options.colorMap),\n options.onigLib\n );\n this._ensureGrammarCache = /* @__PURE__ */ new Map();\n }\n dispose() {\n this._syncRegistry.dispose();\n }\n /**\n * Change the theme. Once called, no previous `ruleStack` should be used anymore.\n */\n setTheme(theme, colorMap) {\n this._syncRegistry.setTheme(Theme.createFromRawTheme(theme, colorMap));\n }\n /**\n * Returns a lookup array for color ids.\n */\n getColorMap() {\n return this._syncRegistry.getColorMap();\n }\n /**\n * Load the grammar for `scopeName` and all referenced included grammars asynchronously.\n * Please do not use language id 0.\n */\n loadGrammarWithEmbeddedLanguages(initialScopeName, initialLanguage, embeddedLanguages) {\n return this.loadGrammarWithConfiguration(initialScopeName, initialLanguage, { embeddedLanguages });\n }\n /**\n * Load the grammar for `scopeName` and all referenced included grammars asynchronously.\n * Please do not use language id 0.\n */\n loadGrammarWithConfiguration(initialScopeName, initialLanguage, configuration) {\n return this._loadGrammar(\n initialScopeName,\n initialLanguage,\n configuration.embeddedLanguages,\n configuration.tokenTypes,\n new BalancedBracketSelectors(\n configuration.balancedBracketSelectors || [],\n configuration.unbalancedBracketSelectors || []\n )\n );\n }\n /**\n * Load the grammar for `scopeName` and all referenced included grammars asynchronously.\n */\n loadGrammar(initialScopeName) {\n return this._loadGrammar(initialScopeName, 0, null, null, null);\n }\n _loadGrammar(initialScopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {\n const dependencyProcessor = new ScopeDependencyProcessor(this._syncRegistry, initialScopeName);\n while (dependencyProcessor.Q.length > 0) {\n dependencyProcessor.Q.map((request) => this._loadSingleGrammar(request.scopeName));\n dependencyProcessor.processQueue();\n }\n return this._grammarForScopeName(\n initialScopeName,\n initialLanguage,\n embeddedLanguages,\n tokenTypes,\n balancedBracketSelectors\n );\n }\n _loadSingleGrammar(scopeName) {\n if (!this._ensureGrammarCache.has(scopeName)) {\n this._doLoadSingleGrammar(scopeName);\n this._ensureGrammarCache.set(scopeName, true);\n }\n }\n _doLoadSingleGrammar(scopeName) {\n const grammar = this._options.loadGrammar(scopeName);\n if (grammar) {\n const injections = typeof this._options.getInjections === \"function\" ? this._options.getInjections(scopeName) : void 0;\n this._syncRegistry.addGrammar(grammar, injections);\n }\n }\n /**\n * Adds a rawGrammar.\n */\n addGrammar(rawGrammar, injections = [], initialLanguage = 0, embeddedLanguages = null) {\n this._syncRegistry.addGrammar(rawGrammar, injections);\n return this._grammarForScopeName(rawGrammar.scopeName, initialLanguage, embeddedLanguages);\n }\n /**\n * Get the grammar for `scopeName`. The grammar must first be created via `loadGrammar` or `addGrammar`.\n */\n _grammarForScopeName(scopeName, initialLanguage = 0, embeddedLanguages = null, tokenTypes = null, balancedBracketSelectors = null) {\n return this._syncRegistry.grammarForScopeName(\n scopeName,\n initialLanguage,\n embeddedLanguages,\n tokenTypes,\n balancedBracketSelectors\n );\n }\n};\nvar INITIAL = StateStackImpl.NULL;\nexport {\n EncodedTokenMetadata,\n FindOption,\n FontStyle,\n INITIAL,\n Registry,\n Theme,\n disposeOnigString\n};\n","import {\n boolean,\n overloadedBoolean,\n booleanish,\n number,\n spaceSeparated,\n commaSeparated\n} from './util/types.js'\nimport {create} from './util/create.js'\nimport {caseInsensitiveTransform} from './util/case-insensitive-transform.js'\n\nexport const html = create({\n space: 'html',\n attributes: {\n acceptcharset: 'accept-charset',\n classname: 'class',\n htmlfor: 'for',\n httpequiv: 'http-equiv'\n },\n transform: caseInsensitiveTransform,\n mustUseProperty: ['checked', 'multiple', 'muted', 'selected'],\n properties: {\n // Standard Properties.\n abbr: null,\n accept: commaSeparated,\n acceptCharset: spaceSeparated,\n accessKey: spaceSeparated,\n action: null,\n allow: null,\n allowFullScreen: boolean,\n allowPaymentRequest: boolean,\n allowUserMedia: boolean,\n alt: null,\n as: null,\n async: boolean,\n autoCapitalize: null,\n autoComplete: spaceSeparated,\n autoFocus: boolean,\n autoPlay: boolean,\n blocking: spaceSeparated,\n capture: null,\n charSet: null,\n checked: boolean,\n cite: null,\n className: spaceSeparated,\n cols: number,\n colSpan: null,\n content: null,\n contentEditable: booleanish,\n controls: boolean,\n controlsList: spaceSeparated,\n coords: number | commaSeparated,\n crossOrigin: null,\n data: null,\n dateTime: null,\n decoding: null,\n default: boolean,\n defer: boolean,\n dir: null,\n dirName: null,\n disabled: boolean,\n download: overloadedBoolean,\n draggable: booleanish,\n encType: null,\n enterKeyHint: null,\n fetchPriority: null,\n form: null,\n formAction: null,\n formEncType: null,\n formMethod: null,\n formNoValidate: boolean,\n formTarget: null,\n headers: spaceSeparated,\n height: number,\n hidden: boolean,\n high: number,\n href: null,\n hrefLang: null,\n htmlFor: spaceSeparated,\n httpEquiv: spaceSeparated,\n id: null,\n imageSizes: null,\n imageSrcSet: null,\n inert: boolean,\n inputMode: null,\n integrity: null,\n is: null,\n isMap: boolean,\n itemId: null,\n itemProp: spaceSeparated,\n itemRef: spaceSeparated,\n itemScope: boolean,\n itemType: spaceSeparated,\n kind: null,\n label: null,\n lang: null,\n language: null,\n list: null,\n loading: null,\n loop: boolean,\n low: number,\n manifest: null,\n max: null,\n maxLength: number,\n media: null,\n method: null,\n min: null,\n minLength: number,\n multiple: boolean,\n muted: boolean,\n name: null,\n nonce: null,\n noModule: boolean,\n noValidate: boolean,\n onAbort: null,\n onAfterPrint: null,\n onAuxClick: null,\n onBeforeMatch: null,\n onBeforePrint: null,\n onBeforeToggle: null,\n onBeforeUnload: null,\n onBlur: null,\n onCancel: null,\n onCanPlay: null,\n onCanPlayThrough: null,\n onChange: null,\n onClick: null,\n onClose: null,\n onContextLost: null,\n onContextMenu: null,\n onContextRestored: null,\n onCopy: null,\n onCueChange: null,\n onCut: null,\n onDblClick: null,\n onDrag: null,\n onDragEnd: null,\n onDragEnter: null,\n onDragExit: null,\n onDragLeave: null,\n onDragOver: null,\n onDragStart: null,\n onDrop: null,\n onDurationChange: null,\n onEmptied: null,\n onEnded: null,\n onError: null,\n onFocus: null,\n onFormData: null,\n onHashChange: null,\n onInput: null,\n onInvalid: null,\n onKeyDown: null,\n onKeyPress: null,\n onKeyUp: null,\n onLanguageChange: null,\n onLoad: null,\n onLoadedData: null,\n onLoadedMetadata: null,\n onLoadEnd: null,\n onLoadStart: null,\n onMessage: null,\n onMessageError: null,\n onMouseDown: null,\n onMouseEnter: null,\n onMouseLeave: null,\n onMouseMove: null,\n onMouseOut: null,\n onMouseOver: null,\n onMouseUp: null,\n onOffline: null,\n onOnline: null,\n onPageHide: null,\n onPageShow: null,\n onPaste: null,\n onPause: null,\n onPlay: null,\n onPlaying: null,\n onPopState: null,\n onProgress: null,\n onRateChange: null,\n onRejectionHandled: null,\n onReset: null,\n onResize: null,\n onScroll: null,\n onScrollEnd: null,\n onSecurityPolicyViolation: null,\n onSeeked: null,\n onSeeking: null,\n onSelect: null,\n onSlotChange: null,\n onStalled: null,\n onStorage: null,\n onSubmit: null,\n onSuspend: null,\n onTimeUpdate: null,\n onToggle: null,\n onUnhandledRejection: null,\n onUnload: null,\n onVolumeChange: null,\n onWaiting: null,\n onWheel: null,\n open: boolean,\n optimum: number,\n pattern: null,\n ping: spaceSeparated,\n placeholder: null,\n playsInline: boolean,\n popover: null,\n popoverTarget: null,\n popoverTargetAction: null,\n poster: null,\n preload: null,\n readOnly: boolean,\n referrerPolicy: null,\n rel: spaceSeparated,\n required: boolean,\n reversed: boolean,\n rows: number,\n rowSpan: number,\n sandbox: spaceSeparated,\n scope: null,\n scoped: boolean,\n seamless: boolean,\n selected: boolean,\n shadowRootClonable: boolean,\n shadowRootDelegatesFocus: boolean,\n shadowRootMode: null,\n shape: null,\n size: number,\n sizes: null,\n slot: null,\n span: number,\n spellCheck: booleanish,\n src: null,\n srcDoc: null,\n srcLang: null,\n srcSet: null,\n start: number,\n step: null,\n style: null,\n tabIndex: number,\n target: null,\n title: null,\n translate: null,\n type: null,\n typeMustMatch: boolean,\n useMap: null,\n value: booleanish,\n width: number,\n wrap: null,\n writingSuggestions: null,\n\n // Legacy.\n // See: https://html.spec.whatwg.org/#other-elements,-attributes-and-apis\n align: null, // Several. Use CSS `text-align` instead,\n aLink: null, // `<body>`. Use CSS `a:active {color}` instead\n archive: spaceSeparated, // `<object>`. List of URIs to archives\n axis: null, // `<td>` and `<th>`. Use `scope` on `<th>`\n background: null, // `<body>`. Use CSS `background-image` instead\n bgColor: null, // `<body>` and table elements. Use CSS `background-color` instead\n border: number, // `<table>`. Use CSS `border-width` instead,\n borderColor: null, // `<table>`. Use CSS `border-color` instead,\n bottomMargin: number, // `<body>`\n cellPadding: null, // `<table>`\n cellSpacing: null, // `<table>`\n char: null, // Several table elements. When `align=char`, sets the character to align on\n charOff: null, // Several table elements. When `char`, offsets the alignment\n classId: null, // `<object>`\n clear: null, // `<br>`. Use CSS `clear` instead\n code: null, // `<object>`\n codeBase: null, // `<object>`\n codeType: null, // `<object>`\n color: null, // `<font>` and `<hr>`. Use CSS instead\n compact: boolean, // Lists. Use CSS to reduce space between items instead\n declare: boolean, // `<object>`\n event: null, // `<script>`\n face: null, // `<font>`. Use CSS instead\n frame: null, // `<table>`\n frameBorder: null, // `<iframe>`. Use CSS `border` instead\n hSpace: number, // `<img>` and `<object>`\n leftMargin: number, // `<body>`\n link: null, // `<body>`. Use CSS `a:link {color: *}` instead\n longDesc: null, // `<frame>`, `<iframe>`, and `<img>`. Use an `<a>`\n lowSrc: null, // `<img>`. Use a `<picture>`\n marginHeight: number, // `<body>`\n marginWidth: number, // `<body>`\n noResize: boolean, // `<frame>`\n noHref: boolean, // `<area>`. Use no href instead of an explicit `nohref`\n noShade: boolean, // `<hr>`. Use background-color and height instead of borders\n noWrap: boolean, // `<td>` and `<th>`\n object: null, // `<applet>`\n profile: null, // `<head>`\n prompt: null, // `<isindex>`\n rev: null, // `<link>`\n rightMargin: number, // `<body>`\n rules: null, // `<table>`\n scheme: null, // `<meta>`\n scrolling: booleanish, // `<frame>`. Use overflow in the child context\n standby: null, // `<object>`\n summary: null, // `<table>`\n text: null, // `<body>`. Use CSS `color` instead\n topMargin: number, // `<body>`\n valueType: null, // `<param>`\n version: null, // `<html>`. Use a doctype.\n vAlign: null, // Several. Use CSS `vertical-align` instead\n vLink: null, // `<body>`. Use CSS `a:visited {color}` instead\n vSpace: number, // `<img>` and `<object>`\n\n // Non-standard Properties.\n allowTransparency: null,\n autoCorrect: null,\n autoSave: null,\n disablePictureInPicture: boolean,\n disableRemotePlayback: boolean,\n prefix: null,\n property: null,\n results: number,\n security: null,\n unselectable: null\n }\n})\n","/**\n * @import {Element, Parents, Properties} from 'hast'\n * @import {State} from '../index.js'\n */\n\nimport {ccount} from 'ccount'\nimport {stringify as commas} from 'comma-separated-tokens'\nimport {find, svg} from 'property-information'\nimport {stringify as spaces} from 'space-separated-tokens'\nimport {stringifyEntities} from 'stringify-entities'\nimport {closing} from '../omission/closing.js'\nimport {opening} from '../omission/opening.js'\n\n/**\n * Maps of subsets.\n *\n * Each value is a matrix of tuples.\n * The value at `0` causes parse errors, the value at `1` is valid.\n * Of both, the value at `0` is unsafe, and the value at `1` is safe.\n *\n * @type {Record<'double' | 'name' | 'single' | 'unquoted', Array<[Array<string>, Array<string>]>>}\n */\nconst constants = {\n // See: <https://html.spec.whatwg.org/#attribute-name-state>.\n name: [\n ['\\t\\n\\f\\r &/=>'.split(''), '\\t\\n\\f\\r \"&\\'/=>`'.split('')],\n ['\\0\\t\\n\\f\\r \"&\\'/<=>'.split(''), '\\0\\t\\n\\f\\r \"&\\'/<=>`'.split('')]\n ],\n // See: <https://html.spec.whatwg.org/#attribute-value-(unquoted)-state>.\n unquoted: [\n ['\\t\\n\\f\\r &>'.split(''), '\\0\\t\\n\\f\\r \"&\\'<=>`'.split('')],\n ['\\0\\t\\n\\f\\r \"&\\'<=>`'.split(''), '\\0\\t\\n\\f\\r \"&\\'<=>`'.split('')]\n ],\n // See: <https://html.spec.whatwg.org/#attribute-value-(single-quoted)-state>.\n single: [\n [\"&'\".split(''), '\"&\\'`'.split('')],\n [\"\\0&'\".split(''), '\\0\"&\\'`'.split('')]\n ],\n // See: <https://html.spec.whatwg.org/#attribute-value-(double-quoted)-state>.\n double: [\n ['\"&'.split(''), '\"&\\'`'.split('')],\n ['\\0\"&'.split(''), '\\0\"&\\'`'.split('')]\n ]\n}\n\n/**\n * Serialize an element node.\n *\n * @param {Element} node\n * Node to handle.\n * @param {number | undefined} index\n * Index of `node` in `parent.\n * @param {Parents | undefined} parent\n * Parent of `node`.\n * @param {State} state\n * Info passed around about the current state.\n * @returns {string}\n * Serialized node.\n */\nexport function element(node, index, parent, state) {\n const schema = state.schema\n const omit = schema.space === 'svg' ? false : state.settings.omitOptionalTags\n let selfClosing =\n schema.space === 'svg'\n ? state.settings.closeEmptyElements\n : state.settings.voids.includes(node.tagName.toLowerCase())\n /** @type {Array<string>} */\n const parts = []\n /** @type {string} */\n let last\n\n if (schema.space === 'html' && node.tagName === 'svg') {\n state.schema = svg\n }\n\n const attributes = serializeAttributes(state, node.properties)\n\n const content = state.all(\n schema.space === 'html' && node.tagName === 'template' ? node.content : node\n )\n\n state.schema = schema\n\n // If the node is categorised as void, but it has children, remove the\n // categorisation.\n // This enables for example `menuitem`s, which are void in W3C HTML but not\n // void in WHATWG HTML, to be stringified properly.\n // Note: `menuitem` has since been removed from the HTML spec, and so is no\n // longer void.\n if (content) selfClosing = false\n\n if (attributes || !omit || !opening(node, index, parent)) {\n parts.push('<', node.tagName, attributes ? ' ' + attributes : '')\n\n if (\n selfClosing &&\n (schema.space === 'svg' || state.settings.closeSelfClosing)\n ) {\n last = attributes.charAt(attributes.length - 1)\n if (\n !state.settings.tightSelfClosing ||\n last === '/' ||\n (last && last !== '\"' && last !== \"'\")\n ) {\n parts.push(' ')\n }\n\n parts.push('/')\n }\n\n parts.push('>')\n }\n\n parts.push(content)\n\n if (!selfClosing && (!omit || !closing(node, index, parent))) {\n parts.push('</' + node.tagName + '>')\n }\n\n return parts.join('')\n}\n\n/**\n * @param {State} state\n * @param {Properties | null | undefined} properties\n * @returns {string}\n */\nfunction serializeAttributes(state, properties) {\n /** @type {Array<string>} */\n const values = []\n let index = -1\n /** @type {string} */\n let key\n\n if (properties) {\n for (key in properties) {\n if (properties[key] !== null && properties[key] !== undefined) {\n const value = serializeAttribute(state, key, properties[key])\n if (value) values.push(value)\n }\n }\n }\n\n while (++index < values.length) {\n const last = state.settings.tightAttributes\n ? values[index].charAt(values[index].length - 1)\n : undefined\n\n // In tight mode, don’t add a space after quoted attributes.\n if (index !== values.length - 1 && last !== '\"' && last !== \"'\") {\n values[index] += ' '\n }\n }\n\n return values.join('')\n}\n\n/**\n * @param {State} state\n * @param {string} key\n * @param {Properties[keyof Properties]} value\n * @returns {string}\n */\nfunction serializeAttribute(state, key, value) {\n const info = find(state.schema, key)\n const x =\n state.settings.allowParseErrors && state.schema.space === 'html' ? 0 : 1\n const y = state.settings.allowDangerousCharacters ? 0 : 1\n let quote = state.quote\n /** @type {string | undefined} */\n let result\n\n if (info.overloadedBoolean && (value === info.attribute || value === '')) {\n value = true\n } else if (\n info.boolean ||\n (info.overloadedBoolean && typeof value !== 'string')\n ) {\n value = Boolean(value)\n }\n\n if (\n value === null ||\n value === undefined ||\n value === false ||\n (typeof value === 'number' && Number.isNaN(value))\n ) {\n return ''\n }\n\n const name = stringifyEntities(\n info.attribute,\n Object.assign({}, state.settings.characterReferences, {\n // Always encode without parse errors in non-HTML.\n subset: constants.name[x][y]\n })\n )\n\n // No value.\n // There is currently only one boolean property in SVG: `[download]` on\n // `<a>`.\n // This property does not seem to work in browsers (Firefox, Safari, Chrome),\n // so I can’t test if dropping the value works.\n // But I assume that it should:\n //\n // ```html\n // <!doctype html>\n // <svg viewBox=\"0 0 100 100\">\n // <a href=https://example.com download>\n // <circle cx=50 cy=40 r=35 />\n // </a>\n // </svg>\n // ```\n //\n // See: <https://github.com/wooorm/property-information/blob/main/lib/svg.js>\n if (value === true) return name\n\n // `spaces` doesn’t accept a second argument, but it’s given here just to\n // keep the code cleaner.\n value = Array.isArray(value)\n ? (info.commaSeparated ? commas : spaces)(value, {\n padLeft: !state.settings.tightCommaSeparatedLists\n })\n : String(value)\n\n if (state.settings.collapseEmptyAttributes && !value) return name\n\n // Check unquoted value.\n if (state.settings.preferUnquoted) {\n result = stringifyEntities(\n value,\n Object.assign({}, state.settings.characterReferences, {\n attribute: true,\n subset: constants.unquoted[x][y]\n })\n )\n }\n\n // If we don’t want unquoted, or if `value` contains character references when\n // unquoted…\n if (result !== value) {\n // If the alternative is less common than `quote`, switch.\n if (\n state.settings.quoteSmart &&\n ccount(value, quote) > ccount(value, state.alternative)\n ) {\n quote = state.alternative\n }\n\n result =\n quote +\n stringifyEntities(\n value,\n Object.assign({}, state.settings.characterReferences, {\n // Always encode without parse errors in non-HTML.\n subset: (quote === \"'\" ? constants.single : constants.double)[x][y],\n attribute: true\n })\n ) +\n quote\n }\n\n // Don’t add a `=` for unquoted empties.\n return name + (result ? '=' + result : result)\n}\n","import {Pattern, pattern} from './pattern.js';\nimport {Context, forEachUnescaped, replaceUnescaped} from 'regex-utilities';\n\nexport const RegexContext = {\n DEFAULT: 'DEFAULT',\n CHAR_CLASS: 'CHAR_CLASS',\n ENCLOSED_P: 'ENCLOSED_P',\n ENCLOSED_U: 'ENCLOSED_U',\n GROUP_NAME: 'GROUP_NAME',\n INTERVAL_QUANTIFIER: 'INTERVAL_QUANTIFIER',\n INVALID_INCOMPLETE_TOKEN: 'INVALID_INCOMPLETE_TOKEN',\n};\n\nexport const CharClassContext = {\n DEFAULT: 'DEFAULT',\n ENCLOSED_P: 'ENCLOSED_P',\n ENCLOSED_Q: 'ENCLOSED_Q',\n ENCLOSED_U: 'ENCLOSED_U',\n INVALID_INCOMPLETE_TOKEN: 'INVALID_INCOMPLETE_TOKEN',\n RANGE: 'RANGE',\n};\n\nexport const enclosedTokenRegexContexts = new Set([\n RegexContext.ENCLOSED_P,\n RegexContext.ENCLOSED_U,\n]);\n\nexport const enclosedTokenCharClassContexts = new Set([\n CharClassContext.ENCLOSED_P,\n CharClassContext.ENCLOSED_Q,\n CharClassContext.ENCLOSED_U,\n]);\n\nexport const patternModsSupported = (() => {\n try {\n new RegExp('(?i:)');\n } catch (e) {\n return false;\n }\n return true;\n})();\n\nexport const flagVSupported = (() => {\n try {\n new RegExp('', 'v');\n } catch (e) {\n return false;\n }\n return true;\n})();\n\n// This marker was chosen because it's impossible to match (so its extemely unlikely to be used in\n// a user-provided regex); it's not at risk of being optimized away, transformed, or flagged as an\n// error by a plugin; and it ends with an unquantifiable token\nexport const emulationGroupMarker = '$E$';\nexport const doublePunctuatorChars = '&!#$%*+,.:;<=>?@^`~';\nexport const namedCapturingDelim = String.raw`\\(\\?<(?![=!])(?<captureName>[^>]+)>`;\nexport const capturingDelim = String.raw`\\((?!\\?)(?!(?<=\\(\\?\\()DEFINE\\))|${namedCapturingDelim}`;\nexport const noncapturingDelim = String.raw`\\(\\?(?:[:=!>A-Za-z\\-]|<[=!]|\\(DEFINE\\))`;\n\n/**\n@param {string} expression\n@param {number} precedingCaptures\n@returns {string}\n*/\nexport function adjustNumberedBackrefs(expression, precedingCaptures) {\n return replaceUnescaped(\n expression,\n String.raw`\\\\(?<num>[1-9]\\d*)`,\n ({groups: {num}}) => `\\\\${+num + precedingCaptures}`,\n Context.DEFAULT\n );\n}\n\n// Properties of strings as of ES2024\nconst stringPropertyNames = [\n 'Basic_Emoji',\n 'Emoji_Keycap_Sequence',\n 'RGI_Emoji_Modifier_Sequence',\n 'RGI_Emoji_Flag_Sequence',\n 'RGI_Emoji_Tag_Sequence',\n 'RGI_Emoji_ZWJ_Sequence',\n 'RGI_Emoji',\n].join('|');\nconst charClassUnionToken = new RegExp(String.raw`\n\\\\(?: c[A-Za-z]\n | p\\{(?<pStrProp>${stringPropertyNames})\\}\n | [pP]\\{[^\\}]+\\}\n | (?<qStrProp>q)\n | u(?:[A-Fa-f\\d]{4}|\\{[A-Fa-f\\d]+\\})\n | x[A-Fa-f\\d]{2}\n | .\n)\n| --\n| &&\n| .\n`.replace(/\\s+/g, ''), 'gsu');\n\n// Assumes flag v and doesn't worry about syntax errors that are caught by it\nexport function containsCharClassUnion(charClassPattern) {\n // Return `true` if it contains:\n // - `\\p` (lowercase only) and the name is a property of strings (case sensitive).\n // - `\\q`.\n // - Two single-char-matching tokens in sequence.\n // - One single-char-matching token followed immediately by unescaped `[`.\n // - One single-char-matching token preceded immediately by unescaped `]`.\n // Else, `false`.\n // Ranges with `-` create a single token.\n // Subtraction and intersection with `--` and `&&` create a single token.\n // Supports any number of nested classes\n let hasFirst = false;\n let lastM;\n for (const {0: m, groups} of charClassPattern.matchAll(charClassUnionToken)) {\n if (groups.pStrProp || groups.qStrProp) {\n return true;\n }\n if (m === '[' && hasFirst) {\n return true;\n }\n if (['-', '--', '&&'].includes(m)) {\n hasFirst = false;\n } else if (m !== '[' && m !== ']') {\n if (hasFirst || lastM === ']') {\n return true;\n }\n hasFirst = true;\n }\n lastM = m;\n }\n return false;\n}\n\n/**\n@param {string} expression\n@returns {number}\n*/\nexport function countCaptures(expression) {\n let num = 0;\n forEachUnescaped(expression, capturingDelim, () => num++, Context.DEFAULT);\n return num;\n}\n\n/**\nEscape special characters for the given context, assuming flag v.\n@param {string} str String to escape\n@param {'DEFAULT' | 'CHAR_CLASS'} context `Context` option from lib `regex-utilities`\n@returns {string} Escaped string\n*/\nexport function escapeV(str, context) {\n if (context === Context.CHAR_CLASS) {\n // Escape all double punctuators (including ^, which is special on its own in the first\n // position) in case they're bordered by the same character in or outside of the escaped string\n return str.replace(new RegExp(String.raw`[()\\[\\]{}|\\\\/\\-${doublePunctuatorChars}]`, 'g'), '\\\\$&');\n }\n return str.replace(/[()\\[\\]{}|\\\\^$*+?.]/g, '\\\\$&');\n}\n\n// Look for characters that would change the meaning of subsequent tokens outside an interpolated value\nexport function getBreakoutChar(expression, regexContext, charClassContext) {\n const escapesRemoved = expression.replace(/\\\\./gsu, '');\n // Trailing unescaped `\\`; checking `.includes('\\\\')` would also work\n if (escapesRemoved.endsWith('\\\\')) {\n return '\\\\';\n }\n if (regexContext === RegexContext.DEFAULT) {\n // Unbalanced `[` or `]` are also errors but don't breakout; they're caught by the wrapper\n return getUnbalancedChar(escapesRemoved, '(', ')');\n } else if (\n regexContext === RegexContext.CHAR_CLASS &&\n !enclosedTokenCharClassContexts.has(charClassContext)\n ) {\n return getUnbalancedChar(escapesRemoved, '[', ']');\n } else if (\n regexContext === RegexContext.INTERVAL_QUANTIFIER ||\n enclosedTokenRegexContexts.has(regexContext) ||\n enclosedTokenCharClassContexts.has(charClassContext)\n ) {\n if (escapesRemoved.includes('}')) {\n return '}';\n }\n } else if (regexContext === RegexContext.GROUP_NAME) {\n if (escapesRemoved.includes('>')) {\n return '>';\n }\n }\n return '';\n}\n\nconst contextToken = new RegExp(String.raw`\n(?<groupN>\\(\\?<(?![=!])|\\\\[gk]<)\n| (?<enclosedPU>\\\\[pPu]\\{)\n| (?<enclosedQ>\\\\q\\{)\n| (?<intervalQ>\\{)\n| (?<incompleteT>\\\\(?: $\n | c(?![A-Za-z])\n | u(?![A-Fa-f\\d]{4})[A-Fa-f\\d]{0,3}\n | x(?![A-Fa-f\\d]{2})[A-Fa-f\\d]?\n )\n)\n| --\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\n@typedef {{\n regexContext: string;\n charClassContext: string;\n charClassDepth: number;\n lastPos: number;\n}} RunningContext\n*/\n/**\nAccepts and returns its full state so it doesn't have to reprocess parts that have already been\nseen. Assumes flag v and doesn't worry about syntax errors that are caught by it.\n@param {string} incompleteExpression\n@param {Partial<RunningContext>} [runningContext]\n@returns {RunningContext}\n*/\nexport function getEndContextForIncompleteExpression(incompleteExpression, {\n regexContext = RegexContext.DEFAULT,\n charClassContext = CharClassContext.DEFAULT,\n charClassDepth = 0,\n lastPos = 0,\n} = {}) {\n contextToken.lastIndex = lastPos;\n let match;\n while (match = contextToken.exec(incompleteExpression)) {\n const {0: m, groups: {groupN, enclosedPU, enclosedQ, intervalQ, incompleteT}} = match;\n if (m === '[') {\n charClassDepth++;\n regexContext = RegexContext.CHAR_CLASS;\n charClassContext = CharClassContext.DEFAULT;\n } else if (m === ']' && regexContext === RegexContext.CHAR_CLASS) {\n if (charClassDepth) {\n charClassDepth--;\n }\n if (!charClassDepth) {\n regexContext = RegexContext.DEFAULT;\n }\n charClassContext = CharClassContext.DEFAULT;\n } else if (regexContext === RegexContext.CHAR_CLASS) {\n if (incompleteT) {\n charClassContext = CharClassContext.INVALID_INCOMPLETE_TOKEN;\n } else if (m === '-') {\n charClassContext = CharClassContext.RANGE;\n } else if (enclosedPU) {\n charClassContext = m[1] === 'u' ? CharClassContext.ENCLOSED_U : CharClassContext.ENCLOSED_P;\n } else if (enclosedQ) {\n charClassContext = CharClassContext.ENCLOSED_Q;\n } else if (\n (m === '}' && enclosedTokenCharClassContexts.has(charClassContext)) ||\n // Don't continue in these contexts since we've advanced another token\n charClassContext === CharClassContext.INVALID_INCOMPLETE_TOKEN ||\n charClassContext === CharClassContext.RANGE\n ) {\n charClassContext = CharClassContext.DEFAULT;\n }\n } else {\n if (incompleteT) {\n regexContext = RegexContext.INVALID_INCOMPLETE_TOKEN;\n } else if (groupN) {\n regexContext = RegexContext.GROUP_NAME;\n } else if (enclosedPU) {\n regexContext = m[1] === 'u' ? RegexContext.ENCLOSED_U : RegexContext.ENCLOSED_P;\n } else if (intervalQ) {\n regexContext = RegexContext.INTERVAL_QUANTIFIER;\n } else if (\n (m === '>' && regexContext === RegexContext.GROUP_NAME) ||\n (m === '}' && (regexContext === RegexContext.INTERVAL_QUANTIFIER || enclosedTokenRegexContexts.has(regexContext))) ||\n // Don't continue in this context since we've advanced another token\n regexContext === RegexContext.INVALID_INCOMPLETE_TOKEN\n ) {\n regexContext = RegexContext.DEFAULT;\n }\n }\n }\n return {\n regexContext,\n charClassContext,\n charClassDepth,\n lastPos: incompleteExpression.length,\n };\n}\n\n// No special handling for escaped versions of the characters\nfunction getUnbalancedChar(expression, leftChar, rightChar) {\n let numOpen = 0;\n for (const [m] of expression.matchAll(new RegExp(`[${escapeV(leftChar + rightChar, Context.CHAR_CLASS)}]`, 'g'))) {\n numOpen += m === leftChar ? 1 : -1;\n if (numOpen < 0) {\n return rightChar;\n }\n }\n if (numOpen > 0) {\n return leftChar;\n }\n return '';\n}\n\n/**\n@typedef {import('./regex.js').InterpolatedValue} InterpolatedValue\n@typedef {import('./regex.js').RawTemplate} RawTemplate\n@typedef {import('./regex.js').RegexTagOptions} RegexTagOptions\n@typedef {(\n value: InterpolatedValue,\n runningContext: RunningContext,\n options: Required<RegexTagOptions>\n) => {\n transformed: string;\n runningContext: RunningContext;\n}} Preprocessor\n*/\n/**\nReturns transformed versions of a template and substitutions, using the given preprocessor. Only\nprocesses substitutions that are instanceof `Pattern`.\n@param {RawTemplate} template\n@param {ReadonlyArray<InterpolatedValue>} substitutions\n@param {Preprocessor} preprocessor\n@param {Required<RegexTagOptions>} options\n@returns {{template: RawTemplate; substitutions: ReadonlyArray<InterpolatedValue>;}}\n*/\nexport function preprocess(template, substitutions, preprocessor, options) {\n let /** @type {RawTemplate} */ newTemplate = {raw: []};\n let newSubstitutions = [];\n let runningContext;\n template.raw.forEach((raw, i) => {\n const result = preprocessor(raw, {...runningContext, lastPos: 0}, options);\n newTemplate.raw.push(result.transformed);\n runningContext = result.runningContext;\n if (i < template.raw.length - 1) {\n const substitution = substitutions[i];\n if (substitution instanceof Pattern) {\n const result = preprocessor(substitution, {...runningContext, lastPos: 0}, options);\n newSubstitutions.push(pattern(result.transformed));\n runningContext = result.runningContext;\n } else {\n newSubstitutions.push(substitution);\n }\n }\n });\n return {\n template: newTemplate,\n substitutions: newSubstitutions,\n };\n}\n\n// Sandbox `^` if relevant, done so it can't change the meaning of the surrounding character class\n// if we happen to be at the first position. See `sandboxLoneDoublePunctuatorChar` for more details\nexport function sandboxLoneCharClassCaret(str) {\n return str.replace(/^\\^/, '\\\\^^');\n}\n\n// Sandbox without escaping by repeating the character and escaping only the first one. The second\n// one is so that, if followed by the same symbol, the resulting double punctuator will still throw\n// as expected. Details:\n// - Only need to check the first position because, if it's part of an implicit union,\n// interpolation handling will wrap it in nested `[…]`.\n// - Can't just wrap in nested `[…]` here, since the value might be used in a range.\n// - Can't add a second unescaped symbol if a lone symbol is the entire string because it might be\n// followed by the same unescaped symbol outside an interpolation, and since it won't be wrapped,\n// the second symbol wouldn't be sandboxed from the one following it.\nexport function sandboxLoneDoublePunctuatorChar(str) {\n return str.replace(new RegExp(`^([${doublePunctuatorChars}])(?!\\\\1)`), (m, _, pos) => {\n return `\\\\${m}${pos + 1 === str.length ? '' : m}`;\n });\n}\n\n/**\nConverts `\\0` tokens to `\\x00` in the given context.\n@param {string} str\n@param {'DEFAULT' | 'CHAR_CLASS'} [context] `Context` option from lib `regex-utilities`\n@returns {string}\n*/\nexport function sandboxUnsafeNulls(str, context) {\n // regex`[\\0${0}]` and regex`[${pattern`\\0`}0]` can't be guarded against via nested `[…]`\n // sandboxing in character classes if the interpolated value doesn't contain union (since it\n // might be placed on a range boundary). So escape `\\0` in character classes as `\\x00`\n return replaceUnescaped(str, String.raw`\\\\0(?!\\d)`, '\\\\x00', context);\n}\n\n/**\n@param {string} str\n@param {number} pos\n@param {string} oldValue\n@param {string} newValue\n@returns {string}\n*/\nexport function spliceStr(str, pos, oldValue, newValue) {\n return str.slice(0, pos) + newValue + str.slice(pos + oldValue.length);\n}\n","import {emulationGroupMarker, noncapturingDelim, spliceStr} from './utils.js';\nimport {Context, replaceUnescaped} from 'regex-utilities';\n\nconst atomicPluginToken = new RegExp(String.raw`(?<noncapturingStart>${noncapturingDelim})|(?<capturingStart>\\((?:\\?<[^>]+>)?)|\\\\?.`, 'gsu');\n\n/**\nApply transformations for atomic groups: `(?>…)`.\n@param {string} expression\n@param {import('./regex.js').PluginData} [data]\n@returns {string}\n*/\nexport function atomic(expression, data) {\n if (!/\\(\\?>/.test(expression)) {\n return expression;\n }\n const aGDelim = '(?>';\n const emulatedAGDelim = `(?:(?=(${data?.useEmulationGroups ? emulationGroupMarker : ''}`;\n const captureNumMap = [0];\n let numCapturesBeforeAG = 0;\n let numAGs = 0;\n let aGPos = NaN;\n let hasProcessedAG;\n do {\n hasProcessedAG = false;\n let numCharClassesOpen = 0;\n let numGroupsOpenInAG = 0;\n let inAG = false;\n let match;\n atomicPluginToken.lastIndex = Number.isNaN(aGPos) ? 0 : aGPos + emulatedAGDelim.length;\n while (match = atomicPluginToken.exec(expression)) {\n const {0: m, index, groups: {capturingStart, noncapturingStart}} = match;\n if (m === '[') {\n numCharClassesOpen++;\n } else if (!numCharClassesOpen) {\n\n if (m === aGDelim && !inAG) {\n aGPos = index;\n inAG = true;\n } else if (inAG && noncapturingStart) {\n numGroupsOpenInAG++;\n } else if (capturingStart) {\n if (inAG) {\n numGroupsOpenInAG++;\n } else {\n numCapturesBeforeAG++;\n captureNumMap.push(numCapturesBeforeAG + numAGs);\n }\n } else if (m === ')' && inAG) {\n if (!numGroupsOpenInAG) {\n numAGs++;\n // Replace `expression` and use `<$$N>` as a temporary wrapper for the backref so it\n // can avoid backref renumbering afterward. Need to wrap the whole substitution\n // (including the lookahead and following backref) in a noncapturing group to handle\n // following quantifiers and literal digits\n expression = `${expression.slice(0, aGPos)}${emulatedAGDelim}${\n expression.slice(aGPos + aGDelim.length, index)\n }))<$$${numAGs + numCapturesBeforeAG}>)${expression.slice(index + 1)}`;\n hasProcessedAG = true;\n break;\n }\n numGroupsOpenInAG--;\n }\n\n } else if (m === ']') {\n numCharClassesOpen--;\n }\n }\n // Start over from the beginning of the last atomic group's contents, in case the processed group\n // contains additional atomic groups\n } while (hasProcessedAG);\n\n // Second pass to adjust numbered backrefs\n expression = replaceUnescaped(\n expression,\n String.raw`\\\\(?<backrefNum>[1-9]\\d*)|<\\$\\$(?<wrappedBackrefNum>\\d+)>`,\n ({0: m, groups: {backrefNum, wrappedBackrefNum}}) => {\n if (backrefNum) {\n const bNum = +backrefNum;\n if (bNum > captureNumMap.length - 1) {\n throw new Error(`Backref \"${m}\" greater than number of captures`);\n }\n return `\\\\${captureNumMap[bNum]}`;\n }\n return `\\\\${wrappedBackrefNum}`;\n },\n Context.DEFAULT\n );\n return expression;\n}\n\nconst baseQuantifier = String.raw`(?:[?*+]|\\{\\d+(?:,\\d*)?\\})`;\n// Complete tokenizer for base syntax; doesn't (need to) know about character-class-only syntax\nconst possessivePluginToken = new RegExp(String.raw`\n\\\\(?: \\d+\n | c[A-Za-z]\n | [gk]<[^>]+>\n | [pPu]\\{[^\\}]+\\}\n | u[A-Fa-f\\d]{4}\n | x[A-Fa-f\\d]{2}\n )\n| \\((?: \\? (?: [:=!>]\n | <(?:[=!]|[^>]+>)\n | [A-Za-z\\-]+:\n | \\(DEFINE\\)\n ))?\n| (?<qBase>${baseQuantifier})(?<qMod>[?+]?)(?<invalidQ>[?*+\\{]?)\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\nTransform posessive quantifiers into atomic groups. The posessessive quantifiers are:\n`?+`, `*+`, `++`, `{N}+`, `{N,}+`, `{N,N}+`.\nThis follows Java, PCRE, Perl, and Python.\nPossessive quantifiers in Oniguruma and Onigmo are only: `?+`, `*+`, `++`.\n@param {string} expression\n@returns {string}\n*/\nexport function possessive(expression) {\n if (!(new RegExp(`${baseQuantifier}\\\\+`).test(expression))) {\n return expression;\n }\n const openGroupIndices = [];\n let lastGroupIndex = null;\n let lastCharClassIndex = null;\n let lastToken = '';\n let numCharClassesOpen = 0;\n let match;\n possessivePluginToken.lastIndex = 0;\n while (match = possessivePluginToken.exec(expression)) {\n const {0: m, index, groups: {qBase, qMod, invalidQ}} = match;\n if (m === '[') {\n if (!numCharClassesOpen) {\n lastCharClassIndex = index;\n }\n numCharClassesOpen++;\n } else if (m === ']') {\n if (numCharClassesOpen) {\n numCharClassesOpen--;\n // Unmatched `]`\n } else {\n lastCharClassIndex = null;\n }\n } else if (!numCharClassesOpen) {\n\n if (qMod === '+' && lastToken && !lastToken.startsWith('(')) {\n // Invalid following quantifier would become valid via the wrapping group\n if (invalidQ) {\n throw new Error(`Invalid quantifier \"${m}\"`);\n }\n let charsAdded = -1; // -1 for removed trailing `+`\n // Possessivizing fixed repetition quantifiers like `{2}` does't change their behavior, so\n // avoid doing so (convert them to greedy)\n if (/^\\{\\d+\\}$/.test(qBase)) {\n expression = spliceStr(expression, index + qBase.length, qMod, '');\n } else {\n if (lastToken === ')' || lastToken === ']') {\n const nodeIndex = lastToken === ')' ? lastGroupIndex : lastCharClassIndex;\n // Unmatched `)` would break out of the wrapping group and mess with handling.\n // Unmatched `]` wouldn't be a problem, but it's unnecessary to have dedicated support\n // for unescaped `]++` since this won't work with flag u or v anyway\n if (nodeIndex === null) {\n throw new Error(`Invalid unmatched \"${lastToken}\"`);\n }\n expression = `${expression.slice(0, nodeIndex)}(?>${expression.slice(nodeIndex, index)}${qBase})${expression.slice(index + m.length)}`;\n } else {\n expression = `${expression.slice(0, index - lastToken.length)}(?>${lastToken}${qBase})${expression.slice(index + m.length)}`;\n }\n charsAdded += 4; // `(?>)`\n }\n possessivePluginToken.lastIndex += charsAdded;\n } else if (m[0] === '(') {\n openGroupIndices.push(index);\n } else if (m === ')') {\n lastGroupIndex = openGroupIndices.length ? openGroupIndices.pop() : null;\n }\n\n }\n lastToken = m;\n }\n return expression;\n}\n","import {doublePunctuatorChars} from './utils.js';\n\nconst incompatibleEscapeChars = '&!#%,:;<=>@`~';\nconst token = new RegExp(String.raw`\n\\[\\^?-?\n| --?\\]\n| (?<dp>[${doublePunctuatorChars}])\\k<dp>\n| --\n| \\\\(?<vOnlyEscape>[${incompatibleEscapeChars}])\n| \\\\[pPu]\\{[^}]+\\}\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\nApplies flag v rules when using flag u, for forward compatibility.\nAssumes flag u and doesn't worry about syntax errors that are caught by it.\n@param {string} expression\n@returns {string}\n*/\nexport function backcompatPlugin(expression) {\n const unescapedLiteralHyphenMsg = 'Invalid unescaped \"-\" in character class';\n let inCharClass = false;\n let result = '';\n for (const {0: m, groups: {dp, vOnlyEscape}} of expression.matchAll(token)) {\n if (m[0] === '[') {\n if (inCharClass) {\n throw new Error('Invalid nested character class when flag v not supported; possibly from interpolation');\n }\n if (m.endsWith('-')) {\n throw new Error(unescapedLiteralHyphenMsg);\n }\n inCharClass = true;\n } else if (m.endsWith(']')) {\n if (m[0] === '-') {\n throw new Error(unescapedLiteralHyphenMsg);\n }\n inCharClass = false;\n } else if (inCharClass) {\n if (m === '&&' || m === '--') {\n throw new Error(`Invalid set operator \"${m}\" when flag v not supported`);\n } else if (dp) {\n throw new Error(`Invalid double punctuator \"${m}\", reserved by flag v`);\n } else if ('(){}/|'.includes(m)) {\n throw new Error(`Invalid unescaped \"${m}\" in character class`);\n } else if (vOnlyEscape) {\n // Remove the escaping backslash to emulate flag v rules, since this character is allowed\n // to be escaped within character classes with flag v but not with flag u\n result += vOnlyEscape;\n continue;\n }\n }\n result += m;\n }\n return result;\n}\n","import {getEndContextForIncompleteExpression, noncapturingDelim, RegexContext} from './utils.js';\n\nconst token = new RegExp(String.raw`\n${noncapturingDelim}\n| \\(\\?<\n| (?<backrefNum>\\\\[1-9]\\d*)\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\nApply transformations for flag n (named capture only).\n\nPreprocessors are applied to the outer regex and interpolated patterns, but not interpolated\nregexes or strings.\n@type {import('./utils.js').Preprocessor}\n*/\nexport function flagNPreprocessor(value, runningContext) {\n value = String(value);\n let expression = '';\n let transformed = '';\n for (const {0: m, groups: {backrefNum}} of value.matchAll(token)) {\n expression += m;\n runningContext = getEndContextForIncompleteExpression(expression, runningContext);\n const {regexContext} = runningContext;\n if (regexContext === RegexContext.DEFAULT) {\n if (m === '(') {\n transformed += '(?:';\n } else if (backrefNum) {\n throw new Error(`Invalid decimal escape \"${m}\" with implicit flag n; replace with named backreference`);\n } else {\n transformed += m;\n }\n } else {\n transformed += m;\n }\n }\n return {\n transformed,\n runningContext,\n };\n}\n","import {CharClassContext, doublePunctuatorChars, emulationGroupMarker, getEndContextForIncompleteExpression, noncapturingDelim, RegexContext, sandboxLoneDoublePunctuatorChar, sandboxUnsafeNulls} from './utils.js';\nimport {Context, replaceUnescaped} from 'regex-utilities';\n\nconst ws = /^\\s$/;\nconst escapedWsOrHash = /^\\\\[\\s#]$/;\nconst charClassWs = /^[ \\t]$/;\nconst escapedCharClassWs = /^\\\\[ \\t]$/;\nconst token = new RegExp(String.raw`\n\\\\(?: [gk]<\n | [pPu]\\{\n | c[A-Za-z]\n | u[A-Fa-f\\d]{4}\n | x[A-Fa-f\\d]{2}\n | 0\\d+\n)\n| \\[\\^\n| ${noncapturingDelim}\n| \\(\\?<\n| (?<dp>[${doublePunctuatorChars}])\\k<dp>\n| --\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\nApply transformations for flag x (insignificant whitespace and line comments).\n\nPreprocessors are applied to the outer regex and interpolated patterns, but not interpolated\nregexes or strings.\n@type {import('./utils.js').Preprocessor}\n*/\nexport function flagXPreprocessor(value, runningContext, options) {\n value = String(value);\n let ignoringWs = false;\n let ignoringCharClassWs = false;\n let ignoringComment = false;\n let expression = '';\n let transformed = '';\n let lastSignificantToken = '';\n let lastSignificantCharClassContext = '';\n let separatorNeeded = false;\n const update = (str, {prefix = true, postfix = false} = {}) => {\n str = (separatorNeeded && prefix ? '(?:)' : '') + str + (postfix ? '(?:)' : '');\n separatorNeeded = false;\n return str;\n };\n for (const {0: m, index} of value.matchAll(token)) {\n if (ignoringComment) {\n if (m === '\\n') {\n ignoringComment = false;\n separatorNeeded = true;\n }\n continue;\n }\n if (ignoringWs) {\n if (ws.test(m)) {\n continue;\n }\n ignoringWs = false;\n separatorNeeded = true;\n } else if (ignoringCharClassWs) {\n if (charClassWs.test(m)) {\n continue;\n }\n ignoringCharClassWs = false;\n }\n\n expression += m;\n runningContext = getEndContextForIncompleteExpression(expression, runningContext);\n const {regexContext, charClassContext} = runningContext;\n if (\n // `--` is matched in one step, so boundary chars aren't `-` unless separated by whitespace\n m === '-' &&\n regexContext === RegexContext.CHAR_CLASS &&\n lastSignificantCharClassContext === CharClassContext.RANGE &&\n (options.flags.includes('v') || options.unicodeSetsPlugin)\n ) {\n // Need to handle this here since the main regex-parsing code would think the hyphen forms\n // part of a subtraction operator since we've removed preceding whitespace\n throw new Error('Invalid unescaped hyphen as the end value for a range');\n }\n if (\n // `??` is matched in one step by the double punctuator token\n (regexContext === RegexContext.DEFAULT && /^(?:[?*+]|\\?\\?)$/.test(m)) ||\n (regexContext === RegexContext.INTERVAL_QUANTIFIER && m === '{')\n ) {\n // Skip the separator prefix and connect the quantifier to the previous token. This also\n // allows whitespace between a quantifier and the `?` that makes it lazy. Add a postfix\n // separator if `m` is `?` and we're following token `(`, to sandbox the `?` from following\n // tokens (since `?` can be a group-type marker). Ex: `( ?:)` becomes `(?(?:):)` and throws.\n // The loop we're in matches valid group openings in one step, so we won't arrive here if\n // matching e.g. `(?:`. Flag n could prevent the need for the postfix since bare `(` is\n // converted to `(?:`, but flag x handling always comes first and flag n can be turned off\n transformed += update(m, {prefix: false, postfix: lastSignificantToken === '(' && m === '?'});\n } else if (regexContext === RegexContext.DEFAULT) {\n if (ws.test(m)) {\n ignoringWs = true;\n } else if (m.startsWith('#')) {\n ignoringComment = true;\n } else if (escapedWsOrHash.test(m)) {\n transformed += update(m[1], {prefix: false});\n } else {\n transformed += update(m);\n }\n } else if (regexContext === RegexContext.CHAR_CLASS && m !== '[' && m !== '[^') {\n if (\n charClassWs.test(m) &&\n ( charClassContext === CharClassContext.DEFAULT ||\n charClassContext === CharClassContext.ENCLOSED_Q ||\n charClassContext === CharClassContext.RANGE\n )\n ) {\n ignoringCharClassWs = true;\n } else if (charClassContext === CharClassContext.INVALID_INCOMPLETE_TOKEN) {\n // Need to handle this here since the main regex-parsing code wouldn't know where the token\n // ends if we removed whitespace after an incomplete token that is followed by something\n // that completes the token\n throw new Error(`Invalid incomplete token in character class: \"${m}\"`);\n } else if (\n escapedCharClassWs.test(m) &&\n (charClassContext === CharClassContext.DEFAULT || charClassContext === CharClassContext.ENCLOSED_Q)\n ) {\n transformed += update(m[1], {prefix: false});\n } else if (charClassContext === CharClassContext.DEFAULT) {\n const nextChar = value[index + 1] ?? '';\n let updated = sandboxUnsafeNulls(m);\n // Avoid escaping lone double punctuators unless required, since some of them are not\n // allowed to be escaped with flag u (the `unicodeSetsPlugin` already unescapes them when\n // using flag u, but it can be set to `null` via an option)\n if (charClassWs.test(nextChar) || m === '^') {\n updated = sandboxLoneDoublePunctuatorChar(updated);\n }\n transformed += update(updated);\n } else {\n transformed += update(m);\n }\n } else {\n transformed += update(m);\n }\n if (!(ignoringWs || ignoringCharClassWs || ignoringComment)) {\n lastSignificantToken = m;\n lastSignificantCharClassContext = charClassContext;\n }\n }\n return {\n transformed,\n runningContext,\n };\n}\n\n/**\nRemove `(?:)` token separators (most likely added by flag x) in cases where it's safe to do so.\n@param {string} expression\n@returns {string}\n*/\nexport function clean(expression) {\n const sep = String.raw`\\(\\?:\\)`;\n // No need for repeated separators\n expression = replaceUnescaped(expression, `(?:${sep}){2,}`, '(?:)', Context.DEFAULT);\n // No need for separators at:\n // - The beginning, if not followed by a quantifier.\n // - The end.\n // - Outside of character classes:\n // - If followed by one of `)|.[$\\\\`, or `(` if that's not followed by `DEFINE)`.\n // - Technically we shouldn't remove `(?:)` if preceded by `(?(DEFINE` and followed by `)`,\n // but in this case flag x injects a sandboxing `(?:)` after the preceding invalid `(?`,\n // so we already get an error from that.\n // - If preceded by one of `()|.]^>`, `\\\\[bBdDfnrsStvwW]`, `(?:`, or a lookaround opening.\n // - So long as the separator is not followed by a quantifier.\n // - And, not followed by an emulation group marker.\n // Examples of things that are not safe to remove `(?:)` at the boundaries of:\n // - Anywhere: Letters, numbers, or any of `-=_,<?*+{}`.\n // - If followed by any of `:!>`.\n // - If preceded by any of `\\\\[cgkpPux]`.\n // - Anything inside character classes.\n const marker = emulationGroupMarker.replace(/\\$/g, '\\\\$');\n expression = replaceUnescaped(\n expression,\n String.raw`(?:${sep}(?=[)|.[$\\\\]|\\((?!DEFINE)|$)|(?<=[()|.\\]^>]|\\\\[bBdDfnrsStvwW]|\\(\\?(?:[:=!]|<[=!])|^)${sep}(?![?*+{]))(?!${marker})`,\n '',\n Context.DEFAULT\n );\n return expression;\n}\n","import {capturingDelim, countCaptures, emulationGroupMarker, namedCapturingDelim, spliceStr} from './utils.js';\nimport {Context, execUnescaped, forEachUnescaped, getGroupContents, hasUnescaped, replaceUnescaped} from 'regex-utilities';\n\n/**\n@param {string} expression\n@param {import('./regex.js').PluginData} [data]\n@returns {string}\n*/\nexport function subroutines(expression, data) {\n // NOTE: subroutines and definition groups fully support numbered backreferences and unnamed\n // captures (from interpolated regexes or from turning implicit flag n off), and all of the\n // complex forward and backward backreference adjustments that can result\n const namedGroups = getNamedCapturingGroups(expression, {includeContents: true});\n const transformed = processSubroutines(expression, namedGroups, !!data?.useEmulationGroups);\n return processDefinitionGroup(transformed, namedGroups);\n}\n\n// Explicitly exclude `&` from subroutine name chars because it's used by extension\n// `regex-recursion` for recursive subroutines via `\\g<name&R=N>`\nconst subroutinePattern = String.raw`\\\\g<(?<subroutineName>[^>&]+)>`;\nconst token = new RegExp(String.raw`\n${subroutinePattern}\n| (?<capturingStart>${capturingDelim})\n| \\\\(?<backrefNum>[1-9]\\d*)\n| \\\\k<(?<backrefName>[^>]+)>\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\n@typedef {\n Map<string, {\n isUnique: boolean;\n contents?: string;\n groupNum?: number;\n numCaptures?: number;\n }>} NamedCapturingGroupsMap\n*/\n/**\nApply transformations for subroutines: `\\g<name>`.\n@param {string} expression\n@param {NamedCapturingGroupsMap} namedGroups\n@param {boolean} useEmulationGroups\n@returns {string}\n*/\nfunction processSubroutines(expression, namedGroups, useEmulationGroups) {\n if (!/\\\\g</.test(expression)) {\n return expression;\n }\n // Can skip a lot of processing and avoid adding captures if there are no backrefs\n const hasBackrefs = hasUnescaped(expression, '\\\\\\\\(?:[1-9]|k<[^>]+>)', Context.DEFAULT);\n const subroutineWrapper = hasBackrefs ? `(${useEmulationGroups ? emulationGroupMarker : ''}` : '(?:';\n const openSubroutines = new Map();\n const openSubroutinesStack = [];\n const captureNumMap = [0];\n let numCapturesPassedOutsideSubroutines = 0;\n let numCapturesPassedInsideSubroutines = 0;\n let numCapturesPassedInsideThisSubroutine = 0;\n let numSubroutineCapturesTrackedInRemap = 0;\n let numCharClassesOpen = 0;\n let result = expression;\n let match;\n token.lastIndex = 0;\n while (match = token.exec(result)) {\n const {0: m, index, groups: {subroutineName, capturingStart, backrefNum, backrefName}} = match;\n if (m === '[') {\n numCharClassesOpen++;\n } else if (!numCharClassesOpen) {\n\n if (subroutineName) {\n if (!namedGroups.has(subroutineName)) {\n throw new Error(`Invalid named capture referenced by subroutine ${m}`);\n }\n if (openSubroutines.has(subroutineName)) {\n throw new Error(`Subroutine ${m} followed a recursive reference`);\n }\n const contents = namedGroups.get(subroutineName).contents;\n // Wrap value in case it has top-level alternation or is followed by a quantifier. The\n // wrapper also marks the end of the expanded contents, which we'll track using\n // `unclosedGroupCount`. If there are any backrefs in the expression, wrap with `()`\n // instead of `(?:)` in case there are backrefs inside the subroutine that refer to their\n // containing capturing group\n const subroutineValue = `${subroutineWrapper}${contents})`;\n if (hasBackrefs) {\n numCapturesPassedInsideThisSubroutine = 0;\n numCapturesPassedInsideSubroutines++;\n }\n openSubroutines.set(subroutineName, {\n // Incrementally decremented to track when we've left the group\n unclosedGroupCount: countOpenParens(subroutineValue),\n });\n openSubroutinesStack.push(subroutineName);\n // Expand the subroutine's contents into the pattern we're looping over\n result = spliceStr(result, index, m, subroutineValue);\n token.lastIndex -= m.length - subroutineWrapper.length;\n } else if (capturingStart) {\n // Somewhere within an expanded subroutine\n if (openSubroutines.size) {\n if (hasBackrefs) {\n numCapturesPassedInsideThisSubroutine++;\n numCapturesPassedInsideSubroutines++;\n }\n // Named capturing group\n if (m !== '(') {\n // Replace named with unnamed capture. Subroutines ideally wouldn't create any new\n // captures, but it can't be helped since we need any backrefs to this capture to work.\n // Given that flag n prevents unnamed capture and thereby requires you to rely on named\n // backrefs and `groups`, switching to unnamed essentially accomplishes not creating a\n // capture. Can fully avoid capturing if there are no backrefs in the expression\n result = spliceStr(result, index, m, subroutineWrapper);\n token.lastIndex -= m.length - subroutineWrapper.length;\n }\n } else if (hasBackrefs) {\n captureNumMap.push(\n lastOf(captureNumMap) + 1 +\n numCapturesPassedInsideSubroutines -\n numSubroutineCapturesTrackedInRemap\n );\n numSubroutineCapturesTrackedInRemap = numCapturesPassedInsideSubroutines;\n numCapturesPassedOutsideSubroutines++;\n }\n } else if ((backrefNum || backrefName) && openSubroutines.size) {\n // Unify handling for named and unnamed by always using the backref num\n const num = backrefNum ? +backrefNum : namedGroups.get(backrefName)?.groupNum;\n let isGroupFromThisSubroutine = false;\n // Search for the group in the contents of the subroutine stack\n for (const s of openSubroutinesStack) {\n const group = namedGroups.get(s);\n if (num >= group.groupNum && num <= (group.groupNum + group.numCaptures)) {\n isGroupFromThisSubroutine = true;\n break;\n }\n }\n if (isGroupFromThisSubroutine) {\n const group = namedGroups.get(lastOf(openSubroutinesStack));\n // Replace the backref with metadata we'll need to rewrite it later, using\n // `\\k<$$bNsNrNcN>` as a temporary wrapper:\n // - b: The unmodified matched backref num, or the corresponding num of a named backref\n // - s: The capture num of the subroutine we're most deeply nested in, including captures\n // added by expanding the contents of preceding subroutines\n // - r: The original capture num of the group that the subroutine we're most deeply\n // nested in references, not counting the effects of subroutines\n // - c: The number of captures within `r`, not counting the effects of subroutines\n const subroutineNum = numCapturesPassedOutsideSubroutines + numCapturesPassedInsideSubroutines - numCapturesPassedInsideThisSubroutine;\n const metadata = `\\\\k<$$b${num}s${subroutineNum}r${group.groupNum}c${group.numCaptures}>`;\n result = spliceStr(result, index, m, metadata);\n token.lastIndex += metadata.length - m.length;\n }\n } else if (m === ')') {\n if (openSubroutines.size) {\n const subroutine = openSubroutines.get(lastOf(openSubroutinesStack));\n subroutine.unclosedGroupCount--;\n if (!subroutine.unclosedGroupCount) {\n openSubroutines.delete(openSubroutinesStack.pop());\n }\n }\n }\n\n } else if (m === ']') {\n numCharClassesOpen--;\n }\n }\n\n if (hasBackrefs) {\n // Second pass to adjust backrefs\n result = replaceUnescaped(\n result,\n String.raw`\\\\(?:(?<bNum>[1-9]\\d*)|k<\\$\\$b(?<bNumSub>\\d+)s(?<subNum>\\d+)r(?<refNum>\\d+)c(?<refCaps>\\d+)>)`,\n ({0: m, groups: {bNum, bNumSub, subNum, refNum, refCaps}}) => {\n if (bNum) {\n const backrefNum = +bNum;\n if (backrefNum > captureNumMap.length - 1) {\n throw new Error(`Backref \"${m}\" greater than number of captures`);\n }\n return `\\\\${captureNumMap[backrefNum]}`;\n }\n const backrefNumInSubroutine = +bNumSub;\n const subroutineGroupNum = +subNum;\n const refGroupNum = +refNum;\n const numCapturesInRef = +refCaps;\n if (backrefNumInSubroutine < refGroupNum || backrefNumInSubroutine > (refGroupNum + numCapturesInRef)) {\n return `\\\\${captureNumMap[backrefNumInSubroutine]}`;\n }\n return `\\\\${subroutineGroupNum - refGroupNum + backrefNumInSubroutine}`;\n },\n Context.DEFAULT\n );\n }\n\n return result;\n}\n\n// `(?:)` allowed because it can be added by flag x's preprocessing of whitespace and comments\nconst defineGroupToken = new RegExp(String.raw`${namedCapturingDelim}|\\(\\?:\\)|(?<invalid>\\\\?.)`, 'gsu');\n\n/**\nRemove valid subroutine definition groups: `(?(DEFINE)…)`.\n@param {string} expression\n@param {NamedCapturingGroupsMap} namedGroups\nIMPORTANT: Avoid using the `contents` property of `namedGroups` objects, because at this point\nsubroutine substitution has been performed on the corresponding substrings in `expression`\n@returns {string}\n*/\nfunction processDefinitionGroup(expression, namedGroups) {\n const defineMatch = execUnescaped(expression, String.raw`\\(\\?\\(DEFINE\\)`, 0, Context.DEFAULT);\n if (!defineMatch) {\n return expression;\n }\n const defineGroup = getGroup(expression, defineMatch);\n if (defineGroup.afterPos < expression.length) {\n // Supporting DEFINE at positions other than the end would complicate backref handling.\n // NOTE: Flag x's preprocessing permits trailing whitespace and comments\n throw new Error('DEFINE group allowed only at the end of a regex');\n } else if (defineGroup.afterPos > expression.length) {\n throw new Error('DEFINE group is unclosed');\n }\n let match;\n defineGroupToken.lastIndex = 0;\n while (match = defineGroupToken.exec(defineGroup.contents)) {\n const {captureName, invalid} = match.groups;\n if (captureName) {\n const group = getGroup(defineGroup.contents, match);\n let duplicateName;\n if (!namedGroups.get(captureName).isUnique) {\n duplicateName = captureName;\n } else {\n const nestedNamedGroups = getNamedCapturingGroups(group.contents);\n for (const name of nestedNamedGroups.keys()) {\n if (!namedGroups.get(name).isUnique) {\n duplicateName = name;\n break;\n }\n }\n }\n if (duplicateName) {\n throw new Error(`Duplicate group name \"${duplicateName}\" within DEFINE`);\n }\n defineGroupToken.lastIndex = group.afterPos;\n } else if (invalid) {\n // Since a DEFINE group is stripped from its expression, we can't easily determine whether\n // unreferenced top-level syntax within it is valid. Such syntax serves no purpose, so it's\n // easiest to not allow it\n throw new Error(`DEFINE group includes unsupported syntax at top level`);\n }\n }\n return expression.slice(0, defineMatch.index);\n}\n\n/**\nCounts unescaped open parens outside of character classes, regardless of group type\n@param {string} expression\n@returns {number}\n*/\nfunction countOpenParens(expression) {\n let num = 0;\n forEachUnescaped(expression, '\\\\(', () => num++, Context.DEFAULT);\n return num;\n}\n\n/**\n@param {string} expression\n@param {string} groupName\n@returns {number}\n*/\nfunction getCaptureNum(expression, groupName) {\n let num = 0;\n let pos = 0;\n let match;\n while (match = execUnescaped(expression, capturingDelim, pos, Context.DEFAULT)) {\n const {0: m, index, groups: {captureName}} = match;\n num++;\n if (captureName === groupName) {\n break;\n }\n pos = index + m.length;\n }\n return num;\n}\n\n/**\n@param {string} expression\n@param {RegExpExecArray} delimMatch\n@returns {{contents: string; afterPos: number}}\n*/\nfunction getGroup(expression, delimMatch) {\n const contentsStart = delimMatch.index + delimMatch[0].length;\n const contents = getGroupContents(expression, contentsStart);\n const afterPos = contentsStart + contents.length + 1;\n return {\n contents,\n afterPos,\n };\n}\n\n/**\n@param {string} expression\n@param {{includeContents: boolean}} [options]\n@returns {NamedCapturingGroupsMap}\n*/\nfunction getNamedCapturingGroups(expression, {includeContents} = {}) {\n const namedGroups = new Map();\n forEachUnescaped(\n expression,\n namedCapturingDelim,\n ({0: m, index, groups: {captureName}}) => {\n // If there are duplicate capture names, subroutines refer to the first instance of the given\n // group (matching the behavior of PCRE and Perl)\n if (namedGroups.has(captureName)) {\n namedGroups.get(captureName).isUnique = false;\n } else {\n const group = {isUnique: true};\n if (includeContents) {\n const contents = getGroupContents(expression, index + m.length);\n Object.assign(group, {\n contents,\n groupNum: getCaptureNum(expression, captureName),\n numCaptures: countCaptures(contents),\n });\n }\n namedGroups.set(captureName, group);\n }\n },\n Context.DEFAULT\n );\n return namedGroups;\n}\n\n/**\n@param {Array<any>} arr\n@returns {any}\n*/\nfunction lastOf(arr) {\n // Remove when support for ES2022 array method `at` (Node.js 16.6) is no longer an issue:\n // <https://caniuse.com/mdn-javascript_builtins_array_at>\n return arr[arr.length - 1];\n}\n","import { rewrite } from 'regex';\n\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => {\n __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nclass RegExpConversionError extends SyntaxError {\n constructor(message, options) {\n super(message, { cause: options.cause });\n __publicField(this, \"patternOriginal\");\n __publicField(this, \"patternConverted\");\n __publicField(this, \"cursorPosition\");\n this.patternOriginal = options.pattern;\n this.patternConverted = options.converted;\n this.cursorPosition = options.cursor;\n }\n}\n\nconst UNNECESSARY_ESCAPE_CHAR_CLASS = new Set(\"!?:=+$(){}_><# \");\nconst UNNECESSARY_ESCAPE = new Set(\"-!:=_>< \");\nconst TABLE_POSIX = {\n alnum: \"0-9A-Za-z\",\n alpha: \"A-Za-z\",\n ascii: \"\\0-\\x7F\",\n blank: \" \\\\t\",\n cntrl: \"\\0-\u001f\\x7F\",\n digit: \"\\\\d\",\n graph: \"!-~\",\n lower: \"a-z\",\n print: \" -~\",\n punct: \"!-/:-@[-`{-~\",\n space: \"\\\\s\",\n upper: \"A-Z\",\n xdigit: \"0-9A-Fa-f\",\n word: \"\\\\w\"\n};\nconst TABLE_SLASH_P = {\n alnum: \"0-9A-Za-z\",\n alpha: \"A-Za-z\",\n alphabetic: \"A-Za-z\",\n blank: \"\\\\s\",\n greek: \"\\\\p{Script=Greek}\",\n print: \"\\\\p{L}\\\\p{N}\\\\p{P}\\\\p{S}\\\\p{Zs}\",\n word: \"\\\\w\"\n};\nconst KNOWN_FLAGS = /* @__PURE__ */ new Set(\"gimsuyx\");\nfunction syntaxLowering(input, options = {}) {\n const {\n useRegex = false,\n preserveFlags = false,\n removePossessiveQuantifier = false,\n removeAtomicGroup = false,\n convertHexDigitsShorthand = false,\n convertUnicodeCategory = false,\n expandNestedCharacterClass = false\n } = options;\n let output = \"\";\n const flags = /* @__PURE__ */ new Set();\n const stack = [];\n const freeSpacingLocal = [];\n let freeSpacingGlobal = false;\n let isInNestedCharClass = false;\n let i = 0;\n try {\n while (i < input.length) {\n const char = input[i];\n while (freeSpacingLocal.length && freeSpacingLocal[0] > stack.length) {\n freeSpacingLocal.shift();\n }\n const head = stack[0];\n const freeSpacing = freeSpacingGlobal || freeSpacingLocal.length;\n if (char === \"\\\\\") {\n if (convertHexDigitsShorthand) {\n if (input[i + 1] === \"h\") {\n const body = `0-9A-Fa-f`;\n if (head === \"[\") {\n output += body;\n } else {\n output += `[${body}]`;\n }\n i += 2;\n continue;\n }\n if (input[i + 1] === \"H\") {\n if (head === \"[\") {\n throw new RegExpConversionError(\n \"Expending \\\\H in character class is not supported\",\n { pattern: input, converted: output, cursor: i }\n );\n } else {\n output += `[^0-9A-Fa-f]`;\n }\n i += 2;\n continue;\n }\n }\n if (convertUnicodeCategory && input[i + 1] === \"p\" && input[i + 2] === \"{\") {\n const end = input.indexOf(\"}\", i + 3);\n if (end === -1) {\n throw new RegExpConversionError(\n \"Unmatched \\\\p{...}\",\n { pattern: input, converted: output, cursor: i }\n );\n }\n const name = input.slice(i + 3, end);\n const resolved = TABLE_SLASH_P[name.toLowerCase()];\n if (resolved) {\n if (head === \"[\") {\n output += resolved;\n } else {\n output += `[${resolved}]`;\n }\n i = end + 1;\n continue;\n }\n }\n if (head === \"[\" && UNNECESSARY_ESCAPE_CHAR_CLASS.has(input[i + 1])) {\n output += input[i + 1];\n i += 2;\n continue;\n }\n if (head !== \"[\" && UNNECESSARY_ESCAPE.has(input[i + 1])) {\n output += input[i + 1];\n i += 2;\n continue;\n }\n output += char + input[i + 1];\n i += 2;\n continue;\n }\n if (char === \"#\" && freeSpacing && input[i - 1].match(/\\s/) && head !== \"[\") {\n for (let j = i + 1; j <= input.length; j++) {\n if (input[j] === \"\\n\" || j === input.length) {\n i = j;\n break;\n }\n }\n continue;\n }\n if (char === \"(\" && head !== \"[\") {\n if (input[i + 1] === \"?\") {\n if (input[i + 2] === \"#\") {\n for (let j = i + 3; j < input.length; j++) {\n if (input[j] === \")\" && input[j - 1] !== \"\\\\\") {\n i = j + 1;\n break;\n }\n }\n continue;\n }\n if (removeAtomicGroup && input[i + 2] === \">\") {\n output += \"(?:\";\n i += 3;\n continue;\n }\n if (KNOWN_FLAGS.has(input[i + 2])) {\n let end = i + 3;\n for (; end < input.length; end++) {\n if (!KNOWN_FLAGS.has(input[end]))\n break;\n }\n const flagStr2 = input.slice(i + 2, end);\n const hasX = flagStr2.includes(\"x\") && flagStr2[0] !== \"-\";\n let remainFlags = [...flagStr2].filter((x) => x !== \"x\").join(\"\");\n if (!preserveFlags) {\n if (remainFlags[0] === \"-\") {\n remainFlags = remainFlags.slice(1);\n for (const flag of flagStr2) {\n flags.delete(flag);\n }\n } else {\n for (const flag of remainFlags) {\n flags.add(flag);\n }\n }\n remainFlags = \"\";\n }\n if (input[end] === \")\") {\n i = end + 1;\n if (hasX) {\n freeSpacingGlobal = true;\n }\n if (remainFlags.length) {\n output += `(?${remainFlags})`;\n }\n continue;\n } else if (input[end] === \":\") {\n i = end + 1;\n stack.unshift(char);\n if (hasX) {\n freeSpacingLocal.unshift(stack.length);\n }\n output += `(?${remainFlags}:`;\n continue;\n }\n }\n stack.unshift(char);\n output += char + input[i + 1] + input[i + 2];\n i += 3;\n } else {\n stack.unshift(char);\n output += char;\n i += 1;\n }\n continue;\n }\n if (char === \")\" && head !== \"[\") {\n if (head === \"(\")\n stack.shift();\n output += char;\n i += 1;\n continue;\n }\n if (char === \"[\") {\n if (input[i + 1] === \":\") {\n let name = \"\";\n let negated = false;\n if (input[i + 2] === \"^\") {\n negated = true;\n i += 1;\n }\n for (let j = i + 2; j < input.length; j++) {\n if (input[j] === \":\") {\n i = j + 2;\n break;\n }\n if (!input[j].match(/[a-z]/i)) {\n name = \"\";\n break;\n }\n name += input[j];\n }\n if (name) {\n let resolved = TABLE_POSIX[name];\n if (!resolved) {\n throw new RegExpConversionError(\n `Unknown posix class \"${name}\"`,\n { pattern: input, converted: output, cursor: i }\n );\n }\n if (negated)\n resolved = `^${resolved}`;\n if (head === \"[\")\n output += resolved;\n else\n output += `[${resolved}]`;\n continue;\n }\n }\n if (head !== \"[\") {\n stack.unshift(char);\n }\n if (head === \"[\" && expandNestedCharacterClass) {\n isInNestedCharClass = true;\n i += 1;\n if (input[i] === \"-\") {\n output += \"\\\\-\";\n i += 1;\n }\n continue;\n }\n output += char;\n i += 1;\n continue;\n }\n if (char === \"]\") {\n if (isInNestedCharClass) {\n isInNestedCharClass = false;\n i += 1;\n continue;\n }\n if (head === \"[\")\n stack.shift();\n output += char;\n i += 1;\n continue;\n }\n if (removePossessiveQuantifier && char === \"+\" && head !== \"[\") {\n if (\"?+}*\".includes(input[i - 1])) {\n i += 1;\n continue;\n }\n }\n if (char === \"*\" && head !== \"[\" && input[i - 1] === \"|\" && input[i - 2] !== \"\\\\\") {\n output += \"\\\\\";\n }\n if (!(freeSpacing && head !== \"[\" && char.match(/\\s/))) {\n output += char;\n }\n i += 1;\n }\n } catch (e) {\n if (e instanceof RegExpConversionError)\n throw e;\n throw new RegExpConversionError(\n `Error lowering regex at position ${i}`,\n { pattern: input, converted: output, cursor: i, cause: e }\n );\n }\n const flagStr = [...flags].join(\"\");\n if (useRegex) {\n output = rewrite(\n output,\n {\n flags: flagStr,\n unicodeSetsPlugin: null,\n disable: {\n n: true,\n v: true,\n x: true\n }\n }\n ).expression;\n }\n return {\n pattern: output,\n flags: flagStr\n };\n}\n\nexport { RegExpConversionError as R, syntaxLowering as s };\n","import { ShikiError as ShikiError$1 } from '@shikijs/types';\nexport * from '@shikijs/types';\nimport { createOnigurumaEngine as createOnigurumaEngine$1, loadWasm as loadWasm$1, getDefaultWasmLoader } from '@shikijs/engine-oniguruma';\nimport { w as warnDeprecated } from './shared/core.afb6276c.mjs';\nexport { e as enableDeprecationWarnings } from './shared/core.afb6276c.mjs';\nimport { FontStyle, INITIAL, EncodedTokenMetadata, Registry as Registry$1, Theme } from '@shikijs/vscode-textmate';\nexport { FontStyle, EncodedTokenMetadata as StackElementMetadata } from '@shikijs/vscode-textmate';\nimport { toHtml } from 'hast-util-to-html';\nexport { toHtml as hastToHtml } from 'hast-util-to-html';\nimport { createJavaScriptRegexEngine as createJavaScriptRegexEngine$1, defaultJavaScriptRegexConstructor as defaultJavaScriptRegexConstructor$1 } from '@shikijs/engine-javascript';\n\nfunction createOnigurumaEngine(options) {\n warnDeprecated(\"import `createOnigurumaEngine` from `@shikijs/engine-oniguruma` or `shiki/engine/oniguruma` instead\");\n return createOnigurumaEngine$1(options);\n}\nfunction createWasmOnigEngine(options) {\n warnDeprecated(\"import `createOnigurumaEngine` from `@shikijs/engine-oniguruma` or `shiki/engine/oniguruma` instead\");\n return createOnigurumaEngine$1(options);\n}\nfunction loadWasm(options) {\n warnDeprecated(\"import `loadWasm` from `@shikijs/engine-oniguruma` or `shiki/engine/oniguruma` instead\");\n return loadWasm$1(options);\n}\n\nfunction toArray(x) {\n return Array.isArray(x) ? x : [x];\n}\nfunction splitLines(code, preserveEnding = false) {\n const parts = code.split(/(\\r?\\n)/g);\n let index = 0;\n const lines = [];\n for (let i = 0; i < parts.length; i += 2) {\n const line = preserveEnding ? parts[i] + (parts[i + 1] || \"\") : parts[i];\n lines.push([line, index]);\n index += parts[i].length;\n index += parts[i + 1]?.length || 0;\n }\n return lines;\n}\nfunction isPlainLang(lang) {\n return !lang || [\"plaintext\", \"txt\", \"text\", \"plain\"].includes(lang);\n}\nfunction isSpecialLang(lang) {\n return lang === \"ansi\" || isPlainLang(lang);\n}\nfunction isNoneTheme(theme) {\n return theme === \"none\";\n}\nfunction isSpecialTheme(theme) {\n return isNoneTheme(theme);\n}\nfunction addClassToHast(node, className) {\n var _a;\n if (!className)\n return node;\n node.properties || (node.properties = {});\n (_a = node.properties).class || (_a.class = []);\n if (typeof node.properties.class === \"string\")\n node.properties.class = node.properties.class.split(/\\s+/g);\n if (!Array.isArray(node.properties.class))\n node.properties.class = [];\n const targets = Array.isArray(className) ? className : className.split(/\\s+/g);\n for (const c of targets) {\n if (c && !node.properties.class.includes(c))\n node.properties.class.push(c);\n }\n return node;\n}\nfunction splitToken(token, offsets) {\n let lastOffset = 0;\n const tokens = [];\n for (const offset of offsets) {\n if (offset > lastOffset) {\n tokens.push({\n ...token,\n content: token.content.slice(lastOffset, offset),\n offset: token.offset + lastOffset\n });\n }\n lastOffset = offset;\n }\n if (lastOffset < token.content.length) {\n tokens.push({\n ...token,\n content: token.content.slice(lastOffset),\n offset: token.offset + lastOffset\n });\n }\n return tokens;\n}\nfunction splitTokens(tokens, breakpoints) {\n const sorted = Array.from(breakpoints instanceof Set ? breakpoints : new Set(breakpoints)).sort((a, b) => a - b);\n if (!sorted.length)\n return tokens;\n return tokens.map((line) => {\n return line.flatMap((token) => {\n const breakpointsInToken = sorted.filter((i) => token.offset < i && i < token.offset + token.content.length).map((i) => i - token.offset).sort((a, b) => a - b);\n if (!breakpointsInToken.length)\n return token;\n return splitToken(token, breakpointsInToken);\n });\n });\n}\nasync function normalizeGetter(p) {\n return Promise.resolve(typeof p === \"function\" ? p() : p).then((r) => r.default || r);\n}\nfunction resolveColorReplacements(theme, options) {\n const replacements = typeof theme === \"string\" ? {} : { ...theme.colorReplacements };\n const themeName = typeof theme === \"string\" ? theme : theme.name;\n for (const [key, value] of Object.entries(options?.colorReplacements || {})) {\n if (typeof value === \"string\")\n replacements[key] = value;\n else if (key === themeName)\n Object.assign(replacements, value);\n }\n return replacements;\n}\nfunction applyColorReplacements(color, replacements) {\n if (!color)\n return color;\n return replacements?.[color?.toLowerCase()] || color;\n}\nfunction getTokenStyleObject(token) {\n const styles = {};\n if (token.color)\n styles.color = token.color;\n if (token.bgColor)\n styles[\"background-color\"] = token.bgColor;\n if (token.fontStyle) {\n if (token.fontStyle & FontStyle.Italic)\n styles[\"font-style\"] = \"italic\";\n if (token.fontStyle & FontStyle.Bold)\n styles[\"font-weight\"] = \"bold\";\n if (token.fontStyle & FontStyle.Underline)\n styles[\"text-decoration\"] = \"underline\";\n }\n return styles;\n}\nfunction stringifyTokenStyle(token) {\n if (typeof token === \"string\")\n return token;\n return Object.entries(token).map(([key, value]) => `${key}:${value}`).join(\";\");\n}\nfunction createPositionConverter(code) {\n const lines = splitLines(code, true).map(([line]) => line);\n function indexToPos(index) {\n if (index === code.length) {\n return {\n line: lines.length - 1,\n character: lines[lines.length - 1].length\n };\n }\n let character = index;\n let line = 0;\n for (const lineText of lines) {\n if (character < lineText.length)\n break;\n character -= lineText.length;\n line++;\n }\n return { line, character };\n }\n function posToIndex(line, character) {\n let index = 0;\n for (let i = 0; i < line; i++)\n index += lines[i].length;\n index += character;\n return index;\n }\n return {\n lines,\n indexToPos,\n posToIndex\n };\n}\n\nclass ShikiError extends Error {\n constructor(message) {\n super(message);\n this.name = \"ShikiError\";\n }\n}\n\nvar __defProp$2 = Object.defineProperty;\nvar __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField$2 = (obj, key, value) => {\n __defNormalProp$2(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nconst _grammarStateMap = /* @__PURE__ */ new WeakMap();\nfunction setLastGrammarStateToMap(keys, state) {\n _grammarStateMap.set(keys, state);\n}\nfunction getLastGrammarStateFromMap(keys) {\n return _grammarStateMap.get(keys);\n}\nclass GrammarState {\n constructor(...args) {\n /**\n * Theme to Stack mapping\n */\n __publicField$2(this, \"_stacks\", {});\n __publicField$2(this, \"lang\");\n if (args.length === 2) {\n const [stacksMap, lang] = args;\n this.lang = lang;\n this._stacks = stacksMap;\n } else {\n const [stack, lang, theme] = args;\n this.lang = lang;\n this._stacks = { [theme]: stack };\n }\n }\n get themes() {\n return Object.keys(this._stacks);\n }\n get theme() {\n return this.themes[0];\n }\n get _stack() {\n return this._stacks[this.theme];\n }\n /**\n * Static method to create a initial grammar state.\n */\n static initial(lang, themes) {\n return new GrammarState(\n Object.fromEntries(toArray(themes).map((theme) => [theme, INITIAL])),\n lang\n );\n }\n /**\n * Get the internal stack object.\n * @internal\n */\n getInternalStack(theme = this.theme) {\n return this._stacks[theme];\n }\n /**\n * @deprecated use `getScopes` instead\n */\n get scopes() {\n return getScopes(this._stacks[this.theme]);\n }\n getScopes(theme = this.theme) {\n return getScopes(this._stacks[theme]);\n }\n toJSON() {\n return {\n lang: this.lang,\n theme: this.theme,\n themes: this.themes,\n scopes: this.scopes\n };\n }\n}\nfunction getScopes(stack) {\n const scopes = [];\n const visited = /* @__PURE__ */ new Set();\n function pushScope(stack2) {\n if (visited.has(stack2))\n return;\n visited.add(stack2);\n const name = stack2?.nameScopesList?.scopeName;\n if (name)\n scopes.push(name);\n if (stack2.parent)\n pushScope(stack2.parent);\n }\n pushScope(stack);\n return scopes;\n}\nfunction getGrammarStack(state, theme) {\n if (!(state instanceof GrammarState))\n throw new ShikiError(\"Invalid grammar state\");\n return state.getInternalStack(theme);\n}\n\nfunction transformerDecorations() {\n const map = /* @__PURE__ */ new WeakMap();\n function getContext(shiki) {\n if (!map.has(shiki.meta)) {\n let normalizePosition = function(p) {\n if (typeof p === \"number\") {\n if (p < 0 || p > shiki.source.length)\n throw new ShikiError(`Invalid decoration offset: ${p}. Code length: ${shiki.source.length}`);\n return {\n ...converter.indexToPos(p),\n offset: p\n };\n } else {\n const line = converter.lines[p.line];\n if (line === void 0)\n throw new ShikiError(`Invalid decoration position ${JSON.stringify(p)}. Lines length: ${converter.lines.length}`);\n if (p.character < 0 || p.character > line.length)\n throw new ShikiError(`Invalid decoration position ${JSON.stringify(p)}. Line ${p.line} length: ${line.length}`);\n return {\n ...p,\n offset: converter.posToIndex(p.line, p.character)\n };\n }\n };\n const converter = createPositionConverter(shiki.source);\n const decorations = (shiki.options.decorations || []).map((d) => ({\n ...d,\n start: normalizePosition(d.start),\n end: normalizePosition(d.end)\n }));\n verifyIntersections(decorations);\n map.set(shiki.meta, {\n decorations,\n converter,\n source: shiki.source\n });\n }\n return map.get(shiki.meta);\n }\n return {\n name: \"shiki:decorations\",\n tokens(tokens) {\n if (!this.options.decorations?.length)\n return;\n const ctx = getContext(this);\n const breakpoints = ctx.decorations.flatMap((d) => [d.start.offset, d.end.offset]);\n const splitted = splitTokens(tokens, breakpoints);\n return splitted;\n },\n code(codeEl) {\n if (!this.options.decorations?.length)\n return;\n const ctx = getContext(this);\n const lines = Array.from(codeEl.children).filter((i) => i.type === \"element\" && i.tagName === \"span\");\n if (lines.length !== ctx.converter.lines.length)\n throw new ShikiError(`Number of lines in code element (${lines.length}) does not match the number of lines in the source (${ctx.converter.lines.length}). Failed to apply decorations.`);\n function applyLineSection(line, start, end, decoration) {\n const lineEl = lines[line];\n let text = \"\";\n let startIndex = -1;\n let endIndex = -1;\n if (start === 0)\n startIndex = 0;\n if (end === 0)\n endIndex = 0;\n if (end === Number.POSITIVE_INFINITY)\n endIndex = lineEl.children.length;\n if (startIndex === -1 || endIndex === -1) {\n for (let i = 0; i < lineEl.children.length; i++) {\n text += stringify(lineEl.children[i]);\n if (startIndex === -1 && text.length === start)\n startIndex = i + 1;\n if (endIndex === -1 && text.length === end)\n endIndex = i + 1;\n }\n }\n if (startIndex === -1)\n throw new ShikiError(`Failed to find start index for decoration ${JSON.stringify(decoration.start)}`);\n if (endIndex === -1)\n throw new ShikiError(`Failed to find end index for decoration ${JSON.stringify(decoration.end)}`);\n const children = lineEl.children.slice(startIndex, endIndex);\n if (!decoration.alwaysWrap && children.length === lineEl.children.length) {\n applyDecoration(lineEl, decoration, \"line\");\n } else if (!decoration.alwaysWrap && children.length === 1 && children[0].type === \"element\") {\n applyDecoration(children[0], decoration, \"token\");\n } else {\n const wrapper = {\n type: \"element\",\n tagName: \"span\",\n properties: {},\n children\n };\n applyDecoration(wrapper, decoration, \"wrapper\");\n lineEl.children.splice(startIndex, children.length, wrapper);\n }\n }\n function applyLine(line, decoration) {\n lines[line] = applyDecoration(lines[line], decoration, \"line\");\n }\n function applyDecoration(el, decoration, type) {\n const properties = decoration.properties || {};\n const transform = decoration.transform || ((i) => i);\n el.tagName = decoration.tagName || \"span\";\n el.properties = {\n ...el.properties,\n ...properties,\n class: el.properties.class\n };\n if (decoration.properties?.class)\n addClassToHast(el, decoration.properties.class);\n el = transform(el, type) || el;\n return el;\n }\n const lineApplies = [];\n const sorted = ctx.decorations.sort((a, b) => b.start.offset - a.start.offset);\n for (const decoration of sorted) {\n const { start, end } = decoration;\n if (start.line === end.line) {\n applyLineSection(start.line, start.character, end.character, decoration);\n } else if (start.line < end.line) {\n applyLineSection(start.line, start.character, Number.POSITIVE_INFINITY, decoration);\n for (let i = start.line + 1; i < end.line; i++)\n lineApplies.unshift(() => applyLine(i, decoration));\n applyLineSection(end.line, 0, end.character, decoration);\n }\n }\n lineApplies.forEach((i) => i());\n }\n };\n}\nfunction verifyIntersections(items) {\n for (let i = 0; i < items.length; i++) {\n const foo = items[i];\n if (foo.start.offset > foo.end.offset)\n throw new ShikiError(`Invalid decoration range: ${JSON.stringify(foo.start)} - ${JSON.stringify(foo.end)}`);\n for (let j = i + 1; j < items.length; j++) {\n const bar = items[j];\n const isFooHasBarStart = foo.start.offset < bar.start.offset && bar.start.offset < foo.end.offset;\n const isFooHasBarEnd = foo.start.offset < bar.end.offset && bar.end.offset < foo.end.offset;\n const isBarHasFooStart = bar.start.offset < foo.start.offset && foo.start.offset < bar.end.offset;\n const isBarHasFooEnd = bar.start.offset < foo.end.offset && foo.end.offset < bar.end.offset;\n if (isFooHasBarStart || isFooHasBarEnd || isBarHasFooStart || isBarHasFooEnd) {\n if (isFooHasBarEnd && isFooHasBarEnd)\n continue;\n if (isBarHasFooStart && isBarHasFooEnd)\n continue;\n throw new ShikiError(`Decorations ${JSON.stringify(foo.start)} and ${JSON.stringify(bar.start)} intersect.`);\n }\n }\n }\n}\nfunction stringify(el) {\n if (el.type === \"text\")\n return el.value;\n if (el.type === \"element\")\n return el.children.map(stringify).join(\"\");\n return \"\";\n}\n\nconst builtInTransformers = [\n /* @__PURE__ */ transformerDecorations()\n];\nfunction getTransformers(options) {\n return [\n ...options.transformers || [],\n ...builtInTransformers\n ];\n}\n\n// src/colors.ts\nvar namedColors = [\n \"black\",\n \"red\",\n \"green\",\n \"yellow\",\n \"blue\",\n \"magenta\",\n \"cyan\",\n \"white\",\n \"brightBlack\",\n \"brightRed\",\n \"brightGreen\",\n \"brightYellow\",\n \"brightBlue\",\n \"brightMagenta\",\n \"brightCyan\",\n \"brightWhite\"\n];\n\n// src/decorations.ts\nvar decorations = {\n 1: \"bold\",\n 2: \"dim\",\n 3: \"italic\",\n 4: \"underline\",\n 7: \"reverse\",\n 9: \"strikethrough\"\n};\n\n// src/parser.ts\nfunction findSequence(value, position) {\n const nextEscape = value.indexOf(\"\\x1B[\", position);\n if (nextEscape !== -1) {\n const nextClose = value.indexOf(\"m\", nextEscape);\n return {\n sequence: value.substring(nextEscape + 2, nextClose).split(\";\"),\n startPosition: nextEscape,\n position: nextClose + 1\n };\n }\n return {\n position: value.length\n };\n}\nfunction parseColor(sequence, index) {\n let offset = 1;\n const colorMode = sequence[index + offset++];\n let color;\n if (colorMode === \"2\") {\n const rgb = [\n sequence[index + offset++],\n sequence[index + offset++],\n sequence[index + offset]\n ].map((x) => Number.parseInt(x));\n if (rgb.length === 3 && !rgb.some((x) => Number.isNaN(x))) {\n color = {\n type: \"rgb\",\n rgb\n };\n }\n } else if (colorMode === \"5\") {\n const colorIndex = Number.parseInt(sequence[index + offset]);\n if (!Number.isNaN(colorIndex)) {\n color = { type: \"table\", index: Number(colorIndex) };\n }\n }\n return [offset, color];\n}\nfunction parseSequence(sequence) {\n const commands = [];\n for (let i = 0; i < sequence.length; i++) {\n const code = sequence[i];\n const codeInt = Number.parseInt(code);\n if (Number.isNaN(codeInt))\n continue;\n if (codeInt === 0) {\n commands.push({ type: \"resetAll\" });\n } else if (codeInt <= 9) {\n const decoration = decorations[codeInt];\n if (decoration) {\n commands.push({\n type: \"setDecoration\",\n value: decorations[codeInt]\n });\n }\n } else if (codeInt <= 29) {\n const decoration = decorations[codeInt - 20];\n if (decoration) {\n commands.push({\n type: \"resetDecoration\",\n value: decoration\n });\n }\n } else if (codeInt <= 37) {\n commands.push({\n type: \"setForegroundColor\",\n value: { type: \"named\", name: namedColors[codeInt - 30] }\n });\n } else if (codeInt === 38) {\n const [offset, color] = parseColor(sequence, i);\n if (color) {\n commands.push({\n type: \"setForegroundColor\",\n value: color\n });\n }\n i += offset;\n } else if (codeInt === 39) {\n commands.push({\n type: \"resetForegroundColor\"\n });\n } else if (codeInt <= 47) {\n commands.push({\n type: \"setBackgroundColor\",\n value: { type: \"named\", name: namedColors[codeInt - 40] }\n });\n } else if (codeInt === 48) {\n const [offset, color] = parseColor(sequence, i);\n if (color) {\n commands.push({\n type: \"setBackgroundColor\",\n value: color\n });\n }\n i += offset;\n } else if (codeInt === 49) {\n commands.push({\n type: \"resetBackgroundColor\"\n });\n } else if (codeInt >= 90 && codeInt <= 97) {\n commands.push({\n type: \"setForegroundColor\",\n value: { type: \"named\", name: namedColors[codeInt - 90 + 8] }\n });\n } else if (codeInt >= 100 && codeInt <= 107) {\n commands.push({\n type: \"setBackgroundColor\",\n value: { type: \"named\", name: namedColors[codeInt - 100 + 8] }\n });\n }\n }\n return commands;\n}\nfunction createAnsiSequenceParser() {\n let foreground = null;\n let background = null;\n let decorations2 = /* @__PURE__ */ new Set();\n return {\n parse(value) {\n const tokens = [];\n let position = 0;\n do {\n const findResult = findSequence(value, position);\n const text = findResult.sequence ? value.substring(position, findResult.startPosition) : value.substring(position);\n if (text.length > 0) {\n tokens.push({\n value: text,\n foreground,\n background,\n decorations: new Set(decorations2)\n });\n }\n if (findResult.sequence) {\n const commands = parseSequence(findResult.sequence);\n for (const styleToken of commands) {\n if (styleToken.type === \"resetAll\") {\n foreground = null;\n background = null;\n decorations2.clear();\n } else if (styleToken.type === \"resetForegroundColor\") {\n foreground = null;\n } else if (styleToken.type === \"resetBackgroundColor\") {\n background = null;\n } else if (styleToken.type === \"resetDecoration\") {\n decorations2.delete(styleToken.value);\n }\n }\n for (const styleToken of commands) {\n if (styleToken.type === \"setForegroundColor\") {\n foreground = styleToken.value;\n } else if (styleToken.type === \"setBackgroundColor\") {\n background = styleToken.value;\n } else if (styleToken.type === \"setDecoration\") {\n decorations2.add(styleToken.value);\n }\n }\n }\n position = findResult.position;\n } while (position < value.length);\n return tokens;\n }\n };\n}\n\n// src/palette.ts\nvar defaultNamedColorsMap = {\n black: \"#000000\",\n red: \"#bb0000\",\n green: \"#00bb00\",\n yellow: \"#bbbb00\",\n blue: \"#0000bb\",\n magenta: \"#ff00ff\",\n cyan: \"#00bbbb\",\n white: \"#eeeeee\",\n brightBlack: \"#555555\",\n brightRed: \"#ff5555\",\n brightGreen: \"#00ff00\",\n brightYellow: \"#ffff55\",\n brightBlue: \"#5555ff\",\n brightMagenta: \"#ff55ff\",\n brightCyan: \"#55ffff\",\n brightWhite: \"#ffffff\"\n};\nfunction createColorPalette(namedColorsMap = defaultNamedColorsMap) {\n function namedColor(name) {\n return namedColorsMap[name];\n }\n function rgbColor(rgb) {\n return `#${rgb.map((x) => Math.max(0, Math.min(x, 255)).toString(16).padStart(2, \"0\")).join(\"\")}`;\n }\n let colorTable;\n function getColorTable() {\n if (colorTable) {\n return colorTable;\n }\n colorTable = [];\n for (let i = 0; i < namedColors.length; i++) {\n colorTable.push(namedColor(namedColors[i]));\n }\n let levels = [0, 95, 135, 175, 215, 255];\n for (let r = 0; r < 6; r++) {\n for (let g = 0; g < 6; g++) {\n for (let b = 0; b < 6; b++) {\n colorTable.push(rgbColor([levels[r], levels[g], levels[b]]));\n }\n }\n }\n let level = 8;\n for (let i = 0; i < 24; i++, level += 10) {\n colorTable.push(rgbColor([level, level, level]));\n }\n return colorTable;\n }\n function tableColor(index) {\n return getColorTable()[index];\n }\n function value(color) {\n switch (color.type) {\n case \"named\":\n return namedColor(color.name);\n case \"rgb\":\n return rgbColor(color.rgb);\n case \"table\":\n return tableColor(color.index);\n }\n }\n return {\n value\n };\n}\n\nfunction tokenizeAnsiWithTheme(theme, fileContents, options) {\n const colorReplacements = resolveColorReplacements(theme, options);\n const lines = splitLines(fileContents);\n const colorPalette = createColorPalette(\n Object.fromEntries(\n namedColors.map((name) => [\n name,\n theme.colors?.[`terminal.ansi${name[0].toUpperCase()}${name.substring(1)}`]\n ])\n )\n );\n const parser = createAnsiSequenceParser();\n return lines.map(\n (line) => parser.parse(line[0]).map((token) => {\n let color;\n let bgColor;\n if (token.decorations.has(\"reverse\")) {\n color = token.background ? colorPalette.value(token.background) : theme.bg;\n bgColor = token.foreground ? colorPalette.value(token.foreground) : theme.fg;\n } else {\n color = token.foreground ? colorPalette.value(token.foreground) : theme.fg;\n bgColor = token.background ? colorPalette.value(token.background) : void 0;\n }\n color = applyColorReplacements(color, colorReplacements);\n bgColor = applyColorReplacements(bgColor, colorReplacements);\n if (token.decorations.has(\"dim\"))\n color = dimColor(color);\n let fontStyle = FontStyle.None;\n if (token.decorations.has(\"bold\"))\n fontStyle |= FontStyle.Bold;\n if (token.decorations.has(\"italic\"))\n fontStyle |= FontStyle.Italic;\n if (token.decorations.has(\"underline\"))\n fontStyle |= FontStyle.Underline;\n return {\n content: token.value,\n offset: line[1],\n // TODO: more accurate offset? might need to fork ansi-sequence-parser\n color,\n bgColor,\n fontStyle\n };\n })\n );\n}\nfunction dimColor(color) {\n const hexMatch = color.match(/#([0-9a-f]{3})([0-9a-f]{3})?([0-9a-f]{2})?/);\n if (hexMatch) {\n if (hexMatch[3]) {\n const alpha = Math.round(Number.parseInt(hexMatch[3], 16) / 2).toString(16).padStart(2, \"0\");\n return `#${hexMatch[1]}${hexMatch[2]}${alpha}`;\n } else if (hexMatch[2]) {\n return `#${hexMatch[1]}${hexMatch[2]}80`;\n } else {\n return `#${Array.from(hexMatch[1]).map((x) => `${x}${x}`).join(\"\")}80`;\n }\n }\n const cssVarMatch = color.match(/var\\((--[\\w-]+-ansi-[\\w-]+)\\)/);\n if (cssVarMatch)\n return `var(${cssVarMatch[1]}-dim)`;\n return color;\n}\n\nfunction codeToTokensBase(internal, code, options = {}) {\n const {\n lang = \"text\",\n theme: themeName = internal.getLoadedThemes()[0]\n } = options;\n if (isPlainLang(lang) || isNoneTheme(themeName))\n return splitLines(code).map((line) => [{ content: line[0], offset: line[1] }]);\n const { theme, colorMap } = internal.setTheme(themeName);\n if (lang === \"ansi\")\n return tokenizeAnsiWithTheme(theme, code, options);\n const _grammar = internal.getLanguage(lang);\n if (options.grammarState) {\n if (options.grammarState.lang !== _grammar.name) {\n throw new ShikiError$1(`Grammar state language \"${options.grammarState.lang}\" does not match highlight language \"${_grammar.name}\"`);\n }\n if (!options.grammarState.themes.includes(theme.name)) {\n throw new ShikiError$1(`Grammar state themes \"${options.grammarState.themes}\" do not contain highlight theme \"${theme.name}\"`);\n }\n }\n return tokenizeWithTheme(code, _grammar, theme, colorMap, options);\n}\nfunction getLastGrammarState(...args) {\n if (args.length === 2) {\n return getLastGrammarStateFromMap(args[1]);\n }\n const [internal, code, options = {}] = args;\n const {\n lang = \"text\",\n theme: themeName = internal.getLoadedThemes()[0]\n } = options;\n if (isPlainLang(lang) || isNoneTheme(themeName))\n throw new ShikiError$1(\"Plain language does not have grammar state\");\n if (lang === \"ansi\")\n throw new ShikiError$1(\"ANSI language does not have grammar state\");\n const { theme, colorMap } = internal.setTheme(themeName);\n const _grammar = internal.getLanguage(lang);\n return new GrammarState(\n _tokenizeWithTheme(code, _grammar, theme, colorMap, options).stateStack,\n _grammar.name,\n theme.name\n );\n}\nfunction tokenizeWithTheme(code, grammar, theme, colorMap, options) {\n const result = _tokenizeWithTheme(code, grammar, theme, colorMap, options);\n const grammarState = new GrammarState(\n _tokenizeWithTheme(code, grammar, theme, colorMap, options).stateStack,\n grammar.name,\n theme.name\n );\n setLastGrammarStateToMap(result.tokens, grammarState);\n return result.tokens;\n}\nfunction _tokenizeWithTheme(code, grammar, theme, colorMap, options) {\n const colorReplacements = resolveColorReplacements(theme, options);\n const {\n tokenizeMaxLineLength = 0,\n tokenizeTimeLimit = 500\n } = options;\n const lines = splitLines(code);\n let stateStack = options.grammarState ? getGrammarStack(options.grammarState, theme.name) ?? INITIAL : options.grammarContextCode != null ? _tokenizeWithTheme(\n options.grammarContextCode,\n grammar,\n theme,\n colorMap,\n {\n ...options,\n grammarState: void 0,\n grammarContextCode: void 0\n }\n ).stateStack : INITIAL;\n let actual = [];\n const final = [];\n for (let i = 0, len = lines.length; i < len; i++) {\n const [line, lineOffset] = lines[i];\n if (line === \"\") {\n actual = [];\n final.push([]);\n continue;\n }\n if (tokenizeMaxLineLength > 0 && line.length >= tokenizeMaxLineLength) {\n actual = [];\n final.push([{\n content: line,\n offset: lineOffset,\n color: \"\",\n fontStyle: 0\n }]);\n continue;\n }\n let resultWithScopes;\n let tokensWithScopes;\n let tokensWithScopesIndex;\n if (options.includeExplanation) {\n resultWithScopes = grammar.tokenizeLine(line, stateStack);\n tokensWithScopes = resultWithScopes.tokens;\n tokensWithScopesIndex = 0;\n }\n const result = grammar.tokenizeLine2(line, stateStack, tokenizeTimeLimit);\n const tokensLength = result.tokens.length / 2;\n for (let j = 0; j < tokensLength; j++) {\n const startIndex = result.tokens[2 * j];\n const nextStartIndex = j + 1 < tokensLength ? result.tokens[2 * j + 2] : line.length;\n if (startIndex === nextStartIndex)\n continue;\n const metadata = result.tokens[2 * j + 1];\n const color = applyColorReplacements(\n colorMap[EncodedTokenMetadata.getForeground(metadata)],\n colorReplacements\n );\n const fontStyle = EncodedTokenMetadata.getFontStyle(metadata);\n const token = {\n content: line.substring(startIndex, nextStartIndex),\n offset: lineOffset + startIndex,\n color,\n fontStyle\n };\n if (options.includeExplanation) {\n const themeSettingsSelectors = [];\n if (options.includeExplanation !== \"scopeName\") {\n for (const setting of theme.settings) {\n let selectors;\n switch (typeof setting.scope) {\n case \"string\":\n selectors = setting.scope.split(/,/).map((scope) => scope.trim());\n break;\n case \"object\":\n selectors = setting.scope;\n break;\n default:\n continue;\n }\n themeSettingsSelectors.push({\n settings: setting,\n selectors: selectors.map((selector) => selector.split(/ /))\n });\n }\n }\n token.explanation = [];\n let offset = 0;\n while (startIndex + offset < nextStartIndex) {\n const tokenWithScopes = tokensWithScopes[tokensWithScopesIndex];\n const tokenWithScopesText = line.substring(\n tokenWithScopes.startIndex,\n tokenWithScopes.endIndex\n );\n offset += tokenWithScopesText.length;\n token.explanation.push({\n content: tokenWithScopesText,\n scopes: options.includeExplanation === \"scopeName\" ? explainThemeScopesNameOnly(\n tokenWithScopes.scopes\n ) : explainThemeScopesFull(\n themeSettingsSelectors,\n tokenWithScopes.scopes\n )\n });\n tokensWithScopesIndex += 1;\n }\n }\n actual.push(token);\n }\n final.push(actual);\n actual = [];\n stateStack = result.ruleStack;\n }\n return {\n tokens: final,\n stateStack\n };\n}\nfunction explainThemeScopesNameOnly(scopes) {\n return scopes.map((scope) => ({ scopeName: scope }));\n}\nfunction explainThemeScopesFull(themeSelectors, scopes) {\n const result = [];\n for (let i = 0, len = scopes.length; i < len; i++) {\n const scope = scopes[i];\n result[i] = {\n scopeName: scope,\n themeMatches: explainThemeScope(themeSelectors, scope, scopes.slice(0, i))\n };\n }\n return result;\n}\nfunction matchesOne(selector, scope) {\n return selector === scope || scope.substring(0, selector.length) === selector && scope[selector.length] === \".\";\n}\nfunction matches(selectors, scope, parentScopes) {\n if (!matchesOne(selectors[selectors.length - 1], scope))\n return false;\n let selectorParentIndex = selectors.length - 2;\n let parentIndex = parentScopes.length - 1;\n while (selectorParentIndex >= 0 && parentIndex >= 0) {\n if (matchesOne(selectors[selectorParentIndex], parentScopes[parentIndex]))\n selectorParentIndex -= 1;\n parentIndex -= 1;\n }\n if (selectorParentIndex === -1)\n return true;\n return false;\n}\nfunction explainThemeScope(themeSettingsSelectors, scope, parentScopes) {\n const result = [];\n for (const { selectors, settings } of themeSettingsSelectors) {\n for (const selectorPieces of selectors) {\n if (matches(selectorPieces, scope, parentScopes)) {\n result.push(settings);\n break;\n }\n }\n }\n return result;\n}\n\nfunction codeToTokensWithThemes(internal, code, options) {\n const themes = Object.entries(options.themes).filter((i) => i[1]).map((i) => ({ color: i[0], theme: i[1] }));\n const themedTokens = themes.map((t) => {\n const tokens2 = codeToTokensBase(internal, code, {\n ...options,\n theme: t.theme\n });\n const state = getLastGrammarStateFromMap(tokens2);\n const theme = typeof t.theme === \"string\" ? t.theme : t.theme.name;\n return {\n tokens: tokens2,\n state,\n theme\n };\n });\n const tokens = syncThemesTokenization(\n ...themedTokens.map((i) => i.tokens)\n );\n const mergedTokens = tokens[0].map(\n (line, lineIdx) => line.map((_token, tokenIdx) => {\n const mergedToken = {\n content: _token.content,\n variants: {},\n offset: _token.offset\n };\n if (\"includeExplanation\" in options && options.includeExplanation) {\n mergedToken.explanation = _token.explanation;\n }\n tokens.forEach((t, themeIdx) => {\n const {\n content: _,\n explanation: __,\n offset: ___,\n ...styles\n } = t[lineIdx][tokenIdx];\n mergedToken.variants[themes[themeIdx].color] = styles;\n });\n return mergedToken;\n })\n );\n const mergedGrammarState = themedTokens[0].state ? new GrammarState(\n Object.fromEntries(themedTokens.map((s) => [s.theme, s.state?.getInternalStack(s.theme)])),\n themedTokens[0].state.lang\n ) : void 0;\n if (mergedGrammarState)\n setLastGrammarStateToMap(mergedTokens, mergedGrammarState);\n return mergedTokens;\n}\nfunction syncThemesTokenization(...themes) {\n const outThemes = themes.map(() => []);\n const count = themes.length;\n for (let i = 0; i < themes[0].length; i++) {\n const lines = themes.map((t) => t[i]);\n const outLines = outThemes.map(() => []);\n outThemes.forEach((t, i2) => t.push(outLines[i2]));\n const indexes = lines.map(() => 0);\n const current = lines.map((l) => l[0]);\n while (current.every((t) => t)) {\n const minLength = Math.min(...current.map((t) => t.content.length));\n for (let n = 0; n < count; n++) {\n const token = current[n];\n if (token.content.length === minLength) {\n outLines[n].push(token);\n indexes[n] += 1;\n current[n] = lines[n][indexes[n]];\n } else {\n outLines[n].push({\n ...token,\n content: token.content.slice(0, minLength)\n });\n current[n] = {\n ...token,\n content: token.content.slice(minLength),\n offset: token.offset + minLength\n };\n }\n }\n }\n }\n return outThemes;\n}\n\nfunction codeToTokens(internal, code, options) {\n let bg;\n let fg;\n let tokens;\n let themeName;\n let rootStyle;\n let grammarState;\n if (\"themes\" in options) {\n const {\n defaultColor = \"light\",\n cssVariablePrefix = \"--shiki-\"\n } = options;\n const themes = Object.entries(options.themes).filter((i) => i[1]).map((i) => ({ color: i[0], theme: i[1] })).sort((a, b) => a.color === defaultColor ? -1 : b.color === defaultColor ? 1 : 0);\n if (themes.length === 0)\n throw new ShikiError$1(\"`themes` option must not be empty\");\n const themeTokens = codeToTokensWithThemes(\n internal,\n code,\n options\n );\n grammarState = getLastGrammarStateFromMap(themeTokens);\n if (defaultColor && !themes.find((t) => t.color === defaultColor))\n throw new ShikiError$1(`\\`themes\\` option must contain the defaultColor key \\`${defaultColor}\\``);\n const themeRegs = themes.map((t) => internal.getTheme(t.theme));\n const themesOrder = themes.map((t) => t.color);\n tokens = themeTokens.map((line) => line.map((token) => mergeToken(token, themesOrder, cssVariablePrefix, defaultColor)));\n if (grammarState)\n setLastGrammarStateToMap(tokens, grammarState);\n const themeColorReplacements = themes.map((t) => resolveColorReplacements(t.theme, options));\n fg = themes.map((t, idx) => (idx === 0 && defaultColor ? \"\" : `${cssVariablePrefix + t.color}:`) + (applyColorReplacements(themeRegs[idx].fg, themeColorReplacements[idx]) || \"inherit\")).join(\";\");\n bg = themes.map((t, idx) => (idx === 0 && defaultColor ? \"\" : `${cssVariablePrefix + t.color}-bg:`) + (applyColorReplacements(themeRegs[idx].bg, themeColorReplacements[idx]) || \"inherit\")).join(\";\");\n themeName = `shiki-themes ${themeRegs.map((t) => t.name).join(\" \")}`;\n rootStyle = defaultColor ? void 0 : [fg, bg].join(\";\");\n } else if (\"theme\" in options) {\n const colorReplacements = resolveColorReplacements(options.theme, options);\n tokens = codeToTokensBase(\n internal,\n code,\n options\n );\n const _theme = internal.getTheme(options.theme);\n bg = applyColorReplacements(_theme.bg, colorReplacements);\n fg = applyColorReplacements(_theme.fg, colorReplacements);\n themeName = _theme.name;\n grammarState = getLastGrammarStateFromMap(tokens);\n } else {\n throw new ShikiError$1(\"Invalid options, either `theme` or `themes` must be provided\");\n }\n return {\n tokens,\n fg,\n bg,\n themeName,\n rootStyle,\n grammarState\n };\n}\nfunction mergeToken(merged, variantsOrder, cssVariablePrefix, defaultColor) {\n const token = {\n content: merged.content,\n explanation: merged.explanation,\n offset: merged.offset\n };\n const styles = variantsOrder.map((t) => getTokenStyleObject(merged.variants[t]));\n const styleKeys = new Set(styles.flatMap((t) => Object.keys(t)));\n const mergedStyles = {};\n styles.forEach((cur, idx) => {\n for (const key of styleKeys) {\n const value = cur[key] || \"inherit\";\n if (idx === 0 && defaultColor) {\n mergedStyles[key] = value;\n } else {\n const keyName = key === \"color\" ? \"\" : key === \"background-color\" ? \"-bg\" : `-${key}`;\n const varKey = cssVariablePrefix + variantsOrder[idx] + (key === \"color\" ? \"\" : keyName);\n mergedStyles[varKey] = value;\n }\n }\n });\n token.htmlStyle = mergedStyles;\n return token;\n}\n\nfunction codeToHast(internal, code, options, transformerContext = {\n meta: {},\n options,\n codeToHast: (_code, _options) => codeToHast(internal, _code, _options),\n codeToTokens: (_code, _options) => codeToTokens(internal, _code, _options)\n}) {\n let input = code;\n for (const transformer of getTransformers(options))\n input = transformer.preprocess?.call(transformerContext, input, options) || input;\n let {\n tokens,\n fg,\n bg,\n themeName,\n rootStyle,\n grammarState\n } = codeToTokens(internal, input, options);\n const {\n mergeWhitespaces = true\n } = options;\n if (mergeWhitespaces === true)\n tokens = mergeWhitespaceTokens(tokens);\n else if (mergeWhitespaces === \"never\")\n tokens = splitWhitespaceTokens(tokens);\n const contextSource = {\n ...transformerContext,\n get source() {\n return input;\n }\n };\n for (const transformer of getTransformers(options))\n tokens = transformer.tokens?.call(contextSource, tokens) || tokens;\n return tokensToHast(\n tokens,\n {\n ...options,\n fg,\n bg,\n themeName,\n rootStyle\n },\n contextSource,\n grammarState\n );\n}\nfunction tokensToHast(tokens, options, transformerContext, grammarState = getLastGrammarStateFromMap(tokens)) {\n const transformers = getTransformers(options);\n const lines = [];\n const root = {\n type: \"root\",\n children: []\n };\n const {\n structure = \"classic\",\n tabindex = \"0\"\n } = options;\n let preNode = {\n type: \"element\",\n tagName: \"pre\",\n properties: {\n class: `shiki ${options.themeName || \"\"}`,\n style: options.rootStyle || `background-color:${options.bg};color:${options.fg}`,\n ...tabindex !== false && tabindex != null ? {\n tabindex: tabindex.toString()\n } : {},\n ...Object.fromEntries(\n Array.from(\n Object.entries(options.meta || {})\n ).filter(([key]) => !key.startsWith(\"_\"))\n )\n },\n children: []\n };\n let codeNode = {\n type: \"element\",\n tagName: \"code\",\n properties: {},\n children: lines\n };\n const lineNodes = [];\n const context = {\n ...transformerContext,\n structure,\n addClassToHast,\n get source() {\n return transformerContext.source;\n },\n get tokens() {\n return tokens;\n },\n get options() {\n return options;\n },\n get root() {\n return root;\n },\n get pre() {\n return preNode;\n },\n get code() {\n return codeNode;\n },\n get lines() {\n return lineNodes;\n }\n };\n tokens.forEach((line, idx) => {\n if (idx) {\n if (structure === \"inline\")\n root.children.push({ type: \"element\", tagName: \"br\", properties: {}, children: [] });\n else if (structure === \"classic\")\n lines.push({ type: \"text\", value: \"\\n\" });\n }\n let lineNode = {\n type: \"element\",\n tagName: \"span\",\n properties: { class: \"line\" },\n children: []\n };\n let col = 0;\n for (const token of line) {\n let tokenNode = {\n type: \"element\",\n tagName: \"span\",\n properties: {\n ...token.htmlAttrs\n },\n children: [{ type: \"text\", value: token.content }]\n };\n if (typeof token.htmlStyle === \"string\")\n warnDeprecated(\"`htmlStyle` as a string is deprecated. Use an object instead.\");\n const style = stringifyTokenStyle(token.htmlStyle || getTokenStyleObject(token));\n if (style)\n tokenNode.properties.style = style;\n for (const transformer of transformers)\n tokenNode = transformer?.span?.call(context, tokenNode, idx + 1, col, lineNode, token) || tokenNode;\n if (structure === \"inline\")\n root.children.push(tokenNode);\n else if (structure === \"classic\")\n lineNode.children.push(tokenNode);\n col += token.content.length;\n }\n if (structure === \"classic\") {\n for (const transformer of transformers)\n lineNode = transformer?.line?.call(context, lineNode, idx + 1) || lineNode;\n lineNodes.push(lineNode);\n lines.push(lineNode);\n }\n });\n if (structure === \"classic\") {\n for (const transformer of transformers)\n codeNode = transformer?.code?.call(context, codeNode) || codeNode;\n preNode.children.push(codeNode);\n for (const transformer of transformers)\n preNode = transformer?.pre?.call(context, preNode) || preNode;\n root.children.push(preNode);\n }\n let result = root;\n for (const transformer of transformers)\n result = transformer?.root?.call(context, result) || result;\n if (grammarState)\n setLastGrammarStateToMap(result, grammarState);\n return result;\n}\nfunction mergeWhitespaceTokens(tokens) {\n return tokens.map((line) => {\n const newLine = [];\n let carryOnContent = \"\";\n let firstOffset = 0;\n line.forEach((token, idx) => {\n const isUnderline = token.fontStyle && token.fontStyle & FontStyle.Underline;\n const couldMerge = !isUnderline;\n if (couldMerge && token.content.match(/^\\s+$/) && line[idx + 1]) {\n if (!firstOffset)\n firstOffset = token.offset;\n carryOnContent += token.content;\n } else {\n if (carryOnContent) {\n if (couldMerge) {\n newLine.push({\n ...token,\n offset: firstOffset,\n content: carryOnContent + token.content\n });\n } else {\n newLine.push(\n {\n content: carryOnContent,\n offset: firstOffset\n },\n token\n );\n }\n firstOffset = 0;\n carryOnContent = \"\";\n } else {\n newLine.push(token);\n }\n }\n });\n return newLine;\n });\n}\nfunction splitWhitespaceTokens(tokens) {\n return tokens.map((line) => {\n return line.flatMap((token) => {\n if (token.content.match(/^\\s+$/))\n return token;\n const match = token.content.match(/^(\\s*)(.*?)(\\s*)$/);\n if (!match)\n return token;\n const [, leading, content, trailing] = match;\n if (!leading && !trailing)\n return token;\n const expanded = [{\n ...token,\n offset: token.offset + leading.length,\n content\n }];\n if (leading) {\n expanded.unshift({\n content: leading,\n offset: token.offset\n });\n }\n if (trailing) {\n expanded.push({\n content: trailing,\n offset: token.offset + leading.length + content.length\n });\n }\n return expanded;\n });\n });\n}\n\nfunction codeToHtml(internal, code, options) {\n const context = {\n meta: {},\n options,\n codeToHast: (_code, _options) => codeToHast(internal, _code, _options),\n codeToTokens: (_code, _options) => codeToTokens(internal, _code, _options)\n };\n let result = toHtml(codeToHast(internal, code, options, context));\n for (const transformer of getTransformers(options))\n result = transformer.postprocess?.call(context, result, options) || result;\n return result;\n}\n\nconst VSCODE_FALLBACK_EDITOR_FG = { light: \"#333333\", dark: \"#bbbbbb\" };\nconst VSCODE_FALLBACK_EDITOR_BG = { light: \"#fffffe\", dark: \"#1e1e1e\" };\nconst RESOLVED_KEY = \"__shiki_resolved\";\nfunction normalizeTheme(rawTheme) {\n if (rawTheme?.[RESOLVED_KEY])\n return rawTheme;\n const theme = {\n ...rawTheme\n };\n if (theme.tokenColors && !theme.settings) {\n theme.settings = theme.tokenColors;\n delete theme.tokenColors;\n }\n theme.type || (theme.type = \"dark\");\n theme.colorReplacements = { ...theme.colorReplacements };\n theme.settings || (theme.settings = []);\n let { bg, fg } = theme;\n if (!bg || !fg) {\n const globalSetting = theme.settings ? theme.settings.find((s) => !s.name && !s.scope) : void 0;\n if (globalSetting?.settings?.foreground)\n fg = globalSetting.settings.foreground;\n if (globalSetting?.settings?.background)\n bg = globalSetting.settings.background;\n if (!fg && theme?.colors?.[\"editor.foreground\"])\n fg = theme.colors[\"editor.foreground\"];\n if (!bg && theme?.colors?.[\"editor.background\"])\n bg = theme.colors[\"editor.background\"];\n if (!fg)\n fg = theme.type === \"light\" ? VSCODE_FALLBACK_EDITOR_FG.light : VSCODE_FALLBACK_EDITOR_FG.dark;\n if (!bg)\n bg = theme.type === \"light\" ? VSCODE_FALLBACK_EDITOR_BG.light : VSCODE_FALLBACK_EDITOR_BG.dark;\n theme.fg = fg;\n theme.bg = bg;\n }\n if (!(theme.settings[0] && theme.settings[0].settings && !theme.settings[0].scope)) {\n theme.settings.unshift({\n settings: {\n foreground: theme.fg,\n background: theme.bg\n }\n });\n }\n let replacementCount = 0;\n const replacementMap = /* @__PURE__ */ new Map();\n function getReplacementColor(value) {\n if (replacementMap.has(value))\n return replacementMap.get(value);\n replacementCount += 1;\n const hex = `#${replacementCount.toString(16).padStart(8, \"0\").toLowerCase()}`;\n if (theme.colorReplacements?.[`#${hex}`])\n return getReplacementColor(value);\n replacementMap.set(value, hex);\n return hex;\n }\n theme.settings = theme.settings.map((setting) => {\n const replaceFg = setting.settings?.foreground && !setting.settings.foreground.startsWith(\"#\");\n const replaceBg = setting.settings?.background && !setting.settings.background.startsWith(\"#\");\n if (!replaceFg && !replaceBg)\n return setting;\n const clone = {\n ...setting,\n settings: {\n ...setting.settings\n }\n };\n if (replaceFg) {\n const replacement = getReplacementColor(setting.settings.foreground);\n theme.colorReplacements[replacement] = setting.settings.foreground;\n clone.settings.foreground = replacement;\n }\n if (replaceBg) {\n const replacement = getReplacementColor(setting.settings.background);\n theme.colorReplacements[replacement] = setting.settings.background;\n clone.settings.background = replacement;\n }\n return clone;\n });\n for (const key of Object.keys(theme.colors || {})) {\n if (key === \"editor.foreground\" || key === \"editor.background\" || key.startsWith(\"terminal.ansi\")) {\n if (!theme.colors[key]?.startsWith(\"#\")) {\n const replacement = getReplacementColor(theme.colors[key]);\n theme.colorReplacements[replacement] = theme.colors[key];\n theme.colors[key] = replacement;\n }\n }\n }\n Object.defineProperty(theme, RESOLVED_KEY, {\n enumerable: false,\n writable: false,\n value: true\n });\n return theme;\n}\n\nasync function resolveLangs(langs) {\n return Array.from(new Set((await Promise.all(\n langs.filter((l) => !isSpecialLang(l)).map(async (lang) => await normalizeGetter(lang).then((r) => Array.isArray(r) ? r : [r]))\n )).flat()));\n}\nasync function resolveThemes(themes) {\n const resolved = await Promise.all(\n themes.map(\n async (theme) => isSpecialTheme(theme) ? null : normalizeTheme(await normalizeGetter(theme))\n )\n );\n return resolved.filter((i) => !!i);\n}\n\nvar __defProp$1 = Object.defineProperty;\nvar __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField$1 = (obj, key, value) => {\n __defNormalProp$1(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nclass Registry extends Registry$1 {\n constructor(_resolver, _themes, _langs, _alias = {}) {\n super(_resolver);\n this._resolver = _resolver;\n this._themes = _themes;\n this._langs = _langs;\n this._alias = _alias;\n __publicField$1(this, \"_resolvedThemes\", /* @__PURE__ */ new Map());\n __publicField$1(this, \"_resolvedGrammars\", /* @__PURE__ */ new Map());\n __publicField$1(this, \"_langMap\", /* @__PURE__ */ new Map());\n __publicField$1(this, \"_langGraph\", /* @__PURE__ */ new Map());\n __publicField$1(this, \"_textmateThemeCache\", /* @__PURE__ */ new WeakMap());\n __publicField$1(this, \"_loadedThemesCache\", null);\n __publicField$1(this, \"_loadedLanguagesCache\", null);\n this._themes.map((t) => this.loadTheme(t));\n this.loadLanguages(this._langs);\n }\n getTheme(theme) {\n if (typeof theme === \"string\")\n return this._resolvedThemes.get(theme);\n else\n return this.loadTheme(theme);\n }\n loadTheme(theme) {\n const _theme = normalizeTheme(theme);\n if (_theme.name) {\n this._resolvedThemes.set(_theme.name, _theme);\n this._loadedThemesCache = null;\n }\n return _theme;\n }\n getLoadedThemes() {\n if (!this._loadedThemesCache)\n this._loadedThemesCache = [...this._resolvedThemes.keys()];\n return this._loadedThemesCache;\n }\n // Override and re-implement this method to cache the textmate themes as `TextMateTheme.createFromRawTheme`\n // is expensive. Themes can switch often especially for dual-theme support.\n //\n // The parent class also accepts `colorMap` as the second parameter, but since we don't use that,\n // we omit here so it's easier to cache the themes.\n setTheme(theme) {\n let textmateTheme = this._textmateThemeCache.get(theme);\n if (!textmateTheme) {\n textmateTheme = Theme.createFromRawTheme(theme);\n this._textmateThemeCache.set(theme, textmateTheme);\n }\n this._syncRegistry.setTheme(textmateTheme);\n }\n getGrammar(name) {\n if (this._alias[name]) {\n const resolved = /* @__PURE__ */ new Set([name]);\n while (this._alias[name]) {\n name = this._alias[name];\n if (resolved.has(name))\n throw new ShikiError(`Circular alias \\`${Array.from(resolved).join(\" -> \")} -> ${name}\\``);\n resolved.add(name);\n }\n }\n return this._resolvedGrammars.get(name);\n }\n loadLanguage(lang) {\n if (this.getGrammar(lang.name))\n return;\n const embeddedLazilyBy = new Set(\n [...this._langMap.values()].filter((i) => i.embeddedLangsLazy?.includes(lang.name))\n );\n this._resolver.addLanguage(lang);\n const grammarConfig = {\n balancedBracketSelectors: lang.balancedBracketSelectors || [\"*\"],\n unbalancedBracketSelectors: lang.unbalancedBracketSelectors || []\n };\n this._syncRegistry._rawGrammars.set(lang.scopeName, lang);\n const g = this.loadGrammarWithConfiguration(lang.scopeName, 1, grammarConfig);\n g.name = lang.name;\n this._resolvedGrammars.set(lang.name, g);\n if (lang.aliases) {\n lang.aliases.forEach((alias) => {\n this._alias[alias] = lang.name;\n });\n }\n this._loadedLanguagesCache = null;\n if (embeddedLazilyBy.size) {\n for (const e of embeddedLazilyBy) {\n this._resolvedGrammars.delete(e.name);\n this._loadedLanguagesCache = null;\n this._syncRegistry?._injectionGrammars?.delete(e.scopeName);\n this._syncRegistry?._grammars?.delete(e.scopeName);\n this.loadLanguage(this._langMap.get(e.name));\n }\n }\n }\n dispose() {\n super.dispose();\n this._resolvedThemes.clear();\n this._resolvedGrammars.clear();\n this._langMap.clear();\n this._langGraph.clear();\n this._loadedThemesCache = null;\n }\n loadLanguages(langs) {\n for (const lang of langs)\n this.resolveEmbeddedLanguages(lang);\n const langsGraphArray = Array.from(this._langGraph.entries());\n const missingLangs = langsGraphArray.filter(([_, lang]) => !lang);\n if (missingLangs.length) {\n const dependents = langsGraphArray.filter(([_, lang]) => lang && lang.embeddedLangs?.some((l) => missingLangs.map(([name]) => name).includes(l))).filter((lang) => !missingLangs.includes(lang));\n throw new ShikiError(`Missing languages ${missingLangs.map(([name]) => `\\`${name}\\``).join(\", \")}, required by ${dependents.map(([name]) => `\\`${name}\\``).join(\", \")}`);\n }\n for (const [_, lang] of langsGraphArray)\n this._resolver.addLanguage(lang);\n for (const [_, lang] of langsGraphArray)\n this.loadLanguage(lang);\n }\n getLoadedLanguages() {\n if (!this._loadedLanguagesCache) {\n this._loadedLanguagesCache = [\n .../* @__PURE__ */ new Set([...this._resolvedGrammars.keys(), ...Object.keys(this._alias)])\n ];\n }\n return this._loadedLanguagesCache;\n }\n resolveEmbeddedLanguages(lang) {\n this._langMap.set(lang.name, lang);\n this._langGraph.set(lang.name, lang);\n if (lang.embeddedLangs) {\n for (const embeddedLang of lang.embeddedLangs)\n this._langGraph.set(embeddedLang, this._langMap.get(embeddedLang));\n }\n }\n}\n\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => {\n __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nclass Resolver {\n constructor(engine, langs) {\n __publicField(this, \"_langs\", /* @__PURE__ */ new Map());\n __publicField(this, \"_scopeToLang\", /* @__PURE__ */ new Map());\n __publicField(this, \"_injections\", /* @__PURE__ */ new Map());\n __publicField(this, \"_onigLib\");\n this._onigLib = {\n createOnigScanner: (patterns) => engine.createScanner(patterns),\n createOnigString: (s) => engine.createString(s)\n };\n langs.forEach((i) => this.addLanguage(i));\n }\n get onigLib() {\n return this._onigLib;\n }\n getLangRegistration(langIdOrAlias) {\n return this._langs.get(langIdOrAlias);\n }\n loadGrammar(scopeName) {\n return this._scopeToLang.get(scopeName);\n }\n addLanguage(l) {\n this._langs.set(l.name, l);\n if (l.aliases) {\n l.aliases.forEach((a) => {\n this._langs.set(a, l);\n });\n }\n this._scopeToLang.set(l.scopeName, l);\n if (l.injectTo) {\n l.injectTo.forEach((i) => {\n if (!this._injections.get(i))\n this._injections.set(i, []);\n this._injections.get(i).push(l.scopeName);\n });\n }\n }\n getInjections(scopeName) {\n const scopeParts = scopeName.split(\".\");\n let injections = [];\n for (let i = 1; i <= scopeParts.length; i++) {\n const subScopeName = scopeParts.slice(0, i).join(\".\");\n injections = [...injections, ...this._injections.get(subScopeName) || []];\n }\n return injections;\n }\n}\n\nlet instancesCount = 0;\nfunction createShikiInternalSync(options) {\n instancesCount += 1;\n if (options.warnings !== false && instancesCount >= 10 && instancesCount % 10 === 0)\n console.warn(`[Shiki] ${instancesCount} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \\`highlighter.dispose()\\` to release unused instances.`);\n let isDisposed = false;\n if (!options.engine)\n throw new ShikiError(\"`engine` option is required for synchronous mode\");\n const langs = (options.langs || []).flat(1);\n const themes = (options.themes || []).flat(1).map(normalizeTheme);\n const resolver = new Resolver(options.engine, langs);\n const _registry = new Registry(resolver, themes, langs, options.langAlias);\n let _lastTheme;\n function getLanguage(name) {\n ensureNotDisposed();\n const _lang = _registry.getGrammar(typeof name === \"string\" ? name : name.name);\n if (!_lang)\n throw new ShikiError(`Language \\`${name}\\` not found, you may need to load it first`);\n return _lang;\n }\n function getTheme(name) {\n if (name === \"none\")\n return { bg: \"\", fg: \"\", name: \"none\", settings: [], type: \"dark\" };\n ensureNotDisposed();\n const _theme = _registry.getTheme(name);\n if (!_theme)\n throw new ShikiError(`Theme \\`${name}\\` not found, you may need to load it first`);\n return _theme;\n }\n function setTheme(name) {\n ensureNotDisposed();\n const theme = getTheme(name);\n if (_lastTheme !== name) {\n _registry.setTheme(theme);\n _lastTheme = name;\n }\n const colorMap = _registry.getColorMap();\n return {\n theme,\n colorMap\n };\n }\n function getLoadedThemes() {\n ensureNotDisposed();\n return _registry.getLoadedThemes();\n }\n function getLoadedLanguages() {\n ensureNotDisposed();\n return _registry.getLoadedLanguages();\n }\n function loadLanguageSync(...langs2) {\n ensureNotDisposed();\n _registry.loadLanguages(langs2.flat(1));\n }\n async function loadLanguage(...langs2) {\n return loadLanguageSync(await resolveLangs(langs2));\n }\n function loadThemeSync(...themes2) {\n ensureNotDisposed();\n for (const theme of themes2.flat(1)) {\n _registry.loadTheme(theme);\n }\n }\n async function loadTheme(...themes2) {\n ensureNotDisposed();\n return loadThemeSync(await resolveThemes(themes2));\n }\n function ensureNotDisposed() {\n if (isDisposed)\n throw new ShikiError(\"Shiki instance has been disposed\");\n }\n function dispose() {\n if (isDisposed)\n return;\n isDisposed = true;\n _registry.dispose();\n instancesCount -= 1;\n }\n return {\n setTheme,\n getTheme,\n getLanguage,\n getLoadedThemes,\n getLoadedLanguages,\n loadLanguage,\n loadLanguageSync,\n loadTheme,\n loadThemeSync,\n dispose,\n [Symbol.dispose]: dispose\n };\n}\n\nasync function createShikiInternal(options = {}) {\n if (options.loadWasm) {\n warnDeprecated(\"`loadWasm` option is deprecated. Use `engine: createOnigurumaEngine(loadWasm)` instead.\");\n }\n const [\n themes,\n langs,\n engine\n ] = await Promise.all([\n resolveThemes(options.themes || []),\n resolveLangs(options.langs || []),\n options.engine || createOnigurumaEngine$1(options.loadWasm || getDefaultWasmLoader())\n ]);\n return createShikiInternalSync({\n ...options,\n loadWasm: void 0,\n themes,\n langs,\n engine\n });\n}\nfunction getShikiInternal(options = {}) {\n warnDeprecated(\"`getShikiInternal` is deprecated. Use `createShikiInternal` instead.\");\n return createShikiInternal(options);\n}\n\nasync function createHighlighterCore(options = {}) {\n const internal = await createShikiInternal(options);\n return {\n getLastGrammarState: (...args) => getLastGrammarState(internal, ...args),\n codeToTokensBase: (code, options2) => codeToTokensBase(internal, code, options2),\n codeToTokensWithThemes: (code, options2) => codeToTokensWithThemes(internal, code, options2),\n codeToTokens: (code, options2) => codeToTokens(internal, code, options2),\n codeToHast: (code, options2) => codeToHast(internal, code, options2),\n codeToHtml: (code, options2) => codeToHtml(internal, code, options2),\n ...internal,\n getInternalContext: () => internal\n };\n}\nfunction createHighlighterCoreSync(options = {}) {\n const internal = createShikiInternalSync(options);\n return {\n getLastGrammarState: (...args) => getLastGrammarState(internal, ...args),\n codeToTokensBase: (code, options2) => codeToTokensBase(internal, code, options2),\n codeToTokensWithThemes: (code, options2) => codeToTokensWithThemes(internal, code, options2),\n codeToTokens: (code, options2) => codeToTokens(internal, code, options2),\n codeToHast: (code, options2) => codeToHast(internal, code, options2),\n codeToHtml: (code, options2) => codeToHtml(internal, code, options2),\n ...internal,\n getInternalContext: () => internal\n };\n}\nfunction makeSingletonHighlighterCore(createHighlighter) {\n let _shiki;\n async function getSingletonHighlighterCore2(options = {}) {\n if (!_shiki) {\n _shiki = createHighlighter({\n ...options,\n themes: options.themes || [],\n langs: options.langs || []\n });\n return _shiki;\n } else {\n const s = await _shiki;\n await Promise.all([\n s.loadTheme(...options.themes || []),\n s.loadLanguage(...options.langs || [])\n ]);\n return s;\n }\n }\n return getSingletonHighlighterCore2;\n}\nconst getSingletonHighlighterCore = /* @__PURE__ */ makeSingletonHighlighterCore(createHighlighterCore);\nfunction getHighlighterCore(options = {}) {\n warnDeprecated(\"`getHighlighterCore` is deprecated. Use `createHighlighterCore` or `getSingletonHighlighterCore` instead.\");\n return createHighlighterCore(options);\n}\n\nfunction createdBundledHighlighter(arg1, arg2, arg3) {\n let bundledLanguages;\n let bundledThemes;\n let engine;\n if (arg2) {\n warnDeprecated(\"`createdBundledHighlighter` signature with `bundledLanguages` and `bundledThemes` is deprecated. Use the options object signature instead.\");\n bundledLanguages = arg1;\n bundledThemes = arg2;\n engine = () => createOnigurumaEngine(arg3);\n } else {\n const options = arg1;\n bundledLanguages = options.langs;\n bundledThemes = options.themes;\n engine = options.engine;\n }\n async function createHighlighter(options) {\n function resolveLang(lang) {\n if (typeof lang === \"string\") {\n if (isSpecialLang(lang))\n return [];\n const bundle = bundledLanguages[lang];\n if (!bundle)\n throw new ShikiError$1(`Language \\`${lang}\\` is not included in this bundle. You may want to load it from external source.`);\n return bundle;\n }\n return lang;\n }\n function resolveTheme(theme) {\n if (isSpecialTheme(theme))\n return \"none\";\n if (typeof theme === \"string\") {\n const bundle = bundledThemes[theme];\n if (!bundle)\n throw new ShikiError$1(`Theme \\`${theme}\\` is not included in this bundle. You may want to load it from external source.`);\n return bundle;\n }\n return theme;\n }\n const _themes = (options.themes ?? []).map((i) => resolveTheme(i));\n const langs = (options.langs ?? []).map((i) => resolveLang(i));\n const core = await createHighlighterCore({\n engine: options.engine ?? engine(),\n ...options,\n themes: _themes,\n langs\n });\n return {\n ...core,\n loadLanguage(...langs2) {\n return core.loadLanguage(...langs2.map(resolveLang));\n },\n loadTheme(...themes) {\n return core.loadTheme(...themes.map(resolveTheme));\n }\n };\n }\n return createHighlighter;\n}\nfunction makeSingletonHighlighter(createHighlighter) {\n let _shiki;\n async function getSingletonHighlighter(options = {}) {\n if (!_shiki) {\n _shiki = createHighlighter({\n ...options,\n themes: options.themes || [],\n langs: options.langs || []\n });\n return _shiki;\n } else {\n const s = await _shiki;\n await Promise.all([\n s.loadTheme(...options.themes || []),\n s.loadLanguage(...options.langs || [])\n ]);\n return s;\n }\n }\n return getSingletonHighlighter;\n}\nfunction createSingletonShorthands(createHighlighter) {\n const getSingletonHighlighter = makeSingletonHighlighter(createHighlighter);\n return {\n getSingletonHighlighter(options) {\n return getSingletonHighlighter(options);\n },\n async codeToHtml(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: \"theme\" in options ? [options.theme] : Object.values(options.themes)\n });\n return shiki.codeToHtml(code, options);\n },\n async codeToHast(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: \"theme\" in options ? [options.theme] : Object.values(options.themes)\n });\n return shiki.codeToHast(code, options);\n },\n async codeToTokens(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: \"theme\" in options ? [options.theme] : Object.values(options.themes)\n });\n return shiki.codeToTokens(code, options);\n },\n async codeToTokensBase(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: [options.theme]\n });\n return shiki.codeToTokensBase(code, options);\n },\n async codeToTokensWithThemes(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: Object.values(options.themes).filter(Boolean)\n });\n return shiki.codeToTokensWithThemes(code, options);\n },\n async getLastGrammarState(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: [options.theme]\n });\n return shiki.getLastGrammarState(code, options);\n }\n };\n}\n\nfunction createJavaScriptRegexEngine(options) {\n warnDeprecated(\"import `createJavaScriptRegexEngine` from `@shikijs/engine-javascript` or `shiki/engine/javascript` instead\");\n return createJavaScriptRegexEngine$1(options);\n}\nfunction defaultJavaScriptRegexConstructor(pattern) {\n warnDeprecated(\"import `defaultJavaScriptRegexConstructor` from `@shikijs/engine-javascript` or `shiki/engine/javascript` instead\");\n return defaultJavaScriptRegexConstructor$1(pattern);\n}\n\nfunction createCssVariablesTheme(options = {}) {\n const {\n name = \"css-variables\",\n variablePrefix = \"--shiki-\",\n fontStyle = true\n } = options;\n const variable = (name2) => {\n if (options.variableDefaults?.[name2])\n return `var(${variablePrefix}${name2}, ${options.variableDefaults[name2]})`;\n return `var(${variablePrefix}${name2})`;\n };\n const theme = {\n name,\n type: \"dark\",\n colors: {\n \"editor.foreground\": variable(\"foreground\"),\n \"editor.background\": variable(\"background\"),\n \"terminal.ansiBlack\": variable(\"ansi-black\"),\n \"terminal.ansiRed\": variable(\"ansi-red\"),\n \"terminal.ansiGreen\": variable(\"ansi-green\"),\n \"terminal.ansiYellow\": variable(\"ansi-yellow\"),\n \"terminal.ansiBlue\": variable(\"ansi-blue\"),\n \"terminal.ansiMagenta\": variable(\"ansi-magenta\"),\n \"terminal.ansiCyan\": variable(\"ansi-cyan\"),\n \"terminal.ansiWhite\": variable(\"ansi-white\"),\n \"terminal.ansiBrightBlack\": variable(\"ansi-bright-black\"),\n \"terminal.ansiBrightRed\": variable(\"ansi-bright-red\"),\n \"terminal.ansiBrightGreen\": variable(\"ansi-bright-green\"),\n \"terminal.ansiBrightYellow\": variable(\"ansi-bright-yellow\"),\n \"terminal.ansiBrightBlue\": variable(\"ansi-bright-blue\"),\n \"terminal.ansiBrightMagenta\": variable(\"ansi-bright-magenta\"),\n \"terminal.ansiBrightCyan\": variable(\"ansi-bright-cyan\"),\n \"terminal.ansiBrightWhite\": variable(\"ansi-bright-white\")\n },\n tokenColors: [\n {\n scope: [\n \"keyword.operator.accessor\",\n \"meta.group.braces.round.function.arguments\",\n \"meta.template.expression\",\n \"markup.fenced_code meta.embedded.block\"\n ],\n settings: {\n foreground: variable(\"foreground\")\n }\n },\n {\n scope: \"emphasis\",\n settings: {\n fontStyle: \"italic\"\n }\n },\n {\n scope: [\"strong\", \"markup.heading.markdown\", \"markup.bold.markdown\"],\n settings: {\n fontStyle: \"bold\"\n }\n },\n {\n scope: [\"markup.italic.markdown\"],\n settings: {\n fontStyle: \"italic\"\n }\n },\n {\n scope: \"meta.link.inline.markdown\",\n settings: {\n fontStyle: \"underline\",\n foreground: variable(\"token-link\")\n }\n },\n {\n scope: [\"string\", \"markup.fenced_code\", \"markup.inline\"],\n settings: {\n foreground: variable(\"token-string\")\n }\n },\n {\n scope: [\"comment\", \"string.quoted.docstring.multi\"],\n settings: {\n foreground: variable(\"token-comment\")\n }\n },\n {\n scope: [\n \"constant.numeric\",\n \"constant.language\",\n \"constant.other.placeholder\",\n \"constant.character.format.placeholder\",\n \"variable.language.this\",\n \"variable.other.object\",\n \"variable.other.class\",\n \"variable.other.constant\",\n \"meta.property-name\",\n \"meta.property-value\",\n \"support\"\n ],\n settings: {\n foreground: variable(\"token-constant\")\n }\n },\n {\n scope: [\n \"keyword\",\n \"storage.modifier\",\n \"storage.type\",\n \"storage.control.clojure\",\n \"entity.name.function.clojure\",\n \"entity.name.tag.yaml\",\n \"support.function.node\",\n \"support.type.property-name.json\",\n \"punctuation.separator.key-value\",\n \"punctuation.definition.template-expression\"\n ],\n settings: {\n foreground: variable(\"token-keyword\")\n }\n },\n {\n scope: \"variable.parameter.function\",\n settings: {\n foreground: variable(\"token-parameter\")\n }\n },\n {\n scope: [\n \"support.function\",\n \"entity.name.type\",\n \"entity.other.inherited-class\",\n \"meta.function-call\",\n \"meta.instance.constructor\",\n \"entity.other.attribute-name\",\n \"entity.name.function\",\n \"constant.keyword.clojure\"\n ],\n settings: {\n foreground: variable(\"token-function\")\n }\n },\n {\n scope: [\n \"entity.name.tag\",\n \"string.quoted\",\n \"string.regexp\",\n \"string.interpolated\",\n \"string.template\",\n \"string.unquoted.plain.out.yaml\",\n \"keyword.other.template\"\n ],\n settings: {\n foreground: variable(\"token-string-expression\")\n }\n },\n {\n scope: [\n \"punctuation.definition.arguments\",\n \"punctuation.definition.dict\",\n \"punctuation.separator\",\n \"meta.function-call.arguments\"\n ],\n settings: {\n foreground: variable(\"token-punctuation\")\n }\n },\n {\n // [Custom] Markdown links\n scope: [\n \"markup.underline.link\",\n \"punctuation.definition.metadata.markdown\"\n ],\n settings: {\n foreground: variable(\"token-link\")\n }\n },\n {\n // [Custom] Markdown list\n scope: [\"beginning.punctuation.definition.list.markdown\"],\n settings: {\n foreground: variable(\"token-string\")\n }\n },\n {\n // [Custom] Markdown punctuation definition brackets\n scope: [\n \"punctuation.definition.string.begin.markdown\",\n \"punctuation.definition.string.end.markdown\",\n \"string.other.link.title.markdown\",\n \"string.other.link.description.markdown\"\n ],\n settings: {\n foreground: variable(\"token-keyword\")\n }\n },\n {\n // [Custom] Diff\n scope: [\n \"markup.inserted\",\n \"meta.diff.header.to-file\",\n \"punctuation.definition.inserted\"\n ],\n settings: {\n foreground: variable(\"token-inserted\")\n }\n },\n {\n scope: [\n \"markup.deleted\",\n \"meta.diff.header.from-file\",\n \"punctuation.definition.deleted\"\n ],\n settings: {\n foreground: variable(\"token-deleted\")\n }\n },\n {\n scope: [\n \"markup.changed\",\n \"punctuation.definition.changed\"\n ],\n settings: {\n foreground: variable(\"token-changed\")\n }\n }\n ]\n };\n if (!fontStyle) {\n theme.tokenColors = theme.tokenColors?.map((tokenColor) => {\n if (tokenColor.settings?.fontStyle)\n delete tokenColor.settings.fontStyle;\n return tokenColor;\n });\n }\n return theme;\n}\n\nexport { addClassToHast, applyColorReplacements, codeToHast, codeToHtml, codeToTokens, codeToTokensBase, codeToTokensWithThemes, createCssVariablesTheme, createHighlighterCore, createHighlighterCoreSync, createJavaScriptRegexEngine, createOnigurumaEngine, createPositionConverter, createShikiInternal, createShikiInternalSync, createSingletonShorthands, createWasmOnigEngine, createdBundledHighlighter, defaultJavaScriptRegexConstructor, getHighlighterCore, getShikiInternal, getSingletonHighlighterCore, getTokenStyleObject, isNoneTheme, isPlainLang, isSpecialLang, isSpecialTheme, loadWasm, makeSingletonHighlighter, makeSingletonHighlighterCore, normalizeGetter, normalizeTheme, resolveColorReplacements, splitLines, splitToken, splitTokens, stringifyTokenStyle, toArray, tokenizeAnsiWithTheme, tokenizeWithTheme, tokensToHast, transformerDecorations, warnDeprecated };\n","/* Theme: github-dark-default */\nexport default Object.freeze(JSON.parse(\"{\\\"colors\\\":{\\\"activityBar.activeBorder\\\":\\\"#f78166\\\",\\\"activityBar.background\\\":\\\"#0d1117\\\",\\\"activityBar.border\\\":\\\"#30363d\\\",\\\"activityBar.foreground\\\":\\\"#e6edf3\\\",\\\"activityBar.inactiveForeground\\\":\\\"#7d8590\\\",\\\"activityBarBadge.background\\\":\\\"#1f6feb\\\",\\\"activityBarBadge.foreground\\\":\\\"#ffffff\\\",\\\"badge.background\\\":\\\"#1f6feb\\\",\\\"badge.foreground\\\":\\\"#ffffff\\\",\\\"breadcrumb.activeSelectionForeground\\\":\\\"#7d8590\\\",\\\"breadcrumb.focusForeground\\\":\\\"#e6edf3\\\",\\\"breadcrumb.foreground\\\":\\\"#7d8590\\\",\\\"breadcrumbPicker.background\\\":\\\"#161b22\\\",\\\"button.background\\\":\\\"#238636\\\",\\\"button.foreground\\\":\\\"#ffffff\\\",\\\"button.hoverBackground\\\":\\\"#2ea043\\\",\\\"button.secondaryBackground\\\":\\\"#282e33\\\",\\\"button.secondaryForeground\\\":\\\"#c9d1d9\\\",\\\"button.secondaryHoverBackground\\\":\\\"#30363d\\\",\\\"checkbox.background\\\":\\\"#161b22\\\",\\\"checkbox.border\\\":\\\"#30363d\\\",\\\"debugConsole.errorForeground\\\":\\\"#ffa198\\\",\\\"debugConsole.infoForeground\\\":\\\"#8b949e\\\",\\\"debugConsole.sourceForeground\\\":\\\"#e3b341\\\",\\\"debugConsole.warningForeground\\\":\\\"#d29922\\\",\\\"debugConsoleInputIcon.foreground\\\":\\\"#bc8cff\\\",\\\"debugIcon.breakpointForeground\\\":\\\"#f85149\\\",\\\"debugTokenExpression.boolean\\\":\\\"#56d364\\\",\\\"debugTokenExpression.error\\\":\\\"#ffa198\\\",\\\"debugTokenExpression.name\\\":\\\"#79c0ff\\\",\\\"debugTokenExpression.number\\\":\\\"#56d364\\\",\\\"debugTokenExpression.string\\\":\\\"#a5d6ff\\\",\\\"debugTokenExpression.value\\\":\\\"#a5d6ff\\\",\\\"debugToolBar.background\\\":\\\"#161b22\\\",\\\"descriptionForeground\\\":\\\"#7d8590\\\",\\\"diffEditor.insertedLineBackground\\\":\\\"#23863626\\\",\\\"diffEditor.insertedTextBackground\\\":\\\"#3fb9504d\\\",\\\"diffEditor.removedLineBackground\\\":\\\"#da363326\\\",\\\"diffEditor.removedTextBackground\\\":\\\"#ff7b724d\\\",\\\"dropdown.background\\\":\\\"#161b22\\\",\\\"dropdown.border\\\":\\\"#30363d\\\",\\\"dropdown.foreground\\\":\\\"#e6edf3\\\",\\\"dropdown.listBackground\\\":\\\"#161b22\\\",\\\"editor.background\\\":\\\"#0d1117\\\",\\\"editor.findMatchBackground\\\":\\\"#9e6a03\\\",\\\"editor.findMatchHighlightBackground\\\":\\\"#f2cc6080\\\",\\\"editor.focusedStackFrameHighlightBackground\\\":\\\"#2ea04366\\\",\\\"editor.foldBackground\\\":\\\"#6e76811a\\\",\\\"editor.foreground\\\":\\\"#e6edf3\\\",\\\"editor.lineHighlightBackground\\\":\\\"#6e76811a\\\",\\\"editor.linkedEditingBackground\\\":\\\"#2f81f712\\\",\\\"editor.selectionHighlightBackground\\\":\\\"#3fb95040\\\",\\\"editor.stackFrameHighlightBackground\\\":\\\"#bb800966\\\",\\\"editor.wordHighlightBackground\\\":\\\"#6e768180\\\",\\\"editor.wordHighlightBorder\\\":\\\"#6e768199\\\",\\\"editor.wordHighlightStrongBackground\\\":\\\"#6e76814d\\\",\\\"editor.wordHighlightStrongBorder\\\":\\\"#6e768199\\\",\\\"editorBracketHighlight.foreground1\\\":\\\"#79c0ff\\\",\\\"editorBracketHighlight.foreground2\\\":\\\"#56d364\\\",\\\"editorBracketHighlight.foreground3\\\":\\\"#e3b341\\\",\\\"editorBracketHighlight.foreground4\\\":\\\"#ffa198\\\",\\\"editorBracketHighlight.foreground5\\\":\\\"#ff9bce\\\",\\\"editorBracketHighlight.foreground6\\\":\\\"#d2a8ff\\\",\\\"editorBracketHighlight.unexpectedBracket.foreground\\\":\\\"#7d8590\\\",\\\"editorBracketMatch.background\\\":\\\"#3fb95040\\\",\\\"editorBracketMatch.border\\\":\\\"#3fb95099\\\",\\\"editorCursor.foreground\\\":\\\"#2f81f7\\\",\\\"editorGroup.border\\\":\\\"#30363d\\\",\\\"editorGroupHeader.tabsBackground\\\":\\\"#010409\\\",\\\"editorGroupHeader.tabsBorder\\\":\\\"#30363d\\\",\\\"editorGutter.addedBackground\\\":\\\"#2ea04366\\\",\\\"editorGutter.deletedBackground\\\":\\\"#f8514966\\\",\\\"editorGutter.modifiedBackground\\\":\\\"#bb800966\\\",\\\"editorIndentGuide.activeBackground\\\":\\\"#e6edf33d\\\",\\\"editorIndentGuide.background\\\":\\\"#e6edf31f\\\",\\\"editorInlayHint.background\\\":\\\"#8b949e33\\\",\\\"editorInlayHint.foreground\\\":\\\"#7d8590\\\",\\\"editorInlayHint.paramBackground\\\":\\\"#8b949e33\\\",\\\"editorInlayHint.paramForeground\\\":\\\"#7d8590\\\",\\\"editorInlayHint.typeBackground\\\":\\\"#8b949e33\\\",\\\"editorInlayHint.typeForeground\\\":\\\"#7d8590\\\",\\\"editorLineNumber.activeForeground\\\":\\\"#e6edf3\\\",\\\"editorLineNumber.foreground\\\":\\\"#6e7681\\\",\\\"editorOverviewRuler.border\\\":\\\"#010409\\\",\\\"editorWhitespace.foreground\\\":\\\"#484f58\\\",\\\"editorWidget.background\\\":\\\"#161b22\\\",\\\"errorForeground\\\":\\\"#f85149\\\",\\\"focusBorder\\\":\\\"#1f6feb\\\",\\\"foreground\\\":\\\"#e6edf3\\\",\\\"gitDecoration.addedResourceForeground\\\":\\\"#3fb950\\\",\\\"gitDecoration.conflictingResourceForeground\\\":\\\"#db6d28\\\",\\\"gitDecoration.deletedResourceForeground\\\":\\\"#f85149\\\",\\\"gitDecoration.ignoredResourceForeground\\\":\\\"#6e7681\\\",\\\"gitDecoration.modifiedResourceForeground\\\":\\\"#d29922\\\",\\\"gitDecoration.submoduleResourceForeground\\\":\\\"#7d8590\\\",\\\"gitDecoration.untrackedResourceForeground\\\":\\\"#3fb950\\\",\\\"icon.foreground\\\":\\\"#7d8590\\\",\\\"input.background\\\":\\\"#0d1117\\\",\\\"input.border\\\":\\\"#30363d\\\",\\\"input.foreground\\\":\\\"#e6edf3\\\",\\\"input.placeholderForeground\\\":\\\"#6e7681\\\",\\\"keybindingLabel.foreground\\\":\\\"#e6edf3\\\",\\\"list.activeSelectionBackground\\\":\\\"#6e768166\\\",\\\"list.activeSelectionForeground\\\":\\\"#e6edf3\\\",\\\"list.focusBackground\\\":\\\"#388bfd26\\\",\\\"list.focusForeground\\\":\\\"#e6edf3\\\",\\\"list.highlightForeground\\\":\\\"#2f81f7\\\",\\\"list.hoverBackground\\\":\\\"#6e76811a\\\",\\\"list.hoverForeground\\\":\\\"#e6edf3\\\",\\\"list.inactiveFocusBackground\\\":\\\"#388bfd26\\\",\\\"list.inactiveSelectionBackground\\\":\\\"#6e768166\\\",\\\"list.inactiveSelectionForeground\\\":\\\"#e6edf3\\\",\\\"minimapSlider.activeBackground\\\":\\\"#8b949e47\\\",\\\"minimapSlider.background\\\":\\\"#8b949e33\\\",\\\"minimapSlider.hoverBackground\\\":\\\"#8b949e3d\\\",\\\"notificationCenterHeader.background\\\":\\\"#161b22\\\",\\\"notificationCenterHeader.foreground\\\":\\\"#7d8590\\\",\\\"notifications.background\\\":\\\"#161b22\\\",\\\"notifications.border\\\":\\\"#30363d\\\",\\\"notifications.foreground\\\":\\\"#e6edf3\\\",\\\"notificationsErrorIcon.foreground\\\":\\\"#f85149\\\",\\\"notificationsInfoIcon.foreground\\\":\\\"#2f81f7\\\",\\\"notificationsWarningIcon.foreground\\\":\\\"#d29922\\\",\\\"panel.background\\\":\\\"#010409\\\",\\\"panel.border\\\":\\\"#30363d\\\",\\\"panelInput.border\\\":\\\"#30363d\\\",\\\"panelTitle.activeBorder\\\":\\\"#f78166\\\",\\\"panelTitle.activeForeground\\\":\\\"#e6edf3\\\",\\\"panelTitle.inactiveForeground\\\":\\\"#7d8590\\\",\\\"peekViewEditor.background\\\":\\\"#6e76811a\\\",\\\"peekViewEditor.matchHighlightBackground\\\":\\\"#bb800966\\\",\\\"peekViewResult.background\\\":\\\"#0d1117\\\",\\\"peekViewResult.matchHighlightBackground\\\":\\\"#bb800966\\\",\\\"pickerGroup.border\\\":\\\"#30363d\\\",\\\"pickerGroup.foreground\\\":\\\"#7d8590\\\",\\\"progressBar.background\\\":\\\"#1f6feb\\\",\\\"quickInput.background\\\":\\\"#161b22\\\",\\\"quickInput.foreground\\\":\\\"#e6edf3\\\",\\\"scrollbar.shadow\\\":\\\"#484f5833\\\",\\\"scrollbarSlider.activeBackground\\\":\\\"#8b949e47\\\",\\\"scrollbarSlider.background\\\":\\\"#8b949e33\\\",\\\"scrollbarSlider.hoverBackground\\\":\\\"#8b949e3d\\\",\\\"settings.headerForeground\\\":\\\"#e6edf3\\\",\\\"settings.modifiedItemIndicator\\\":\\\"#bb800966\\\",\\\"sideBar.background\\\":\\\"#010409\\\",\\\"sideBar.border\\\":\\\"#30363d\\\",\\\"sideBar.foreground\\\":\\\"#e6edf3\\\",\\\"sideBarSectionHeader.background\\\":\\\"#010409\\\",\\\"sideBarSectionHeader.border\\\":\\\"#30363d\\\",\\\"sideBarSectionHeader.foreground\\\":\\\"#e6edf3\\\",\\\"sideBarTitle.foreground\\\":\\\"#e6edf3\\\",\\\"statusBar.background\\\":\\\"#0d1117\\\",\\\"statusBar.border\\\":\\\"#30363d\\\",\\\"statusBar.debuggingBackground\\\":\\\"#da3633\\\",\\\"statusBar.debuggingForeground\\\":\\\"#ffffff\\\",\\\"statusBar.focusBorder\\\":\\\"#1f6feb80\\\",\\\"statusBar.foreground\\\":\\\"#7d8590\\\",\\\"statusBar.noFolderBackground\\\":\\\"#0d1117\\\",\\\"statusBarItem.activeBackground\\\":\\\"#e6edf31f\\\",\\\"statusBarItem.focusBorder\\\":\\\"#1f6feb\\\",\\\"statusBarItem.hoverBackground\\\":\\\"#e6edf314\\\",\\\"statusBarItem.prominentBackground\\\":\\\"#6e768166\\\",\\\"statusBarItem.remoteBackground\\\":\\\"#30363d\\\",\\\"statusBarItem.remoteForeground\\\":\\\"#e6edf3\\\",\\\"symbolIcon.arrayForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.booleanForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.classForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.colorForeground\\\":\\\"#79c0ff\\\",\\\"symbolIcon.constantForeground\\\":[\\\"#aff5b4\\\",\\\"#7ee787\\\",\\\"#56d364\\\",\\\"#3fb950\\\",\\\"#2ea043\\\",\\\"#238636\\\",\\\"#196c2e\\\",\\\"#0f5323\\\",\\\"#033a16\\\",\\\"#04260f\\\"],\\\"symbolIcon.constructorForeground\\\":\\\"#d2a8ff\\\",\\\"symbolIcon.enumeratorForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.enumeratorMemberForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.eventForeground\\\":\\\"#6e7681\\\",\\\"symbolIcon.fieldForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.fileForeground\\\":\\\"#d29922\\\",\\\"symbolIcon.folderForeground\\\":\\\"#d29922\\\",\\\"symbolIcon.functionForeground\\\":\\\"#bc8cff\\\",\\\"symbolIcon.interfaceForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.keyForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.keywordForeground\\\":\\\"#ff7b72\\\",\\\"symbolIcon.methodForeground\\\":\\\"#bc8cff\\\",\\\"symbolIcon.moduleForeground\\\":\\\"#ff7b72\\\",\\\"symbolIcon.namespaceForeground\\\":\\\"#ff7b72\\\",\\\"symbolIcon.nullForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.numberForeground\\\":\\\"#3fb950\\\",\\\"symbolIcon.objectForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.operatorForeground\\\":\\\"#79c0ff\\\",\\\"symbolIcon.packageForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.propertyForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.referenceForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.snippetForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.stringForeground\\\":\\\"#79c0ff\\\",\\\"symbolIcon.structForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.textForeground\\\":\\\"#79c0ff\\\",\\\"symbolIcon.typeParameterForeground\\\":\\\"#79c0ff\\\",\\\"symbolIcon.unitForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.variableForeground\\\":\\\"#f0883e\\\",\\\"tab.activeBackground\\\":\\\"#0d1117\\\",\\\"tab.activeBorder\\\":\\\"#0d1117\\\",\\\"tab.activeBorderTop\\\":\\\"#f78166\\\",\\\"tab.activeForeground\\\":\\\"#e6edf3\\\",\\\"tab.border\\\":\\\"#30363d\\\",\\\"tab.hoverBackground\\\":\\\"#0d1117\\\",\\\"tab.inactiveBackground\\\":\\\"#010409\\\",\\\"tab.inactiveForeground\\\":\\\"#7d8590\\\",\\\"tab.unfocusedActiveBorder\\\":\\\"#0d1117\\\",\\\"tab.unfocusedActiveBorderTop\\\":\\\"#30363d\\\",\\\"tab.unfocusedHoverBackground\\\":\\\"#6e76811a\\\",\\\"terminal.ansiBlack\\\":\\\"#484f58\\\",\\\"terminal.ansiBlue\\\":\\\"#58a6ff\\\",\\\"terminal.ansiBrightBlack\\\":\\\"#6e7681\\\",\\\"terminal.ansiBrightBlue\\\":\\\"#79c0ff\\\",\\\"terminal.ansiBrightCyan\\\":\\\"#56d4dd\\\",\\\"terminal.ansiBrightGreen\\\":\\\"#56d364\\\",\\\"terminal.ansiBrightMagenta\\\":\\\"#d2a8ff\\\",\\\"terminal.ansiBrightRed\\\":\\\"#ffa198\\\",\\\"terminal.ansiBrightWhite\\\":\\\"#ffffff\\\",\\\"terminal.ansiBrightYellow\\\":\\\"#e3b341\\\",\\\"terminal.ansiCyan\\\":\\\"#39c5cf\\\",\\\"terminal.ansiGreen\\\":\\\"#3fb950\\\",\\\"terminal.ansiMagenta\\\":\\\"#bc8cff\\\",\\\"terminal.ansiRed\\\":\\\"#ff7b72\\\",\\\"terminal.ansiWhite\\\":\\\"#b1bac4\\\",\\\"terminal.ansiYellow\\\":\\\"#d29922\\\",\\\"terminal.foreground\\\":\\\"#e6edf3\\\",\\\"textBlockQuote.background\\\":\\\"#010409\\\",\\\"textBlockQuote.border\\\":\\\"#30363d\\\",\\\"textCodeBlock.background\\\":\\\"#6e768166\\\",\\\"textLink.activeForeground\\\":\\\"#2f81f7\\\",\\\"textLink.foreground\\\":\\\"#2f81f7\\\",\\\"textPreformat.background\\\":\\\"#6e768166\\\",\\\"textPreformat.foreground\\\":\\\"#7d8590\\\",\\\"textSeparator.foreground\\\":\\\"#21262d\\\",\\\"titleBar.activeBackground\\\":\\\"#0d1117\\\",\\\"titleBar.activeForeground\\\":\\\"#7d8590\\\",\\\"titleBar.border\\\":\\\"#30363d\\\",\\\"titleBar.inactiveBackground\\\":\\\"#010409\\\",\\\"titleBar.inactiveForeground\\\":\\\"#7d8590\\\",\\\"tree.indentGuidesStroke\\\":\\\"#21262d\\\",\\\"welcomePage.buttonBackground\\\":\\\"#21262d\\\",\\\"welcomePage.buttonHoverBackground\\\":\\\"#30363d\\\"},\\\"displayName\\\":\\\"GitHub Dark Default\\\",\\\"name\\\":\\\"github-dark-default\\\",\\\"semanticHighlighting\\\":true,\\\"tokenColors\\\":[{\\\"scope\\\":[\\\"comment\\\",\\\"punctuation.definition.comment\\\",\\\"string.comment\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#8b949e\\\"}},{\\\"scope\\\":[\\\"constant.other.placeholder\\\",\\\"constant.character\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#ff7b72\\\"}},{\\\"scope\\\":[\\\"constant\\\",\\\"entity.name.constant\\\",\\\"variable.other.constant\\\",\\\"variable.other.enummember\\\",\\\"variable.language\\\",\\\"entity\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":[\\\"entity.name\\\",\\\"meta.export.default\\\",\\\"meta.definition.variable\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#ffa657\\\"}},{\\\"scope\\\":[\\\"variable.parameter.function\\\",\\\"meta.jsx.children\\\",\\\"meta.block\\\",\\\"meta.tag.attributes\\\",\\\"entity.name.constant\\\",\\\"meta.object.member\\\",\\\"meta.embedded.expression\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#e6edf3\\\"}},{\\\"scope\\\":\\\"entity.name.function\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#d2a8ff\\\"}},{\\\"scope\\\":[\\\"entity.name.tag\\\",\\\"support.class.component\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#7ee787\\\"}},{\\\"scope\\\":\\\"keyword\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ff7b72\\\"}},{\\\"scope\\\":[\\\"storage\\\",\\\"storage.type\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#ff7b72\\\"}},{\\\"scope\\\":[\\\"storage.modifier.package\\\",\\\"storage.modifier.import\\\",\\\"storage.type.java\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#e6edf3\\\"}},{\\\"scope\\\":[\\\"string\\\",\\\"string punctuation.section.embedded source\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#a5d6ff\\\"}},{\\\"scope\\\":\\\"support\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"meta.property-name\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ffa657\\\"}},{\\\"scope\\\":\\\"variable.other\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#e6edf3\\\"}},{\\\"scope\\\":\\\"invalid.broken\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":\\\"invalid.deprecated\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":\\\"invalid.illegal\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":\\\"invalid.unimplemented\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":\\\"carriage-return\\\",\\\"settings\\\":{\\\"background\\\":\\\"#ff7b72\\\",\\\"content\\\":\\\"^M\\\",\\\"fontStyle\\\":\\\"italic underline\\\",\\\"foreground\\\":\\\"#f0f6fc\\\"}},{\\\"scope\\\":\\\"message.error\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":\\\"string variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":[\\\"source.regexp\\\",\\\"string.regexp\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#a5d6ff\\\"}},{\\\"scope\\\":[\\\"string.regexp.character-class\\\",\\\"string.regexp constant.character.escape\\\",\\\"string.regexp source.ruby.embedded\\\",\\\"string.regexp string.regexp.arbitrary-repitition\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#a5d6ff\\\"}},{\\\"scope\\\":\\\"string.regexp constant.character.escape\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#7ee787\\\"}},{\\\"scope\\\":\\\"support.constant\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"support.variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"support.type.property-name.json\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#7ee787\\\"}},{\\\"scope\\\":\\\"meta.module-reference\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"punctuation.definition.list.begin.markdown\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ffa657\\\"}},{\\\"scope\\\":[\\\"markup.heading\\\",\\\"markup.heading entity.name\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"markup.quote\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#7ee787\\\"}},{\\\"scope\\\":\\\"markup.italic\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#e6edf3\\\"}},{\\\"scope\\\":\\\"markup.bold\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#e6edf3\\\"}},{\\\"scope\\\":[\\\"markup.underline\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"underline\\\"}},{\\\"scope\\\":[\\\"markup.strikethrough\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"strikethrough\\\"}},{\\\"scope\\\":\\\"markup.inline.raw\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":[\\\"markup.deleted\\\",\\\"meta.diff.header.from-file\\\",\\\"punctuation.definition.deleted\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#490202\\\",\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":[\\\"punctuation.section.embedded\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#ff7b72\\\"}},{\\\"scope\\\":[\\\"markup.inserted\\\",\\\"meta.diff.header.to-file\\\",\\\"punctuation.definition.inserted\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#04260f\\\",\\\"foreground\\\":\\\"#7ee787\\\"}},{\\\"scope\\\":[\\\"markup.changed\\\",\\\"punctuation.definition.changed\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#5a1e02\\\",\\\"foreground\\\":\\\"#ffa657\\\"}},{\\\"scope\\\":[\\\"markup.ignored\\\",\\\"markup.untracked\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#79c0ff\\\",\\\"foreground\\\":\\\"#161b22\\\"}},{\\\"scope\\\":\\\"meta.diff.range\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#d2a8ff\\\"}},{\\\"scope\\\":\\\"meta.diff.header\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"meta.separator\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"meta.output\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":[\\\"brackethighlighter.tag\\\",\\\"brackethighlighter.curly\\\",\\\"brackethighlighter.round\\\",\\\"brackethighlighter.square\\\",\\\"brackethighlighter.angle\\\",\\\"brackethighlighter.quote\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#8b949e\\\"}},{\\\"scope\\\":\\\"brackethighlighter.unmatched\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":[\\\"constant.other.reference.link\\\",\\\"string.other.link\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#a5d6ff\\\"}}],\\\"type\\\":\\\"dark\\\"}\"))\n","// TODO: We should find some other ways to do this.\nconst pre = (markdown: string): string =>\n // IE11 does not support \"u\" flag and Babel could not remove it. We intentionally omitting the \"u\" flag here.\n // eslint-disable-next-line require-unicode-regexp\n markdown.replace(/\\n\\r|\\r\\n/g, carriageReturn => (carriageReturn === '\\n\\r' ? '\\r\\n' : '\\n\\r'));\n\nexport { pre };\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError, ObjectDisposedError } from \"./Error\";\r\nimport { IDetachable } from \"./IDetachable\";\r\nimport { IDisposable } from \"./IDisposable\";\r\nimport { List } from \"./List\";\r\nimport {\r\n Deferred,\r\n} from \"./Promise\";\r\nexport interface IQueue<TItem> extends IDisposable {\r\n enqueue(item: TItem): void;\r\n enqueueFromPromise(promise: Promise<TItem>): void;\r\n dequeue(): Promise<TItem>;\r\n peek(): Promise<TItem>;\r\n length(): number;\r\n}\r\n\r\nenum SubscriberType {\r\n Dequeue,\r\n Peek,\r\n}\r\n\r\nexport class Queue<TItem> implements IQueue<TItem> {\r\n private privPromiseStore: List<Promise<TItem>> = new List<Promise<TItem>>();\r\n private privList: List<TItem>;\r\n private privDetachables: IDetachable[];\r\n private privSubscribers: List<{ type: SubscriberType, deferral: Deferred<TItem> }>;\r\n private privIsDrainInProgress: boolean = false;\r\n private privIsDisposing: boolean = false;\r\n private privDisposeReason: string = null;\r\n\r\n public constructor(list?: List<TItem>) {\r\n this.privList = list ? list : new List<TItem>();\r\n this.privDetachables = [];\r\n this.privSubscribers = new List<{ type: SubscriberType, deferral: Deferred<TItem> }>();\r\n this.privDetachables.push(this.privList.onAdded(this.drain));\r\n }\r\n\r\n public enqueue = (item: TItem): void => {\r\n this.throwIfDispose();\r\n this.enqueueFromPromise(new Promise<TItem>((resolve: (value: TItem) => void, reject: (reason: any) => void) => { resolve(item); }));\r\n }\r\n\r\n public enqueueFromPromise = (promise: Promise<TItem>): void => {\r\n this.throwIfDispose();\r\n promise.then((val: TItem): void => {\r\n this.privList.add(val);\r\n /* tslint:disable:no-empty */\r\n }, (error: string): void => { });\r\n }\r\n\r\n public dequeue = (): Promise<TItem> => {\r\n this.throwIfDispose();\r\n const deferredSubscriber = new Deferred<TItem>();\r\n\r\n if (this.privSubscribers) {\r\n this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Dequeue });\r\n this.drain();\r\n }\r\n\r\n return deferredSubscriber.promise;\r\n }\r\n\r\n public peek = (): Promise<TItem> => {\r\n this.throwIfDispose();\r\n const deferredSubscriber = new Deferred<TItem>();\r\n\r\n const subs = this.privSubscribers;\r\n if (subs) {\r\n this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Peek });\r\n this.drain();\r\n }\r\n\r\n return deferredSubscriber.promise;\r\n }\r\n\r\n public length = (): number => {\r\n this.throwIfDispose();\r\n return this.privList.length();\r\n }\r\n\r\n public isDisposed = (): boolean => {\r\n return this.privSubscribers == null;\r\n }\r\n\r\n public async drainAndDispose(pendingItemProcessor: (pendingItemInQueue: TItem) => void, reason?: string): Promise<void> {\r\n if (!this.isDisposed() && !this.privIsDisposing) {\r\n this.privDisposeReason = reason;\r\n this.privIsDisposing = true;\r\n\r\n const subs = this.privSubscribers;\r\n if (subs) {\r\n while (subs.length() > 0) {\r\n const subscriber = subs.removeFirst();\r\n // TODO: this needs work (Resolve(null) instead?).\r\n subscriber.deferral.resolve(undefined);\r\n // subscriber.deferral.reject(\"Disposed\");\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privSubscribers === subs) {\r\n this.privSubscribers = subs;\r\n }\r\n }\r\n\r\n for (const detachable of this.privDetachables) {\r\n await detachable.detach();\r\n }\r\n\r\n if (this.privPromiseStore.length() > 0 && pendingItemProcessor) {\r\n const promiseArray: Promise<TItem>[] = [];\r\n\r\n this.privPromiseStore.toArray().forEach((wrapper: Promise<TItem>) => {\r\n promiseArray.push(wrapper);\r\n });\r\n return Promise.all(promiseArray).finally(() => {\r\n this.privSubscribers = null;\r\n this.privList.forEach((item: TItem, index: number): void => {\r\n pendingItemProcessor(item);\r\n });\r\n this.privList = null;\r\n return;\r\n }).then<void>();\r\n } else {\r\n this.privSubscribers = null;\r\n this.privList = null;\r\n }\r\n }\r\n }\r\n\r\n public async dispose(reason?: string): Promise<void> {\r\n await this.drainAndDispose(null, reason);\r\n }\r\n\r\n private drain = (): void => {\r\n if (!this.privIsDrainInProgress && !this.privIsDisposing) {\r\n this.privIsDrainInProgress = true;\r\n\r\n const subs = this.privSubscribers;\r\n const lists = this.privList;\r\n if (subs && lists) {\r\n while (lists.length() > 0 && subs.length() > 0 && !this.privIsDisposing) {\r\n const subscriber = subs.removeFirst();\r\n if (subscriber.type === SubscriberType.Peek) {\r\n subscriber.deferral.resolve(lists.first());\r\n } else {\r\n const dequeuedItem = lists.removeFirst();\r\n subscriber.deferral.resolve(dequeuedItem);\r\n }\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privSubscribers === subs) {\r\n this.privSubscribers = subs;\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privList === lists) {\r\n this.privList = lists;\r\n }\r\n }\r\n\r\n this.privIsDrainInProgress = false;\r\n }\r\n }\r\n\r\n private throwIfDispose = (): void => {\r\n if (this.isDisposed()) {\r\n if (this.privDisposeReason) {\r\n throw new InvalidOperationError(this.privDisposeReason);\r\n }\r\n\r\n throw new ObjectDisposedError(\"Queue\");\r\n } else if (this.privIsDisposing) {\r\n throw new InvalidOperationError(\"Queue disposing\");\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n IAudioDestination,\r\n IStreamChunk,\r\n Stream,\r\n} from \"../../common/Exports\";\r\nimport { Contracts } from \"../Contracts\";\r\nimport {\r\n AudioStreamFormat,\r\n PushAudioOutputStreamCallback\r\n} from \"../Exports\";\r\nimport { AudioOutputFormatImpl } from \"./AudioOutputFormat\";\r\n\r\n/**\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @class AudioOutputStream\r\n */\r\nexport abstract class AudioOutputStream {\r\n\r\n /**\r\n * Creates and initializes an instance.\r\n * @constructor\r\n */\r\n protected constructor() { }\r\n\r\n /**\r\n * Sets the format of the AudioOutputStream\r\n * Note: the format is set by the synthesizer before writing. Do not set it before passing it to AudioConfig\r\n * @member AudioOutputStream.prototype.format\r\n */\r\n public abstract set format(format: AudioStreamFormat);\r\n\r\n /**\r\n * Creates a memory backed PullAudioOutputStream with the specified audio format.\r\n * @member AudioOutputStream.createPullStream\r\n * @function\r\n * @public\r\n * @returns {PullAudioOutputStream} The audio output stream being created.\r\n */\r\n public static createPullStream(): PullAudioOutputStream {\r\n return PullAudioOutputStream.create();\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member AudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio output stream used for custom audio output configurations.\r\n * @class PullAudioOutputStream\r\n */\r\nexport abstract class PullAudioOutputStream extends AudioOutputStream {\r\n\r\n /**\r\n * Creates a memory backed PullAudioOutputStream with the specified audio format.\r\n * @member PullAudioOutputStream.create\r\n * @function\r\n * @public\r\n * @returns {PullAudioOutputStream} The push audio output stream being created.\r\n */\r\n public static create(): PullAudioOutputStream {\r\n return new PullAudioOutputStreamImpl();\r\n }\r\n\r\n /**\r\n * Reads audio data from the internal buffer.\r\n * @member PullAudioOutputStream.prototype.read\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - An ArrayBuffer to store the read data.\r\n * @returns {Promise<number>} Audio buffer length has been read.\r\n */\r\n public abstract read(dataBuffer: ArrayBuffer): Promise<number>;\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PullAudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio output stream used for custom audio output configurations.\r\n * @private\r\n * @class PullAudioOutputStreamImpl\r\n */\r\nexport class PullAudioOutputStreamImpl extends PullAudioOutputStream implements IAudioDestination {\r\n private privFormat: AudioOutputFormatImpl;\r\n private privId: string;\r\n private privStream: Stream<ArrayBuffer>;\r\n private privLastChunkView: Int8Array;\r\n\r\n /**\r\n * Creates and initializes an instance with the given values.\r\n * @constructor\r\n */\r\n public constructor() {\r\n super();\r\n this.privId = createNoDashGuid();\r\n this.privStream = new Stream<ArrayBuffer>();\r\n }\r\n\r\n /**\r\n * Sets the format information to the stream. For internal use only.\r\n * @param {AudioStreamFormat} format - the format to be set.\r\n */\r\n public set format(format: AudioStreamFormat) {\r\n if (format === undefined || format === null) {\r\n this.privFormat = AudioOutputFormatImpl.getDefaultOutputFormat();\r\n }\r\n this.privFormat = format as AudioOutputFormatImpl;\r\n }\r\n\r\n /**\r\n * Format information for the audio\r\n */\r\n public get format(): AudioStreamFormat {\r\n return this.privFormat;\r\n }\r\n\r\n /**\r\n * Checks if the stream is closed\r\n * @member PullAudioOutputStreamImpl.prototype.isClosed\r\n * @property\r\n * @public\r\n */\r\n public get isClosed(): boolean {\r\n return this.privStream.isClosed;\r\n }\r\n\r\n /**\r\n * Gets the id of the stream\r\n * @member PullAudioOutputStreamImpl.prototype.id\r\n * @property\r\n * @public\r\n */\r\n public id(): string {\r\n return this.privId;\r\n }\r\n\r\n /**\r\n * Reads audio data from the internal buffer.\r\n * @member PullAudioOutputStreamImpl.prototype.read\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - An ArrayBuffer to store the read data.\r\n * @returns {Promise<number>} - Audio buffer length has been read.\r\n */\r\n public async read(dataBuffer: ArrayBuffer): Promise<number> {\r\n const intView: Int8Array = new Int8Array(dataBuffer);\r\n let totalBytes: number = 0;\r\n\r\n if (this.privLastChunkView !== undefined) {\r\n if (this.privLastChunkView.length > dataBuffer.byteLength) {\r\n intView.set(this.privLastChunkView.slice(0, dataBuffer.byteLength));\r\n this.privLastChunkView = this.privLastChunkView.slice(dataBuffer.byteLength);\r\n return Promise.resolve(dataBuffer.byteLength);\r\n }\r\n intView.set(this.privLastChunkView);\r\n totalBytes = this.privLastChunkView.length;\r\n this.privLastChunkView = undefined;\r\n }\r\n\r\n // Until we have the minimum number of bytes to send in a transmission, keep asking for more.\r\n while (totalBytes < dataBuffer.byteLength && !this.privStream.isReadEnded) {\r\n const chunk: IStreamChunk<ArrayBuffer> = await this.privStream.read();\r\n if (chunk !== undefined && !chunk.isEnd) {\r\n let tmpBuffer: ArrayBuffer;\r\n if (chunk.buffer.byteLength > dataBuffer.byteLength - totalBytes) {\r\n tmpBuffer = chunk.buffer.slice(0, dataBuffer.byteLength - totalBytes);\r\n this.privLastChunkView = new Int8Array(chunk.buffer.slice(dataBuffer.byteLength - totalBytes));\r\n } else {\r\n tmpBuffer = chunk.buffer;\r\n }\r\n intView.set(new Int8Array(tmpBuffer), totalBytes);\r\n totalBytes += tmpBuffer.byteLength;\r\n } else {\r\n await this.privStream.readEnded();\r\n }\r\n }\r\n return totalBytes;\r\n }\r\n\r\n /**\r\n * Writes the audio data specified by making an internal copy of the data.\r\n * @member PullAudioOutputStreamImpl.prototype.write\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy.\r\n */\r\n public write(dataBuffer: ArrayBuffer): void {\r\n Contracts.throwIfNullOrUndefined(this.privStream, \"must set format before writing\");\r\n this.privStream.writeStreamChunk({\r\n buffer: dataBuffer,\r\n isEnd: false,\r\n timeReceived: Date.now()\r\n });\r\n }\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PullAudioOutputStreamImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n this.privStream.close();\r\n }\r\n}\r\n\r\n/*\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @class PushAudioOutputStream\r\n */\r\nexport abstract class PushAudioOutputStream extends AudioOutputStream {\r\n /**\r\n * Creates and initializes and instance.\r\n * @constructor\r\n */\r\n protected constructor() { super(); }\r\n\r\n /**\r\n * Creates a PushAudioOutputStream that delegates to the specified callback interface for\r\n * write() and close() methods.\r\n * @member PushAudioOutputStream.create\r\n * @function\r\n * @public\r\n * @param {PushAudioOutputStreamCallback} callback - The custom audio output object,\r\n * derived from PushAudioOutputStreamCallback\r\n * @returns {PushAudioOutputStream} The push audio output stream being created.\r\n */\r\n public static create(callback: PushAudioOutputStreamCallback): PushAudioOutputStream {\r\n return new PushAudioOutputStreamImpl(callback);\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member PushAudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n\r\n}\r\n\r\n/**\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @private\r\n * @class PushAudioOutputStreamImpl\r\n */\r\nexport class PushAudioOutputStreamImpl extends PushAudioOutputStream implements IAudioDestination {\r\n private readonly privId: string;\r\n private privCallback: PushAudioOutputStreamCallback;\r\n\r\n /**\r\n * Creates a PushAudioOutputStream that delegates to the specified callback interface for\r\n * read() and close() methods.\r\n * @constructor\r\n * @param {PushAudioOutputStreamCallback} callback - The custom audio output object,\r\n * derived from PushAudioOutputStreamCallback\r\n */\r\n public constructor(callback: PushAudioOutputStreamCallback) {\r\n super();\r\n this.privId = createNoDashGuid();\r\n this.privCallback = callback;\r\n }\r\n\r\n // tslint:disable-next-line:no-empty\r\n public set format(format: AudioStreamFormat) { }\r\n\r\n public write(buffer: ArrayBuffer): void {\r\n if (!!this.privCallback.write) {\r\n this.privCallback.write(buffer);\r\n }\r\n }\r\n\r\n public close(): void {\r\n if (!!this.privCallback.close) {\r\n this.privCallback.close();\r\n }\r\n }\r\n\r\n public id(): string {\r\n return this.privId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionMessage,\r\n Deferred,\r\n IStringDictionary,\r\n IWebsocketMessageFormatter,\r\n MessageType,\r\n RawWebsocketMessage,\r\n} from \"../common/Exports\";\r\n\r\nconst CRLF: string = \"\\r\\n\";\r\n\r\nexport class WebsocketMessageFormatter implements IWebsocketMessageFormatter {\r\n\r\n public toConnectionMessage = (message: RawWebsocketMessage): Promise<ConnectionMessage> => {\r\n const deferral = new Deferred<ConnectionMessage>();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const textMessage: string = message.textContent;\r\n let headers: IStringDictionary<string> = {};\r\n let body: string = null;\r\n\r\n if (textMessage) {\r\n const headerBodySplit = textMessage.split(\"\\r\\n\\r\\n\");\r\n if (headerBodySplit && headerBodySplit.length > 0) {\r\n headers = this.parseHeaders(headerBodySplit[0]);\r\n if (headerBodySplit.length > 1) {\r\n body = headerBodySplit[1];\r\n }\r\n }\r\n }\r\n\r\n deferral.resolve(new ConnectionMessage(message.messageType, body, headers, message.id));\r\n } else if (message.messageType === MessageType.Binary) {\r\n const binaryMessage: ArrayBuffer = message.binaryContent;\r\n let headers: IStringDictionary<string> = {};\r\n let body: ArrayBuffer = null;\r\n\r\n if (!binaryMessage || binaryMessage.byteLength < 2) {\r\n throw new Error(\"Invalid binary message format. Header length missing.\");\r\n }\r\n\r\n const dataView = new DataView(binaryMessage);\r\n const headerLength = dataView.getInt16(0);\r\n\r\n if (binaryMessage.byteLength < headerLength + 2) {\r\n throw new Error(\"Invalid binary message format. Header content missing.\");\r\n }\r\n\r\n let headersString = \"\";\r\n for (let i = 0; i < headerLength; i++) {\r\n headersString += String.fromCharCode((dataView).getInt8(i + 2));\r\n }\r\n\r\n headers = this.parseHeaders(headersString);\r\n\r\n if (binaryMessage.byteLength > headerLength + 2) {\r\n body = binaryMessage.slice(2 + headerLength);\r\n }\r\n\r\n deferral.resolve(new ConnectionMessage(message.messageType, body, headers, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. Error: ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n\r\n public fromConnectionMessage = (message: ConnectionMessage): Promise<RawWebsocketMessage> => {\r\n const deferral = new Deferred<RawWebsocketMessage>();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const payload = `${this.makeHeaders(message)}${CRLF}${message.textBody ? message.textBody : \"\"}`;\r\n\r\n deferral.resolve(new RawWebsocketMessage(MessageType.Text, payload, message.id));\r\n\r\n } else if (message.messageType === MessageType.Binary) {\r\n const headersString = this.makeHeaders(message);\r\n const content = message.binaryBody;\r\n\r\n const headerBuffer = this.stringToArrayBuffer(headersString);\r\n const headerInt8Array = new Int8Array(headerBuffer);\r\n const headerLength = headerInt8Array.byteLength;\r\n\r\n const payloadInt8Array = new Int8Array(2 + headerLength + (content ? content.byteLength : 0));\r\n payloadInt8Array[0] = ((headerLength >> 8) & 0xff);\r\n payloadInt8Array[1] = headerLength & 0xff;\r\n payloadInt8Array.set(headerInt8Array, 2);\r\n\r\n if (content) {\r\n const bodyInt8Array = new Int8Array(content);\r\n payloadInt8Array.set(bodyInt8Array, 2 + headerLength);\r\n }\r\n\r\n const payload: ArrayBuffer = payloadInt8Array.buffer;\r\n\r\n deferral.resolve(new RawWebsocketMessage(MessageType.Binary, payload, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n\r\n private makeHeaders = (message: ConnectionMessage): string => {\r\n let headersString: string = \"\";\r\n\r\n if (message.headers) {\r\n for (const header in message.headers) {\r\n if (header) {\r\n headersString += `${header}: ${message.headers[header]}${CRLF}`;\r\n }\r\n }\r\n }\r\n\r\n return headersString;\r\n }\r\n\r\n private parseHeaders = (headersString: string): IStringDictionary<string> => {\r\n const headers: IStringDictionary<string> = {};\r\n\r\n if (headersString) {\r\n const headerMatches = headersString.match(/[^\\r\\n]+/g);\r\n if (headers) {\r\n for (const header of headerMatches) {\r\n if (header) {\r\n const separatorIndex = header.indexOf(\":\");\r\n const headerName = separatorIndex > 0 ? header.substr(0, separatorIndex).trim().toLowerCase() : header;\r\n const headerValue =\r\n separatorIndex > 0 && header.length > (separatorIndex + 1) ?\r\n header.substr(separatorIndex + 1).trim() :\r\n \"\";\r\n\r\n headers[headerName] = headerValue;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return headers;\r\n }\r\n\r\n private stringToArrayBuffer = (str: string): ArrayBuffer => {\r\n const buffer = new ArrayBuffer(str.length);\r\n const view = new DataView(buffer);\r\n for (let i = 0; i < str.length; i++) {\r\n view.setUint8(i, str.charCodeAt(i));\r\n }\r\n return buffer;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport {\r\n AudioSourceErrorEvent,\r\n AudioStreamNodeAttachedEvent,\r\n AudioStreamNodeAttachingEvent,\r\n AudioStreamNodeDetachedEvent,\r\n AudioStreamNodeErrorEvent,\r\n ConnectionEstablishedEvent,\r\n ConnectionEstablishErrorEvent,\r\n ConnectionMessageReceivedEvent,\r\n ConnectionStartEvent,\r\n IEventListener,\r\n IStringDictionary,\r\n PlatformEvent,\r\n} from \"../common/Exports\";\r\nimport { ConnectingToServiceEvent, RecognitionTriggeredEvent } from \"./RecognitionEvents\";\r\n\r\nexport interface ITelemetry {\r\n Metrics: IMetric[];\r\n ReceivedMessages: IStringDictionary<string[]>;\r\n}\r\n\r\nexport interface IMetric {\r\n End?: string;\r\n Error?: string;\r\n Id?: string;\r\n Name?: string;\r\n Start?: string;\r\n PhraseLatencyMs?: number[];\r\n FirstHypothesisLatencyMs?: number[];\r\n}\r\n\r\nexport class ServiceTelemetryListener implements IEventListener<PlatformEvent> {\r\n private privIsDisposed: boolean = false;\r\n\r\n private privRequestId: string;\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n\r\n private privListeningTriggerMetric: IMetric = null;\r\n private privMicMetric: IMetric = null;\r\n private privConnectionEstablishMetric: IMetric = null;\r\n\r\n private privMicStartTime: string;\r\n\r\n private privConnectionId: string;\r\n private privConnectionStartTime: string;\r\n\r\n private privReceivedMessages: IStringDictionary<string[]>;\r\n private privPhraseLatencies: number[];\r\n private privHypothesisLatencies: number[];\r\n\r\n constructor(requestId: string, audioSourceId: string, audioNodeId: string) {\r\n this.privRequestId = requestId;\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n\r\n this.privReceivedMessages = {};\r\n this.privPhraseLatencies = [];\r\n this.privHypothesisLatencies = [];\r\n }\r\n\r\n public phraseReceived(audioReceivedTime: number): void {\r\n if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it.\r\n this.privPhraseLatencies.push(Date.now() - audioReceivedTime);\r\n }\r\n }\r\n\r\n public hypothesisReceived(audioReceivedTime: number): void {\r\n if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it.\r\n this.privHypothesisLatencies.push(Date.now() - audioReceivedTime);\r\n }\r\n }\r\n\r\n public onEvent = (e: PlatformEvent): void => {\r\n if (this.privIsDisposed) {\r\n return;\r\n }\r\n\r\n if (e instanceof RecognitionTriggeredEvent && e.requestId === this.privRequestId) {\r\n this.privListeningTriggerMetric = {\r\n End: e.eventTime,\r\n Name: \"ListeningTrigger\",\r\n Start: e.eventTime,\r\n };\r\n }\r\n\r\n if (e instanceof AudioStreamNodeAttachingEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n this.privMicStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof AudioStreamNodeAttachedEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n this.privMicStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof AudioSourceErrorEvent && e.audioSourceId === this.privAudioSourceId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Error: e.error,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof AudioStreamNodeErrorEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Error: e.error,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof AudioStreamNodeDetachedEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectingToServiceEvent && e.requestId === this.privRequestId) {\r\n this.privConnectionId = e.sessionId;\r\n }\r\n\r\n if (e instanceof ConnectionStartEvent && e.connectionId === this.privConnectionId) {\r\n this.privConnectionStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof ConnectionEstablishedEvent && e.connectionId === this.privConnectionId) {\r\n if (!this.privConnectionEstablishMetric) {\r\n this.privConnectionEstablishMetric = {\r\n End: e.eventTime,\r\n Id: this.privConnectionId,\r\n Name: \"Connection\",\r\n Start: this.privConnectionStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectionEstablishErrorEvent && e.connectionId === this.privConnectionId) {\r\n if (!this.privConnectionEstablishMetric) {\r\n this.privConnectionEstablishMetric = {\r\n End: e.eventTime,\r\n Error: this.getConnectionError(e.statusCode),\r\n Id: this.privConnectionId,\r\n Name: \"Connection\",\r\n Start: this.privConnectionStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectionMessageReceivedEvent && e.connectionId === this.privConnectionId) {\r\n if (e.message && e.message.headers && e.message.headers.path) {\r\n if (!this.privReceivedMessages[e.message.headers.path]) {\r\n this.privReceivedMessages[e.message.headers.path] = new Array<string>();\r\n }\r\n\r\n this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime);\r\n }\r\n }\r\n }\r\n\r\n public getTelemetry = (): string => {\r\n const metrics = new Array<IMetric>();\r\n\r\n if (this.privListeningTriggerMetric) {\r\n metrics.push(this.privListeningTriggerMetric);\r\n }\r\n\r\n if (this.privMicMetric) {\r\n metrics.push(this.privMicMetric);\r\n }\r\n\r\n if (this.privConnectionEstablishMetric) {\r\n metrics.push(this.privConnectionEstablishMetric);\r\n }\r\n\r\n if (this.privPhraseLatencies.length > 0) {\r\n metrics.push({\r\n PhraseLatencyMs: this.privPhraseLatencies,\r\n });\r\n }\r\n\r\n if (this.privHypothesisLatencies.length > 0) {\r\n metrics.push({\r\n FirstHypothesisLatencyMs: this.privHypothesisLatencies,\r\n });\r\n }\r\n\r\n const telemetry: ITelemetry = {\r\n Metrics: metrics,\r\n ReceivedMessages: this.privReceivedMessages,\r\n };\r\n\r\n const json = JSON.stringify(telemetry);\r\n\r\n // We dont want to send the same telemetry again. So clean those out.\r\n this.privReceivedMessages = {};\r\n this.privListeningTriggerMetric = null;\r\n this.privMicMetric = null;\r\n this.privConnectionEstablishMetric = null;\r\n this.privPhraseLatencies = [];\r\n this.privHypothesisLatencies = [];\r\n return json;\r\n }\r\n\r\n // Determines if there are any telemetry events to send to the service.\r\n public get hasTelemetry(): boolean {\r\n return (Object.keys(this.privReceivedMessages).length !== 0 ||\r\n this.privListeningTriggerMetric !== null ||\r\n this.privMicMetric !== null ||\r\n this.privConnectionEstablishMetric !== null ||\r\n this.privPhraseLatencies.length !== 0 ||\r\n this.privHypothesisLatencies.length !== 0);\r\n }\r\n\r\n public dispose = (): void => {\r\n this.privIsDisposed = true;\r\n }\r\n\r\n private getConnectionError = (statusCode: number): string => {\r\n /*\r\n -- Websocket status codes --\r\n NormalClosure = 1000,\r\n EndpointUnavailable = 1001,\r\n ProtocolError = 1002,\r\n InvalidMessageType = 1003,\r\n Empty = 1005,\r\n InvalidPayloadData = 1007,\r\n PolicyViolation = 1008,\r\n MessageTooBig = 1009,\r\n MandatoryExtension = 1010,\r\n InternalServerError = 1011\r\n */\r\n\r\n switch (statusCode) {\r\n case 400:\r\n case 1002:\r\n case 1003:\r\n case 1005:\r\n case 1007:\r\n case 1008:\r\n case 1009: return \"BadRequest\";\r\n case 401: return \"Unauthorized\";\r\n case 403: return \"Forbidden\";\r\n case 503:\r\n case 1001: return \"ServerUnavailable\";\r\n case 500:\r\n case 1011: return \"ServerError\";\r\n case 408:\r\n case 504: return \"Timeout\";\r\n default: return \"statuscode:\" + statusCode.toString();\r\n }\r\n }\r\n}\r\n","import { type AudioConfig as AudioConfigType } from 'microsoft-cognitiveservices-speech-sdk';\nimport { parse } from 'valibot';\n\nimport resolveFunctionOrReturnValue from './resolveFunctionOrReturnValue';\nimport SpeechSDK from './SpeechSDK';\nimport credentialsSchema, { type Credentials } from './SpeechToText/validation/credentialsSchema';\nimport enableTelemetrySchema, { EnableTelemetry } from './SpeechToText/validation/enableTelemetrySchema';\nimport initialSilenceTimeoutSchema, {\n InitialSilenceTimeout\n} from './SpeechToText/validation/initialSilenceTimeoutSchema';\nimport looseEventsSchema, { LooseEvents } from './SpeechToText/validation/looseEventsSchema';\nimport referenceGrammarsSchema, { ReferenceGrammars } from './SpeechToText/validation/referenceGrammarsSchema';\nimport speechRecognitionEndpointIdSchema, {\n SpeechRecognitionEndpointId\n} from './SpeechToText/validation/speechRecognitionEndpointIdSchema';\nimport textNormalizationSchema, { TextNormalization } from './SpeechToText/validation/textNormalizationSchema';\n\nconst { AudioConfig } = SpeechSDK;\n\nlet shouldWarnOnSubscriptionKey = true;\n\ntype PatchOptionsInit = {\n audioConfig?: AudioConfigType | undefined;\n credentials: (() => Credentials | Promise<Credentials>) | Credentials | Promise<Credentials>;\n enableTelemetry?: boolean | undefined;\n initialSilenceTimeout?: number | undefined;\n looseEvent?: boolean | undefined;\n looseEvents?: boolean | undefined;\n referenceGrammars?: readonly string[] | undefined;\n speechRecognitionEndpointId?: string | undefined;\n textNormalization?: 'display' | 'itn' | 'lexical' | 'maskeditn' | undefined;\n};\n\ntype PatchedOptions = Readonly<{\n audioConfig: AudioConfigType;\n enableTelemetry: EnableTelemetry;\n fetchCredentials: () => Promise<Credentials>;\n initialSilenceTimeout: InitialSilenceTimeout;\n looseEvents: LooseEvents;\n referenceGrammars: ReferenceGrammars;\n speechRecognitionEndpointId: SpeechRecognitionEndpointId;\n textNormalization: TextNormalization;\n}>;\n\nexport default function patchOptions(init: PatchOptionsInit): PatchedOptions {\n const {\n audioConfig,\n credentials,\n enableTelemetry,\n initialSilenceTimeout,\n looseEvent,\n referenceGrammars,\n speechRecognitionEndpointId,\n textNormalization\n } = init;\n\n let { looseEvents } = init;\n\n if (typeof looseEvent !== 'undefined') {\n console.warn('web-speech-cognitive-services: The option \"looseEvent\" should be named as \"looseEvents\".');\n\n looseEvents = looseEvent;\n }\n\n return Object.freeze({\n audioConfig: audioConfig || AudioConfig.fromDefaultMicrophoneInput(),\n // We set telemetry to true to honor the default telemetry settings of Speech SDK\n // https://github.com/Microsoft/cognitive-services-speech-sdk-js#data--telemetry\n enableTelemetry: parse(enableTelemetrySchema, enableTelemetry),\n fetchCredentials: async () => {\n const parsedCredentials = parse(credentialsSchema, await resolveFunctionOrReturnValue<Credentials>(credentials));\n\n if (shouldWarnOnSubscriptionKey && parsedCredentials.subscriptionKey) {\n console.warn(\n 'web-speech-cognitive-services: In production environment, subscription key should not be used, authorization token should be used instead.'\n );\n\n shouldWarnOnSubscriptionKey = false;\n }\n\n return parsedCredentials;\n },\n initialSilenceTimeout: parse(initialSilenceTimeoutSchema, initialSilenceTimeout),\n looseEvents: parse(looseEventsSchema, looseEvents),\n referenceGrammars: parse(referenceGrammarsSchema, referenceGrammars),\n speechRecognitionEndpointId: parse(speechRecognitionEndpointIdSchema, speechRecognitionEndpointId),\n textNormalization: parse(textNormalizationSchema, textNormalization)\n });\n}\n\nexport type { Credentials, PatchedOptions, PatchOptionsInit };\n","/* eslint no-magic-numbers: [\"error\", { \"ignore\": [0, 1, 100] }] */\n\n// Cognitive Services does not support unsigned percentage\n// It must be converted into +/- first.\nfunction relativePercentage(value) {\n let relative = Math.round((value - 1) * 100);\n\n if (relative >= 0) {\n relative = '+' + relative;\n }\n\n return relative + '%';\n}\n\nexport default function buildSSML({ lang, pitch = 1, rate = 1, text, voice, volume }) {\n return `<speak version=\"1.0\" xml:lang=\"${lang}\">\n <voice xml:lang=\"${lang}\" name=\"${voice}\">\n <prosody pitch=\"${relativePercentage(pitch)}\" rate=\"${relativePercentage(rate)}\" volume=\"${relativePercentage(\n volume\n )}\">\n ${text}\n </prosody>\n </voice>\n</speak>`;\n}\n","import { WebSpeechPonyfillFactory } from 'botframework-webchat-api';\nimport { AudioConfig } from 'microsoft-cognitiveservices-speech-sdk';\nimport { createSpeechServicesPonyfill } from 'web-speech-cognitive-services';\n\nimport createMicrophoneAudioConfigAndAudioContext from './speech/createMicrophoneAudioConfigAndAudioContext';\nimport CognitiveServicesAudioOutputFormat from './types/CognitiveServicesAudioOutputFormat';\nimport CognitiveServicesCredentials from './types/CognitiveServicesCredentials';\nimport CognitiveServicesTextNormalization from './types/CognitiveServicesTextNormalization';\n\nexport default function createCognitiveServicesSpeechServicesPonyfillFactory({\n audioConfig,\n audioContext,\n audioInputDeviceId,\n credentials,\n enableTelemetry,\n initialSilenceTimeout,\n speechRecognitionEndpointId,\n speechSynthesisDeploymentId,\n speechSynthesisOutputFormat,\n textNormalization\n}: {\n audioConfig?: AudioConfig;\n audioContext?: AudioContext;\n audioInputDeviceId?: string;\n credentials: CognitiveServicesCredentials;\n enableTelemetry?: true;\n initialSilenceTimeout?: number | undefined;\n speechRecognitionEndpointId?: string;\n speechSynthesisDeploymentId?: string;\n speechSynthesisOutputFormat?: CognitiveServicesAudioOutputFormat;\n textNormalization?: CognitiveServicesTextNormalization;\n}): WebSpeechPonyfillFactory {\n if (!window.navigator.mediaDevices && !audioConfig) {\n console.warn(\n 'botframework-webchat: Your browser does not support Web Audio or the page is not loaded via HTTPS or localhost. Cognitive Services Speech Services is disabled. However, you may pass a custom AudioConfig to enable speech in this environment.'\n );\n\n return () => ({});\n }\n\n if (audioConfig) {\n audioInputDeviceId &&\n console.warn(\n 'botframework-webchat: \"audioConfig\" and \"audioInputDeviceId\" cannot be set at the same time; ignoring \"audioInputDeviceId\".'\n );\n\n audioContext &&\n console.warn(\n 'botframework-webchat: \"audioConfig\" and \"audioContext\" cannot be set at the same time; ignoring \"audioContext\" for speech recognition.'\n );\n } else {\n ({ audioConfig, audioContext } = createMicrophoneAudioConfigAndAudioContext({\n audioContext,\n audioInputDeviceId,\n enableTelemetry\n }));\n }\n\n return ({ referenceGrammarID } = {}) => {\n const { SpeechGrammarList, SpeechRecognition, speechSynthesis, SpeechSynthesisUtterance } =\n createSpeechServicesPonyfill({\n audioConfig,\n audioContext,\n credentials,\n enableTelemetry,\n initialSilenceTimeout,\n referenceGrammars: referenceGrammarID ? [`luis/${referenceGrammarID}-PRODUCTION`] : [],\n speechRecognitionEndpointId,\n speechSynthesisDeploymentId,\n speechSynthesisOutputFormat,\n textNormalization\n });\n\n return {\n resumeAudioContext: () => audioContext && audioContext.state === 'suspended' && audioContext.resume(),\n SpeechGrammarList,\n SpeechRecognition,\n speechSynthesis,\n SpeechSynthesisUtterance\n };\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/__w/1/s/BotFramework-WebChat/packages/bundle/dist/chunk-7WMTUZ5O.js","../../../node_modules/requires-port/index.js","../../../node_modules/querystringify/index.js","../../../node_modules/url-parse/index.js","../src/FullComposer.tsx","../src/AddFullBundle.tsx","../src/adaptiveCards/AdaptiveCardsComposer.tsx","../src/adaptiveCards/AdaptiveCardsContext.ts","../src/codeHighlighter/ShikiComposer.tsx","../../../node_modules/@shikijs/types/dist/index.mjs","../../../node_modules/@shikijs/engine-oniguruma/dist/index.mjs","../../../node_modules/@shikijs/core/dist/shared/core.afb6276c.mjs","../../../node_modules/@shikijs/vscode-textmate/dist/index.mjs","../../../node_modules/property-information/lib/html.js","../../../node_modules/hast-util-to-html/lib/handle/element.js","../../../node_modules/regex/src/utils.js","../../../node_modules/regex/src/atomic.js","../../../node_modules/regex/src/backcompat.js","../../../node_modules/regex/src/flag-n.js","../../../node_modules/regex/src/flag-x.js","../../../node_modules/regex/src/subroutines.js","../../../node_modules/oniguruma-to-js/dist/shared/oniguruma-to-js.2969e22d.mjs","../../../node_modules/@shikijs/core/dist/index.mjs","../../../node_modules/shiki/dist/themes/github-dark-default.mjs","../src/markdown/private/respectCRLF.ts","../../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common/src/common/Queue.ts","../../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/sdk/Audio/src/sdk/Audio/AudioOutputStream.ts","../../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/WebsocketMessageFormatter.ts","../../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/es2015/src/common.speech/src/common.speech/ServiceTelemetryListener.Internal.ts","../../../node_modules/web-speech-cognitive-services/src/SpeechServices/patchOptions.ts","../../../node_modules/web-speech-cognitive-services/src/SpeechServices/TextToSpeech/buildSSML.js","../src/createCognitiveServicesSpeechServicesPonyfillFactory.ts"],"names":["require_requires_port","__commonJSMin","exports","module","port","protocol","require_querystringify","has","undef","decode","input","encode","querystring","query","parser","result","part","key","value","querystringify","obj","prefix","pairs","require_url_parse","required","qs","controlOrWhitespace","CRHTLF","slashes","protocolre","windowsDriveLetter","trimLeft","str","rules","address","url","isSpecial","ignore","lolcation","loc","globalVar","location","finaldestination","type","Url","scheme","extractProtocol","match","forwardSlashes","otherSlashes","slashesCount","rest","resolve","relative","base","path","i","last","unshift","up","extracted","parse","instruction","index","instructions","set","fn","char","ins","toString","stringify","host","AdaptiveCardsContext","createContext","AdaptiveCardsContext_default","AdaptiveCardsComposer","adaptiveCardsHostConfig","adaptiveCardsPackage","children","patchedAdaptiveCardsPackage","useMemo","defaultAdaptiveCardsPackage","adaptiveCardsContext","React","AdaptiveCardsComposer_default","ShikiError","message","getHeapMax","_emscripten_get_now","alignUp","x","multiple","main","init","wasmMemory","buffer","binding","updateGlobalBufferAndViews","buf","_emscripten_memcpy_big","dest","src","num","emscripten_realloc_buffer","size","_emscripten_resize_heap","requestedSize","oldSize","maxHeapSize","cutDown","overGrownHeapSize","newSize","UTF8Decoder","UTF8ArrayToString","heapOrArray","idx","maxBytesToRead","endIdx","endPtr","u0","u1","u2","ch","UTF8ToString","ptr","asmLibraryArg","createWasm","onigBinding","throwLastOnigError","UtfString","_UtfString","__publicField","utf16Length","utf8Length","computeIndicesMapping","utf16OffsetToUtf8","utf8OffsetToUtf16","utf8Value","i8","i16","charCode","codePoint","wasSurrogatePair","nextCharCode","len","codepoint","_OnigString","utfString","utf8Offset","utf16Offset","OnigString","OnigScanner","patterns","strPtrsArr","strLenArr","strPtrsPtr","strLenPtr","scannerPtr","string","startPosition","arg","options","debugCall","resultPtr","HEAPU32","offset","count","captureIndices","beg","end","isInstantiatorOptionsObject","dataOrOptions","isInstantiatorModule","isDataOptionsObject","isResponse","isArrayBuffer","data","_a","initPromise","loadWasm","_load","info","instance","_makeResponseStreamingLoader","_makeResponseNonStreamingLoader","_makeArrayBufferLoader","importObject","arrayBuffer","_defaultWasmLoader","getDefaultWasmLoader","createOnigurumaEngine","s","emitDeprecation","warnDeprecated"],"mappings":"AAAA,ifAA4I,IAAK,EAAE,CAAC,gCAAE,CAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,gCAAE,CAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,gCAAE,CAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CCAlM,IAAAA,EAAAA,CAAAC,gCAAAA,CAAAC,EAAAA,CAAAC,EAAAA,CAAAA,EAAA,CAAA,YAAA,CAWAA,EAAAA,CAAO,OAAA,CAAU,QAAA,CAAkBC,CAAAA,CAAMC,CAAAA,CAAU,CAIjD,EAAA,CAHAA,CAAAA,CAAWA,CAAAA,CAAS,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,CAChCD,CAAAA,CAAO,CAACA,CAAAA,CAEJ,CAACA,CAAAA,CAAM,MAAO,CAAA,CAAA,CAElB,MAAA,CAAQC,CAAAA,CAAU,CAChB,IAAK,MAAA,CACL,IAAK,IAAA,CACL,OAAOD,CAAAA,GAAS,EAAA,CAEhB,IAAK,OAAA,CACL,IAAK,KAAA,CACL,OAAOA,CAAAA,GAAS,GAAA,CAEhB,IAAK,KAAA,CACL,OAAOA,CAAAA,GAAS,EAAA,CAEhB,IAAK,QAAA,CACL,OAAOA,CAAAA,GAAS,EAAA,CAEhB,IAAK,MAAA,CACL,MAAO,CAAA,CACT,CAEA,OAAOA,CAAAA,GAAS,CAClB,CAAA,CAAA,CAAA,CCrCA,IAAAE,EAAAA,CAAAL,gCAAAA,EAAAC,EAAA,CAAA,YAAA,CAEA,IAAIK,EAAAA,CAAM,MAAA,CAAO,SAAA,CAAU,cAAA,CACvBC,EAAAA,CASJ,SAASC,EAAAA,CAAOC,CAAAA,CAAO,CACrB,GAAI,CACF,OAA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AA;AAAiC,YAAA;AAIjC,cAAA;AAAyB,OAAA;AACzB,aAAA;AAAiC,aAAA;ACqDQ,aAAA;AfzE27a;Ae2Ej8a,mBAAA;AfzEi8a;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AeuKl8a;AfrKk8a;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AgB0Dz7a;AhBxDy7a;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AgB0D98a,WAAA;AhBxD88a;AiB9Cz8a;AjBgDy8a;AACA;AiB9Cz8a,SAAA;AjBgDy8a;AiB9C57a,oBAAA;AjBgD47a;AACA;AkBvDz8a;AACb;AlByDs9a;AACA;AACA;AmBvDz8a;AnByDy8a;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AmBvDp9a,EAAA;AnByDo9a;AmBvDz8a,SAAA;AnByDy8a;AACA;AmB7Bz9a;AC3BgB;AACb;AACiB,oBAAA;ApB2Dq8a;AACA;AACA;AqBmD98a;ACmciC;ACxkBpB;ACGwC,EAAA;AAAS;ACmF5E,EAAA;AC2CE,0EAAA;ACtHM;AAcyC;A3BmE26a;A4BgIx9a;AClKb;AC3CqC,mBAAA;AAGpC,oBAAA;AACO,MAAA;A9B+E69a;AACA;A+BlC95a,QAAA;A/BoC85a","file":"/__w/1/s/BotFramework-WebChat/packages/bundle/dist/chunk-7WMTUZ5O.js","sourcesContent":[null,"'use strict';\n\n/**\n * Check if we're required to add a port number.\n *\n * @see https://url.spec.whatwg.org/#default-port\n * @param {Number|String} port Port number we need to check\n * @param {String} protocol Protocol we need to check against.\n * @returns {Boolean} Is it a default port for the given protocol\n * @api private\n */\nmodule.exports = function required(port, protocol) {\n protocol = protocol.split(':')[0];\n port = +port;\n\n if (!port) return false;\n\n switch (protocol) {\n case 'http':\n case 'ws':\n return port !== 80;\n\n case 'https':\n case 'wss':\n return port !== 443;\n\n case 'ftp':\n return port !== 21;\n\n case 'gopher':\n return port !== 70;\n\n case 'file':\n return false;\n }\n\n return port !== 0;\n};\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , undef;\n\n/**\n * Decode a URI encoded string.\n *\n * @param {String} input The URI encoded string.\n * @returns {String|Null} The decoded string.\n * @api private\n */\nfunction decode(input) {\n try {\n return decodeURIComponent(input.replace(/\\+/g, ' '));\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Attempts to encode a given input.\n *\n * @param {String} input The string that needs to be encoded.\n * @returns {String|Null} The encoded string.\n * @api private\n */\nfunction encode(input) {\n try {\n return encodeURIComponent(input);\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Simple query string parser.\n *\n * @param {String} query The query string that needs to be parsed.\n * @returns {Object}\n * @api public\n */\nfunction querystring(query) {\n var parser = /([^=?#&]+)=?([^&]*)/g\n , result = {}\n , part;\n\n while (part = parser.exec(query)) {\n var key = decode(part[1])\n , value = decode(part[2]);\n\n //\n // Prevent overriding of existing properties. This ensures that build-in\n // methods like `toString` or __proto__ are not overriden by malicious\n // querystrings.\n //\n // In the case if failed decoding, we want to omit the key/value pairs\n // from the result.\n //\n if (key === null || value === null || key in result) continue;\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Transform a query string to an object.\n *\n * @param {Object} obj Object that should be transformed.\n * @param {String} prefix Optional prefix.\n * @returns {String}\n * @api public\n */\nfunction querystringify(obj, prefix) {\n prefix = prefix || '';\n\n var pairs = []\n , value\n , key;\n\n //\n // Optionally prefix with a '?' if needed\n //\n if ('string' !== typeof prefix) prefix = '?';\n\n for (key in obj) {\n if (has.call(obj, key)) {\n value = obj[key];\n\n //\n // Edge cases where we actually want to encode the value to an empty\n // string instead of the stringified value.\n //\n if (!value && (value === null || value === undef || isNaN(value))) {\n value = '';\n }\n\n key = encode(key);\n value = encode(value);\n\n //\n // If we failed to encode the strings, we should bail out as we don't\n // want to add invalid strings to the query.\n //\n if (key === null || value === null) continue;\n pairs.push(key +'='+ value);\n }\n }\n\n return pairs.length ? prefix + pairs.join('&') : '';\n}\n\n//\n// Expose the module.\n//\nexports.stringify = querystringify;\nexports.parse = querystring;\n","'use strict';\n\nvar required = require('requires-port')\n , qs = require('querystringify')\n , controlOrWhitespace = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/\n , CRHTLF = /[\\n\\r\\t]/g\n , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//\n , port = /:\\d+$/\n , protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i\n , windowsDriveLetter = /^[a-zA-Z]:/;\n\n/**\n * Remove control characters and whitespace from the beginning of a string.\n *\n * @param {Object|String} str String to trim.\n * @returns {String} A new string representing `str` stripped of control\n * characters and whitespace from its beginning.\n * @public\n */\nfunction trimLeft(str) {\n return (str ? str : '').toString().replace(controlOrWhitespace, '');\n}\n\n/**\n * These are the parse rules for the URL parser, it informs the parser\n * about:\n *\n * 0. The char it Needs to parse, if it's a string it should be done using\n * indexOf, RegExp using exec and NaN means set as current value.\n * 1. The property we should set when parsing this value.\n * 2. Indication if it's backwards or forward parsing, when set as number it's\n * the value of extra chars that should be split off.\n * 3. Inherit from location if non existing in the parser.\n * 4. `toLowerCase` the resulting value.\n */\nvar rules = [\n ['#', 'hash'], // Extract from the back.\n ['?', 'query'], // Extract from the back.\n function sanitize(address, url) { // Sanitize what is left of the address\n return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n },\n ['/', 'pathname'], // Extract from the back.\n ['@', 'auth', 1], // Extract from the front.\n [NaN, 'host', undefined, 1, 1], // Set left over value.\n [/:(\\d*)$/, 'port', undefined, 1], // RegExp the back.\n [NaN, 'hostname', undefined, 1, 1] // Set left over.\n];\n\n/**\n * These properties should not be copied or inherited from. This is only needed\n * for all non blob URL's as a blob URL does not include a hash, only the\n * origin.\n *\n * @type {Object}\n * @private\n */\nvar ignore = { hash: 1, query: 1 };\n\n/**\n * The location object differs when your code is loaded through a normal page,\n * Worker or through a worker using a blob. And with the blobble begins the\n * trouble as the location object will contain the URL of the blob, not the\n * location of the page where our code is loaded in. The actual origin is\n * encoded in the `pathname` so we can thankfully generate a good \"default\"\n * location from it so we can generate proper relative URL's again.\n *\n * @param {Object|String} loc Optional default location object.\n * @returns {Object} lolcation object.\n * @public\n */\nfunction lolcation(loc) {\n var globalVar;\n\n if (typeof window !== 'undefined') globalVar = window;\n else if (typeof global !== 'undefined') globalVar = global;\n else if (typeof self !== 'undefined') globalVar = self;\n else globalVar = {};\n\n var location = globalVar.location || {};\n loc = loc || location;\n\n var finaldestination = {}\n , type = typeof loc\n , key;\n\n if ('blob:' === loc.protocol) {\n finaldestination = new Url(unescape(loc.pathname), {});\n } else if ('string' === type) {\n finaldestination = new Url(loc, {});\n for (key in ignore) delete finaldestination[key];\n } else if ('object' === type) {\n for (key in loc) {\n if (key in ignore) continue;\n finaldestination[key] = loc[key];\n }\n\n if (finaldestination.slashes === undefined) {\n finaldestination.slashes = slashes.test(loc.href);\n }\n }\n\n return finaldestination;\n}\n\n/**\n * Check whether a protocol scheme is special.\n *\n * @param {String} The protocol scheme of the URL\n * @return {Boolean} `true` if the protocol scheme is special, else `false`\n * @private\n */\nfunction isSpecial(scheme) {\n return (\n scheme === 'file:' ||\n scheme === 'ftp:' ||\n scheme === 'http:' ||\n scheme === 'https:' ||\n scheme === 'ws:' ||\n scheme === 'wss:'\n );\n}\n\n/**\n * @typedef ProtocolExtract\n * @type Object\n * @property {String} protocol Protocol matched in the URL, in lowercase.\n * @property {Boolean} slashes `true` if protocol is followed by \"//\", else `false`.\n * @property {String} rest Rest of the URL that is not part of the protocol.\n */\n\n/**\n * Extract protocol information from a URL with/without double slash (\"//\").\n *\n * @param {String} address URL we want to extract from.\n * @param {Object} location\n * @return {ProtocolExtract} Extracted information.\n * @private\n */\nfunction extractProtocol(address, location) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n location = location || {};\n\n var match = protocolre.exec(address);\n var protocol = match[1] ? match[1].toLowerCase() : '';\n var forwardSlashes = !!match[2];\n var otherSlashes = !!match[3];\n var slashesCount = 0;\n var rest;\n\n if (forwardSlashes) {\n if (otherSlashes) {\n rest = match[2] + match[3] + match[4];\n slashesCount = match[2].length + match[3].length;\n } else {\n rest = match[2] + match[4];\n slashesCount = match[2].length;\n }\n } else {\n if (otherSlashes) {\n rest = match[3] + match[4];\n slashesCount = match[3].length;\n } else {\n rest = match[4]\n }\n }\n\n if (protocol === 'file:') {\n if (slashesCount >= 2) {\n rest = rest.slice(2);\n }\n } else if (isSpecial(protocol)) {\n rest = match[4];\n } else if (protocol) {\n if (forwardSlashes) {\n rest = rest.slice(2);\n }\n } else if (slashesCount >= 2 && isSpecial(location.protocol)) {\n rest = match[4];\n }\n\n return {\n protocol: protocol,\n slashes: forwardSlashes || isSpecial(protocol),\n slashesCount: slashesCount,\n rest: rest\n };\n}\n\n/**\n * Resolve a relative URL pathname against a base URL pathname.\n *\n * @param {String} relative Pathname of the relative URL.\n * @param {String} base Pathname of the base URL.\n * @return {String} Resolved pathname.\n * @private\n */\nfunction resolve(relative, base) {\n if (relative === '') return base;\n\n var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))\n , i = path.length\n , last = path[i - 1]\n , unshift = false\n , up = 0;\n\n while (i--) {\n if (path[i] === '.') {\n path.splice(i, 1);\n } else if (path[i] === '..') {\n path.splice(i, 1);\n up++;\n } else if (up) {\n if (i === 0) unshift = true;\n path.splice(i, 1);\n up--;\n }\n }\n\n if (unshift) path.unshift('');\n if (last === '.' || last === '..') path.push('');\n\n return path.join('/');\n}\n\n/**\n * The actual URL instance. Instead of returning an object we've opted-in to\n * create an actual constructor as it's much more memory efficient and\n * faster and it pleases my OCD.\n *\n * It is worth noting that we should not use `URL` as class name to prevent\n * clashes with the global URL instance that got introduced in browsers.\n *\n * @constructor\n * @param {String} address URL we want to parse.\n * @param {Object|String} [location] Location defaults for relative paths.\n * @param {Boolean|Function} [parser] Parser for the query string.\n * @private\n */\nfunction Url(address, location, parser) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n\n if (!(this instanceof Url)) {\n return new Url(address, location, parser);\n }\n\n var relative, extracted, parse, instruction, index, key\n , instructions = rules.slice()\n , type = typeof location\n , url = this\n , i = 0;\n\n //\n // The following if statements allows this module two have compatibility with\n // 2 different API:\n //\n // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n // where the boolean indicates that the query string should also be parsed.\n //\n // 2. The `URL` interface of the browser which accepts a URL, object as\n // arguments. The supplied object will be used as default values / fall-back\n // for relative paths.\n //\n if ('object' !== type && 'string' !== type) {\n parser = location;\n location = null;\n }\n\n if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n location = lolcation(location);\n\n //\n // Extract protocol information before running the instructions.\n //\n extracted = extractProtocol(address || '', location);\n relative = !extracted.protocol && !extracted.slashes;\n url.slashes = extracted.slashes || relative && location.slashes;\n url.protocol = extracted.protocol || location.protocol || '';\n address = extracted.rest;\n\n //\n // When the authority component is absent the URL starts with a path\n // component.\n //\n if (\n extracted.protocol === 'file:' && (\n extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n (!extracted.slashes &&\n (extracted.protocol ||\n extracted.slashesCount < 2 ||\n !isSpecial(url.protocol)))\n ) {\n instructions[3] = [/(.*)/, 'pathname'];\n }\n\n for (; i < instructions.length; i++) {\n instruction = instructions[i];\n\n if (typeof instruction === 'function') {\n address = instruction(address, url);\n continue;\n }\n\n parse = instruction[0];\n key = instruction[1];\n\n if (parse !== parse) {\n url[key] = address;\n } else if ('string' === typeof parse) {\n index = parse === '@'\n ? address.lastIndexOf(parse)\n : address.indexOf(parse);\n\n if (~index) {\n if ('number' === typeof instruction[2]) {\n url[key] = address.slice(0, index);\n address = address.slice(index + instruction[2]);\n } else {\n url[key] = address.slice(index);\n address = address.slice(0, index);\n }\n }\n } else if ((index = parse.exec(address))) {\n url[key] = index[1];\n address = address.slice(0, index.index);\n }\n\n url[key] = url[key] || (\n relative && instruction[3] ? location[key] || '' : ''\n );\n\n //\n // Hostname, host and protocol should be lowercased so they can be used to\n // create a proper `origin`.\n //\n if (instruction[4]) url[key] = url[key].toLowerCase();\n }\n\n //\n // Also parse the supplied query string in to an object. If we're supplied\n // with a custom parser as function use that instead of the default build-in\n // parser.\n //\n if (parser) url.query = parser(url.query);\n\n //\n // If the URL is relative, resolve the pathname against the base URL.\n //\n if (\n relative\n && location.slashes\n && url.pathname.charAt(0) !== '/'\n && (url.pathname !== '' || location.pathname !== '')\n ) {\n url.pathname = resolve(url.pathname, location.pathname);\n }\n\n //\n // Default to a / for pathname if none exists. This normalizes the URL\n // to always have a /\n //\n if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n url.pathname = '/' + url.pathname;\n }\n\n //\n // We should not add port numbers if they are already the default port number\n // for a given protocol. As the host also contains the port number we're going\n // override it with the hostname which contains no port number.\n //\n if (!required(url.port, url.protocol)) {\n url.host = url.hostname;\n url.port = '';\n }\n\n //\n // Parse down the `auth` for the username and password.\n //\n url.username = url.password = '';\n\n if (url.auth) {\n index = url.auth.indexOf(':');\n\n if (~index) {\n url.username = url.auth.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = url.auth.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password))\n } else {\n url.username = encodeURIComponent(decodeURIComponent(url.auth));\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n }\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n //\n // The href is just the compiled result.\n //\n url.href = url.toString();\n}\n\n/**\n * This is convenience method for changing properties in the URL instance to\n * insure that they all propagate correctly.\n *\n * @param {String} part Property we need to adjust.\n * @param {Mixed} value The newly assigned value.\n * @param {Boolean|Function} fn When setting the query, it will be the function\n * used to parse the query.\n * When setting the protocol, double slash will be\n * removed from the final url if it is true.\n * @returns {URL} URL instance for chaining.\n * @public\n */\nfunction set(part, value, fn) {\n var url = this;\n\n switch (part) {\n case 'query':\n if ('string' === typeof value && value.length) {\n value = (fn || qs.parse)(value);\n }\n\n url[part] = value;\n break;\n\n case 'port':\n url[part] = value;\n\n if (!required(value, url.protocol)) {\n url.host = url.hostname;\n url[part] = '';\n } else if (value) {\n url.host = url.hostname +':'+ value;\n }\n\n break;\n\n case 'hostname':\n url[part] = value;\n\n if (url.port) value += ':'+ url.port;\n url.host = value;\n break;\n\n case 'host':\n url[part] = value;\n\n if (port.test(value)) {\n value = value.split(':');\n url.port = value.pop();\n url.hostname = value.join(':');\n } else {\n url.hostname = value;\n url.port = '';\n }\n\n break;\n\n case 'protocol':\n url.protocol = value.toLowerCase();\n url.slashes = !fn;\n break;\n\n case 'pathname':\n case 'hash':\n if (value) {\n var char = part === 'pathname' ? '/' : '#';\n url[part] = value.charAt(0) !== char ? char + value : value;\n } else {\n url[part] = value;\n }\n break;\n\n case 'username':\n case 'password':\n url[part] = encodeURIComponent(value);\n break;\n\n case 'auth':\n var index = value.indexOf(':');\n\n if (~index) {\n url.username = value.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = value.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password));\n } else {\n url.username = encodeURIComponent(decodeURIComponent(value));\n }\n }\n\n for (var i = 0; i < rules.length; i++) {\n var ins = rules[i];\n\n if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n url.href = url.toString();\n\n return url;\n}\n\n/**\n * Transform the properties back in to a valid and full URL string.\n *\n * @param {Function} stringify Optional query stringify function.\n * @returns {String} Compiled version of the URL.\n * @public\n */\nfunction toString(stringify) {\n if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n var query\n , url = this\n , host = url.host\n , protocol = url.protocol;\n\n if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n var result =\n protocol +\n ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n if (url.username) {\n result += url.username;\n if (url.password) result += ':'+ url.password;\n result += '@';\n } else if (url.password) {\n result += ':'+ url.password;\n result += '@';\n } else if (\n url.protocol !== 'file:' &&\n isSpecial(url.protocol) &&\n !host &&\n url.pathname !== '/'\n ) {\n //\n // Add back the empty userinfo, otherwise the original invalid URL\n // might be transformed into a valid one with `url.pathname` as host.\n //\n result += '@';\n }\n\n //\n // Trailing colon is removed from `url.host` when it is parsed. If it still\n // ends with a colon, then add back the trailing colon that was removed. This\n // prevents an invalid URL from being transformed into a valid one.\n //\n if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {\n host += ':';\n }\n\n result += host + url.pathname;\n\n query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n if (url.hash) result += url.hash;\n\n return result;\n}\n\nUrl.prototype = { set: set, toString: toString };\n\n//\n// Expose the URL parser and some additional properties that might be useful for\n// others or testing.\n//\nUrl.extractProtocol = extractProtocol;\nUrl.location = lolcation;\nUrl.trimLeft = trimLeft;\nUrl.qs = qs;\n\nmodule.exports = Url;\n","import { Components, type ComposerProps } from 'botframework-webchat-component';\nimport PropTypes from 'prop-types';\nimport React from 'react';\n\nimport AddFullBundle, { type AddFullBundleProps } from './AddFullBundle';\n\nconst { Composer } = Components;\n\ntype FullComposerProps = ComposerProps & AddFullBundleProps;\n\nconst FullComposer = (props: FullComposerProps) => (\n <AddFullBundle {...props}>\n {extraProps => (\n <Composer {...props} {...extraProps}>\n {/* We need to spread, thus, we cannot we destructuring assignment. */}\n {/* eslint-disable-next-line react/destructuring-assignment */}\n {props.children}\n </Composer>\n )}\n </AddFullBundle>\n);\n\nFullComposer.defaultProps = {\n ...Composer.defaultProps,\n adaptiveCardsHostConfig: undefined,\n adaptiveCardsPackage: undefined,\n children: undefined\n};\n\nFullComposer.propTypes = {\n ...Composer.propTypes,\n adaptiveCardsHostConfig: PropTypes.any,\n adaptiveCardsPackage: PropTypes.any,\n children: PropTypes.any\n};\n\nexport default FullComposer;\n\nexport type { FullComposerProps };\n","import {\n type AttachmentForScreenReaderMiddleware,\n type AttachmentMiddleware,\n type StyleOptions\n} from 'botframework-webchat-api';\nimport { type HTMLContentTransformMiddleware } from 'botframework-webchat-component';\nimport { singleToArray, warnOnce, type OneOrMany } from 'botframework-webchat-core';\nimport React, { memo, type ReactNode } from 'react';\n\nimport AdaptiveCardsComposer from './adaptiveCards/AdaptiveCardsComposer';\nimport { type AdaptiveCardsStyleOptions } from './adaptiveCards/AdaptiveCardsStyleOptions';\nimport ShikiComposer from './codeHighlighter/ShikiComposer';\nimport { type AdaptiveCardsPackage } from './types/AdaptiveCardsPackage';\nimport { type StrictFullBundleStyleOptions } from './types/FullBundleStyleOptions';\nimport useComposerProps from './useComposerProps';\n\ntype AddFullBundleProps = Readonly<{\n adaptiveCardsHostConfig?: any;\n adaptiveCardsPackage?: AdaptiveCardsPackage;\n attachmentForScreenReaderMiddleware?: OneOrMany<AttachmentForScreenReaderMiddleware>;\n attachmentMiddleware?: OneOrMany<AttachmentMiddleware>;\n children: ({ extraStyleSet }: { extraStyleSet: any }) => ReactNode;\n htmlContentTransformMiddleware?: HTMLContentTransformMiddleware[];\n renderMarkdown?: (\n markdown: string,\n newLineOptions: { markdownRespectCRLF: boolean },\n linkOptions: { externalLinkAlt: string }\n ) => string;\n styleOptions?: StyleOptions & AdaptiveCardsStyleOptions;\n styleSet?: any & { options: StrictFullBundleStyleOptions };\n\n /** @deprecated Rename to \"adaptiveCardsHostConfig\" */\n adaptiveCardHostConfig?: any;\n}>;\n\nconst adaptiveCardHostConfigDeprecation = warnOnce(\n '\"adaptiveCardHostConfig\" is deprecated. Please use \"adaptiveCardsHostConfig\" instead. \"adaptiveCardHostConfig\" will be removed on or after 2022-01-01.'\n);\n\nfunction AddFullBundle({\n adaptiveCardHostConfig,\n adaptiveCardsHostConfig,\n adaptiveCardsPackage,\n attachmentForScreenReaderMiddleware,\n attachmentMiddleware,\n children,\n htmlContentTransformMiddleware,\n renderMarkdown,\n styleOptions,\n styleSet\n}: AddFullBundleProps) {\n adaptiveCardHostConfig && adaptiveCardHostConfigDeprecation();\n\n const patchedProps = useComposerProps({\n attachmentForScreenReaderMiddleware: singleToArray(attachmentForScreenReaderMiddleware),\n attachmentMiddleware: singleToArray(attachmentMiddleware),\n htmlContentTransformMiddleware,\n renderMarkdown,\n styleOptions,\n styleSet\n });\n\n return (\n <ShikiComposer>\n <AdaptiveCardsComposer\n adaptiveCardsHostConfig={adaptiveCardHostConfig || adaptiveCardsHostConfig}\n adaptiveCardsPackage={adaptiveCardsPackage}\n >\n {children(patchedProps)}\n </AdaptiveCardsComposer>\n </ShikiComposer>\n );\n}\n\nexport default memo(AddFullBundle);\n\nexport type { AddFullBundleProps };\n","import * as defaultAdaptiveCardsPackage from 'adaptivecards';\nimport React, { useMemo, type ReactNode } from 'react';\n\nimport { type AdaptiveCardsPackage } from '../types/AdaptiveCardsPackage';\nimport AdaptiveCardsContext from './AdaptiveCardsContext';\n\ntype AdaptiveCardsComposerProps = Readonly<{\n adaptiveCardsHostConfig: any;\n adaptiveCardsPackage: AdaptiveCardsPackage;\n children?: ReactNode | undefined;\n}>;\n\nconst AdaptiveCardsComposer = ({\n adaptiveCardsHostConfig,\n adaptiveCardsPackage,\n children\n}: AdaptiveCardsComposerProps) => {\n const patchedAdaptiveCardsPackage = useMemo(\n () => adaptiveCardsPackage || defaultAdaptiveCardsPackage,\n [adaptiveCardsPackage]\n );\n\n const adaptiveCardsContext = useMemo(\n () => ({\n adaptiveCardsPackage: patchedAdaptiveCardsPackage,\n hostConfigFromProps: adaptiveCardsHostConfig\n }),\n [adaptiveCardsHostConfig, patchedAdaptiveCardsPackage]\n );\n\n return <AdaptiveCardsContext.Provider value={adaptiveCardsContext}>{children}</AdaptiveCardsContext.Provider>;\n};\n\nexport default AdaptiveCardsComposer;\n","import { createContext } from 'react';\n\nimport { type AdaptiveCardsPackage } from '../types/AdaptiveCardsPackage';\n\ntype AdaptiveCardsContextType = {\n adaptiveCardsPackage: AdaptiveCardsPackage;\n hostConfigFromProps: any;\n};\n\nconst AdaptiveCardsContext = createContext<AdaptiveCardsContextType>(undefined);\n\nexport default AdaptiveCardsContext;\nexport type { AdaptiveCardsContextType };\n","import { CodeHighlighterComposer, type HighlightCodeFn } from 'botframework-webchat-component/internal';\nimport React, { memo, ReactNode, useEffect, useState } from 'react';\nimport { type HighlighterCore } from 'shiki';\n\nimport createHighlighter from './shiki';\n\nconst createHighligtCodeWithShiki =\n (shikiHiglighter: HighlighterCore): HighlightCodeFn =>\n (code, language, options) =>\n shikiHiglighter.codeToHtml(code, {\n lang: language,\n theme: options.theme\n });\n\nfunction ShikiComposer({ children }: { readonly children: ReactNode | undefined }) {\n const [highlightProps, setHighlightProps] = useState<Readonly<{ highlightCode: HighlightCodeFn }>>();\n\n useEffect(() => {\n let isMounted = true;\n (async () =>\n isMounted &&\n setHighlightProps(\n Object.freeze({\n highlightCode: createHighligtCodeWithShiki(await createHighlighter())\n })\n ))();\n return () => {\n isMounted = false;\n };\n }, []);\n\n return <CodeHighlighterComposer {...highlightProps}>{children}</CodeHighlighterComposer>;\n}\n\nexport default memo(ShikiComposer);\n","class ShikiError extends Error {\n constructor(message) {\n super(message);\n this.name = \"ShikiError\";\n }\n}\n\nexport { ShikiError };\n","class ShikiError extends Error {\n constructor(message) {\n super(message);\n this.name = 'ShikiError';\n }\n}\n\nfunction getHeapMax() {\n return 2147483648;\n}\nfunction _emscripten_get_now() {\n return typeof performance !== 'undefined' ? performance.now() : Date.now();\n}\nconst alignUp = (x, multiple) => x + ((multiple - (x % multiple)) % multiple);\nasync function main(init) {\n let wasmMemory;\n let buffer;\n const binding = {};\n function updateGlobalBufferAndViews(buf) {\n buffer = buf;\n binding.HEAPU8 = new Uint8Array(buf);\n binding.HEAPU32 = new Uint32Array(buf);\n }\n function _emscripten_memcpy_big(dest, src, num) {\n binding.HEAPU8.copyWithin(dest, src, src + num);\n }\n function emscripten_realloc_buffer(size) {\n try {\n wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16);\n updateGlobalBufferAndViews(wasmMemory.buffer);\n return 1;\n }\n catch { }\n }\n function _emscripten_resize_heap(requestedSize) {\n const oldSize = binding.HEAPU8.length;\n requestedSize = requestedSize >>> 0;\n const maxHeapSize = getHeapMax();\n if (requestedSize > maxHeapSize)\n return false;\n for (let cutDown = 1; cutDown <= 4; cutDown *= 2) {\n let overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);\n overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);\n const newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536));\n const replacement = emscripten_realloc_buffer(newSize);\n if (replacement)\n return true;\n }\n return false;\n }\n const UTF8Decoder = typeof TextDecoder != 'undefined' ? new TextDecoder('utf8') : undefined;\n function UTF8ArrayToString(heapOrArray, idx, maxBytesToRead = 1024) {\n const endIdx = idx + maxBytesToRead;\n let endPtr = idx;\n while (heapOrArray[endPtr] && !(endPtr >= endIdx))\n ++endPtr;\n if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {\n return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));\n }\n let str = '';\n while (idx < endPtr) {\n let u0 = heapOrArray[idx++];\n if (!(u0 & 128)) {\n str += String.fromCharCode(u0);\n continue;\n }\n const u1 = heapOrArray[idx++] & 63;\n if ((u0 & 224) === 192) {\n str += String.fromCharCode(((u0 & 31) << 6) | u1);\n continue;\n }\n const u2 = heapOrArray[idx++] & 63;\n if ((u0 & 240) === 224) {\n u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;\n }\n else {\n u0 = ((u0 & 7) << 18)\n | (u1 << 12)\n | (u2 << 6)\n | (heapOrArray[idx++] & 63);\n }\n if (u0 < 65536) {\n str += String.fromCharCode(u0);\n }\n else {\n const ch = u0 - 65536;\n str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023));\n }\n }\n return str;\n }\n function UTF8ToString(ptr, maxBytesToRead) {\n return ptr ? UTF8ArrayToString(binding.HEAPU8, ptr, maxBytesToRead) : '';\n }\n const asmLibraryArg = {\n emscripten_get_now: _emscripten_get_now,\n emscripten_memcpy_big: _emscripten_memcpy_big,\n emscripten_resize_heap: _emscripten_resize_heap,\n fd_write: () => 0,\n };\n async function createWasm() {\n const info = {\n env: asmLibraryArg,\n wasi_snapshot_preview1: asmLibraryArg,\n };\n const exports = await init(info);\n wasmMemory = exports.memory;\n updateGlobalBufferAndViews(wasmMemory.buffer);\n Object.assign(binding, exports);\n binding.UTF8ToString = UTF8ToString;\n }\n await createWasm();\n return binding;\n}\n\n/* ---------------------------------------------------------\n * Copyright (C) Microsoft Corporation. All rights reserved.\n *-------------------------------------------------------- */\nlet onigBinding = null;\n// let defaultDebugCall = false\nfunction throwLastOnigError(onigBinding) {\n throw new ShikiError(onigBinding.UTF8ToString(onigBinding.getLastOnigError()));\n}\nclass UtfString {\n static _utf8ByteLength(str) {\n let result = 0;\n for (let i = 0, len = str.length; i < len; i++) {\n const charCode = str.charCodeAt(i);\n let codepoint = charCode;\n let wasSurrogatePair = false;\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n // Hit a high surrogate, try to look for a matching low surrogate\n if (i + 1 < len) {\n const nextCharCode = str.charCodeAt(i + 1);\n if (nextCharCode >= 0xDC00 && nextCharCode <= 0xDFFF) {\n // Found the matching low surrogate\n codepoint = (((charCode - 0xD800) << 10) + 0x10000) | (nextCharCode - 0xDC00);\n wasSurrogatePair = true;\n }\n }\n }\n if (codepoint <= 0x7F)\n result += 1;\n else if (codepoint <= 0x7FF)\n result += 2;\n else if (codepoint <= 0xFFFF)\n result += 3;\n else\n result += 4;\n if (wasSurrogatePair)\n i++;\n }\n return result;\n }\n utf16Length;\n utf8Length;\n utf16Value;\n utf8Value;\n utf16OffsetToUtf8;\n utf8OffsetToUtf16;\n constructor(str) {\n const utf16Length = str.length;\n const utf8Length = UtfString._utf8ByteLength(str);\n const computeIndicesMapping = (utf8Length !== utf16Length);\n const utf16OffsetToUtf8 = computeIndicesMapping ? new Uint32Array(utf16Length + 1) : null;\n if (computeIndicesMapping)\n utf16OffsetToUtf8[utf16Length] = utf8Length;\n const utf8OffsetToUtf16 = computeIndicesMapping ? new Uint32Array(utf8Length + 1) : null;\n if (computeIndicesMapping)\n utf8OffsetToUtf16[utf8Length] = utf16Length;\n const utf8Value = new Uint8Array(utf8Length);\n let i8 = 0;\n for (let i16 = 0; i16 < utf16Length; i16++) {\n const charCode = str.charCodeAt(i16);\n let codePoint = charCode;\n let wasSurrogatePair = false;\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n // Hit a high surrogate, try to look for a matching low surrogate\n if (i16 + 1 < utf16Length) {\n const nextCharCode = str.charCodeAt(i16 + 1);\n if (nextCharCode >= 0xDC00 && nextCharCode <= 0xDFFF) {\n // Found the matching low surrogate\n codePoint = (((charCode - 0xD800) << 10) + 0x10000) | (nextCharCode - 0xDC00);\n wasSurrogatePair = true;\n }\n }\n }\n if (computeIndicesMapping) {\n utf16OffsetToUtf8[i16] = i8;\n if (wasSurrogatePair)\n utf16OffsetToUtf8[i16 + 1] = i8;\n if (codePoint <= 0x7F) {\n utf8OffsetToUtf16[i8 + 0] = i16;\n }\n else if (codePoint <= 0x7FF) {\n utf8OffsetToUtf16[i8 + 0] = i16;\n utf8OffsetToUtf16[i8 + 1] = i16;\n }\n else if (codePoint <= 0xFFFF) {\n utf8OffsetToUtf16[i8 + 0] = i16;\n utf8OffsetToUtf16[i8 + 1] = i16;\n utf8OffsetToUtf16[i8 + 2] = i16;\n }\n else {\n utf8OffsetToUtf16[i8 + 0] = i16;\n utf8OffsetToUtf16[i8 + 1] = i16;\n utf8OffsetToUtf16[i8 + 2] = i16;\n utf8OffsetToUtf16[i8 + 3] = i16;\n }\n }\n if (codePoint <= 0x7F) {\n utf8Value[i8++] = codePoint;\n }\n else if (codePoint <= 0x7FF) {\n utf8Value[i8++] = 0b11000000 | ((codePoint & 0b00000000000000000000011111000000) >>> 6);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n }\n else if (codePoint <= 0xFFFF) {\n utf8Value[i8++] = 0b11100000 | ((codePoint & 0b00000000000000001111000000000000) >>> 12);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n }\n else {\n utf8Value[i8++] = 0b11110000 | ((codePoint & 0b00000000000111000000000000000000) >>> 18);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000111111000000000000) >>> 12);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);\n utf8Value[i8++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);\n }\n if (wasSurrogatePair)\n i16++;\n }\n this.utf16Length = utf16Length;\n this.utf8Length = utf8Length;\n this.utf16Value = str;\n this.utf8Value = utf8Value;\n this.utf16OffsetToUtf8 = utf16OffsetToUtf8;\n this.utf8OffsetToUtf16 = utf8OffsetToUtf16;\n }\n createString(onigBinding) {\n const result = onigBinding.omalloc(this.utf8Length);\n onigBinding.HEAPU8.set(this.utf8Value, result);\n return result;\n }\n}\nclass OnigString {\n static LAST_ID = 0;\n static _sharedPtr = 0; // a pointer to a string of 10000 bytes\n static _sharedPtrInUse = false;\n id = (++OnigString.LAST_ID);\n _onigBinding;\n content;\n utf16Length;\n utf8Length;\n utf16OffsetToUtf8;\n utf8OffsetToUtf16;\n ptr;\n constructor(str) {\n if (!onigBinding)\n throw new ShikiError('Must invoke loadWasm first.');\n this._onigBinding = onigBinding;\n this.content = str;\n const utfString = new UtfString(str);\n this.utf16Length = utfString.utf16Length;\n this.utf8Length = utfString.utf8Length;\n this.utf16OffsetToUtf8 = utfString.utf16OffsetToUtf8;\n this.utf8OffsetToUtf16 = utfString.utf8OffsetToUtf16;\n if (this.utf8Length < 10000 && !OnigString._sharedPtrInUse) {\n if (!OnigString._sharedPtr)\n OnigString._sharedPtr = onigBinding.omalloc(10000);\n OnigString._sharedPtrInUse = true;\n onigBinding.HEAPU8.set(utfString.utf8Value, OnigString._sharedPtr);\n this.ptr = OnigString._sharedPtr;\n }\n else {\n this.ptr = utfString.createString(onigBinding);\n }\n }\n convertUtf8OffsetToUtf16(utf8Offset) {\n if (this.utf8OffsetToUtf16) {\n if (utf8Offset < 0)\n return 0;\n if (utf8Offset > this.utf8Length)\n return this.utf16Length;\n return this.utf8OffsetToUtf16[utf8Offset];\n }\n return utf8Offset;\n }\n convertUtf16OffsetToUtf8(utf16Offset) {\n if (this.utf16OffsetToUtf8) {\n if (utf16Offset < 0)\n return 0;\n if (utf16Offset > this.utf16Length)\n return this.utf8Length;\n return this.utf16OffsetToUtf8[utf16Offset];\n }\n return utf16Offset;\n }\n dispose() {\n if (this.ptr === OnigString._sharedPtr)\n OnigString._sharedPtrInUse = false;\n else\n this._onigBinding.ofree(this.ptr);\n }\n}\nclass OnigScanner {\n _onigBinding;\n _ptr;\n constructor(patterns) {\n if (!onigBinding)\n throw new ShikiError('Must invoke loadWasm first.');\n const strPtrsArr = [];\n const strLenArr = [];\n for (let i = 0, len = patterns.length; i < len; i++) {\n const utfString = new UtfString(patterns[i]);\n strPtrsArr[i] = utfString.createString(onigBinding);\n strLenArr[i] = utfString.utf8Length;\n }\n const strPtrsPtr = onigBinding.omalloc(4 * patterns.length);\n onigBinding.HEAPU32.set(strPtrsArr, strPtrsPtr / 4);\n const strLenPtr = onigBinding.omalloc(4 * patterns.length);\n onigBinding.HEAPU32.set(strLenArr, strLenPtr / 4);\n const scannerPtr = onigBinding.createOnigScanner(strPtrsPtr, strLenPtr, patterns.length);\n for (let i = 0, len = patterns.length; i < len; i++)\n onigBinding.ofree(strPtrsArr[i]);\n onigBinding.ofree(strLenPtr);\n onigBinding.ofree(strPtrsPtr);\n if (scannerPtr === 0)\n throwLastOnigError(onigBinding);\n this._onigBinding = onigBinding;\n this._ptr = scannerPtr;\n }\n dispose() {\n this._onigBinding.freeOnigScanner(this._ptr);\n }\n findNextMatchSync(string, startPosition, arg) {\n // let debugCall = defaultDebugCall\n let options = 0 /* FindOption.None */;\n if (typeof arg === 'number') {\n // if (arg & FindOption.DebugCall)\n // debugCall = true\n options = arg;\n }\n if (typeof string === 'string') {\n string = new OnigString(string);\n const result = this._findNextMatchSync(string, startPosition, false, options);\n string.dispose();\n return result;\n }\n return this._findNextMatchSync(string, startPosition, false, options);\n }\n _findNextMatchSync(string, startPosition, debugCall, options) {\n const onigBinding = this._onigBinding;\n // let resultPtr: Pointer\n // if (debugCall)\n // resultPtr = onigBinding.findNextOnigScannerMatchDbg(this._ptr, string.id, string.ptr, string.utf8Length, string.convertUtf16OffsetToUtf8(startPosition), options)\n // else\n const resultPtr = onigBinding.findNextOnigScannerMatch(this._ptr, string.id, string.ptr, string.utf8Length, string.convertUtf16OffsetToUtf8(startPosition), options);\n if (resultPtr === 0) {\n // no match\n return null;\n }\n const HEAPU32 = onigBinding.HEAPU32;\n let offset = resultPtr / 4; // byte offset -> uint32 offset\n const index = HEAPU32[offset++];\n const count = HEAPU32[offset++];\n const captureIndices = [];\n for (let i = 0; i < count; i++) {\n const beg = string.convertUtf8OffsetToUtf16(HEAPU32[offset++]);\n const end = string.convertUtf8OffsetToUtf16(HEAPU32[offset++]);\n captureIndices[i] = {\n start: beg,\n end,\n length: end - beg,\n };\n }\n return {\n index,\n captureIndices,\n };\n }\n}\nfunction isInstantiatorOptionsObject(dataOrOptions) {\n return (typeof dataOrOptions.instantiator === 'function');\n}\nfunction isInstantiatorModule(dataOrOptions) {\n return (typeof dataOrOptions.default === 'function');\n}\nfunction isDataOptionsObject(dataOrOptions) {\n return (typeof dataOrOptions.data !== 'undefined');\n}\nfunction isResponse(dataOrOptions) {\n return (typeof Response !== 'undefined' && dataOrOptions instanceof Response);\n}\nfunction isArrayBuffer(data) {\n return (typeof ArrayBuffer !== 'undefined' && (data instanceof ArrayBuffer || ArrayBuffer.isView(data)))\n // eslint-disable-next-line node/prefer-global/buffer\n || (typeof Buffer !== 'undefined' && Buffer.isBuffer?.(data))\n || (typeof SharedArrayBuffer !== 'undefined' && data instanceof SharedArrayBuffer)\n || (typeof Uint32Array !== 'undefined' && data instanceof Uint32Array);\n}\nlet initPromise;\nfunction loadWasm(options) {\n if (initPromise)\n return initPromise;\n async function _load() {\n onigBinding = await main(async (info) => {\n let instance = options;\n instance = await instance;\n if (typeof instance === 'function')\n instance = await instance(info);\n if (typeof instance === 'function')\n instance = await instance(info);\n if (isInstantiatorOptionsObject(instance)) {\n instance = await instance.instantiator(info);\n }\n else if (isInstantiatorModule(instance)) {\n instance = await instance.default(info);\n }\n else {\n if (isDataOptionsObject(instance))\n instance = instance.data;\n if (isResponse(instance)) {\n if (typeof WebAssembly.instantiateStreaming === 'function')\n instance = await _makeResponseStreamingLoader(instance)(info);\n else\n instance = await _makeResponseNonStreamingLoader(instance)(info);\n }\n else if (isArrayBuffer(instance)) {\n instance = await _makeArrayBufferLoader(instance)(info);\n }\n // import(\"shiki/onig.wasm\") returns `{ default: WebAssembly.Module }` on cloudflare workers\n // https://developers.cloudflare.com/workers/wrangler/bundling/\n else if (instance instanceof WebAssembly.Module) {\n instance = await _makeArrayBufferLoader(instance)(info);\n }\n else if ('default' in instance && instance.default instanceof WebAssembly.Module) {\n instance = await _makeArrayBufferLoader(instance.default)(info);\n }\n }\n if ('instance' in instance)\n instance = instance.instance;\n if ('exports' in instance)\n instance = instance.exports;\n return instance;\n });\n }\n initPromise = _load();\n return initPromise;\n}\nfunction _makeArrayBufferLoader(data) {\n return importObject => WebAssembly.instantiate(data, importObject);\n}\nfunction _makeResponseStreamingLoader(data) {\n return importObject => WebAssembly.instantiateStreaming(data, importObject);\n}\nfunction _makeResponseNonStreamingLoader(data) {\n return async (importObject) => {\n const arrayBuffer = await data.arrayBuffer();\n return WebAssembly.instantiate(arrayBuffer, importObject);\n };\n}\n// export function createOnigString(str: string) {\n// return new OnigString(str)\n// }\n// export function createOnigScanner(patterns: string[]) {\n// return new OnigScanner(patterns)\n// }\n// export function setDefaultDebugCall(_defaultDebugCall: boolean): void {\n// defaultDebugCall = _defaultDebugCall\n// }\n\nlet _defaultWasmLoader;\n/**\n * Set the default wasm loader for `loadWasm`.\n * @internal\n */\nfunction setDefaultWasmLoader(_loader) {\n _defaultWasmLoader = _loader;\n}\n/**\n * @internal\n */\nfunction getDefaultWasmLoader() {\n return _defaultWasmLoader;\n}\nasync function createOnigurumaEngine(options) {\n if (options)\n await loadWasm(options);\n return {\n createScanner(patterns) {\n return new OnigScanner(patterns);\n },\n createString(s) {\n return new OnigString(s);\n },\n };\n}\n/**\n * Deprecated. Use `createOnigurumaEngine` instead.\n */\nasync function createWasmOnigEngine(options) {\n return createOnigurumaEngine(options);\n}\n\nexport { createOnigurumaEngine, createWasmOnigEngine, getDefaultWasmLoader, loadWasm, setDefaultWasmLoader };\n","let emitDeprecation = false;\nfunction enableDeprecationWarnings(value = true) {\n emitDeprecation = value;\n}\nfunction warnDeprecated(message) {\n if (emitDeprecation)\n console.trace(`[SHIKI DEPRECATE]: ${message}`);\n}\n\nexport { enableDeprecationWarnings as e, warnDeprecated as w };\n","// src/utils.ts\nfunction clone(something) {\n return doClone(something);\n}\nfunction doClone(something) {\n if (Array.isArray(something)) {\n return cloneArray(something);\n }\n if (typeof something === \"object\") {\n return cloneObj(something);\n }\n return something;\n}\nfunction cloneArray(arr) {\n let r = [];\n for (let i = 0, len = arr.length; i < len; i++) {\n r[i] = doClone(arr[i]);\n }\n return r;\n}\nfunction cloneObj(obj) {\n let r = {};\n for (let key in obj) {\n r[key] = doClone(obj[key]);\n }\n return r;\n}\nfunction mergeObjects(target, ...sources) {\n sources.forEach((source) => {\n for (let key in source) {\n target[key] = source[key];\n }\n });\n return target;\n}\nfunction basename(path) {\n const idx = ~path.lastIndexOf(\"/\") || ~path.lastIndexOf(\"\\\\\");\n if (idx === 0) {\n return path;\n } else if (~idx === path.length - 1) {\n return basename(path.substring(0, path.length - 1));\n } else {\n return path.substr(~idx + 1);\n }\n}\nvar CAPTURING_REGEX_SOURCE = /\\$(\\d+)|\\${(\\d+):\\/(downcase|upcase)}/g;\nvar RegexSource = class {\n static hasCaptures(regexSource) {\n if (regexSource === null) {\n return false;\n }\n CAPTURING_REGEX_SOURCE.lastIndex = 0;\n return CAPTURING_REGEX_SOURCE.test(regexSource);\n }\n static replaceCaptures(regexSource, captureSource, captureIndices) {\n return regexSource.replace(CAPTURING_REGEX_SOURCE, (match, index, commandIndex, command) => {\n let capture = captureIndices[parseInt(index || commandIndex, 10)];\n if (capture) {\n let result = captureSource.substring(capture.start, capture.end);\n while (result[0] === \".\") {\n result = result.substring(1);\n }\n switch (command) {\n case \"downcase\":\n return result.toLowerCase();\n case \"upcase\":\n return result.toUpperCase();\n default:\n return result;\n }\n } else {\n return match;\n }\n });\n }\n};\nfunction strcmp(a, b) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n}\nfunction strArrCmp(a, b) {\n if (a === null && b === null) {\n return 0;\n }\n if (!a) {\n return -1;\n }\n if (!b) {\n return 1;\n }\n let len1 = a.length;\n let len2 = b.length;\n if (len1 === len2) {\n for (let i = 0; i < len1; i++) {\n let res = strcmp(a[i], b[i]);\n if (res !== 0) {\n return res;\n }\n }\n return 0;\n }\n return len1 - len2;\n}\nfunction isValidHexColor(hex) {\n if (/^#[0-9a-f]{6}$/i.test(hex)) {\n return true;\n }\n if (/^#[0-9a-f]{8}$/i.test(hex)) {\n return true;\n }\n if (/^#[0-9a-f]{3}$/i.test(hex)) {\n return true;\n }\n if (/^#[0-9a-f]{4}$/i.test(hex)) {\n return true;\n }\n return false;\n}\nfunction escapeRegExpCharacters(value) {\n return value.replace(/[\\-\\\\\\{\\}\\*\\+\\?\\|\\^\\$\\.\\,\\[\\]\\(\\)\\#\\s]/g, \"\\\\$&\");\n}\nvar CachedFn = class {\n constructor(fn) {\n this.fn = fn;\n this.cache = /* @__PURE__ */ new Map();\n }\n get(key) {\n if (this.cache.has(key)) {\n return this.cache.get(key);\n }\n const value = this.fn(key);\n this.cache.set(key, value);\n return value;\n }\n};\n\n// src/theme.ts\nvar Theme = class {\n constructor(_colorMap, _defaults, _root) {\n this._colorMap = _colorMap;\n this._defaults = _defaults;\n this._root = _root;\n this._cachedMatchRoot = new CachedFn(\n (scopeName) => this._root.match(scopeName)\n );\n }\n static createFromRawTheme(source, colorMap) {\n return this.createFromParsedTheme(parseTheme(source), colorMap);\n }\n static createFromParsedTheme(source, colorMap) {\n return resolveParsedThemeRules(source, colorMap);\n }\n getColorMap() {\n return this._colorMap.getColorMap();\n }\n getDefaults() {\n return this._defaults;\n }\n match(scopePath) {\n if (scopePath === null) {\n return this._defaults;\n }\n const scopeName = scopePath.scopeName;\n const matchingTrieElements = this._cachedMatchRoot.get(scopeName);\n const effectiveRule = matchingTrieElements.find(\n (v) => _scopePathMatchesParentScopes(scopePath.parent, v.parentScopes)\n );\n if (!effectiveRule) {\n return null;\n }\n return new StyleAttributes(\n effectiveRule.fontStyle,\n effectiveRule.foreground,\n effectiveRule.background\n );\n }\n};\nvar ScopeStack = class _ScopeStack {\n constructor(parent, scopeName) {\n this.parent = parent;\n this.scopeName = scopeName;\n }\n static push(path, scopeNames) {\n for (const name of scopeNames) {\n path = new _ScopeStack(path, name);\n }\n return path;\n }\n static from(...segments) {\n let result = null;\n for (let i = 0; i < segments.length; i++) {\n result = new _ScopeStack(result, segments[i]);\n }\n return result;\n }\n push(scopeName) {\n return new _ScopeStack(this, scopeName);\n }\n getSegments() {\n let item = this;\n const result = [];\n while (item) {\n result.push(item.scopeName);\n item = item.parent;\n }\n result.reverse();\n return result;\n }\n toString() {\n return this.getSegments().join(\" \");\n }\n extends(other) {\n if (this === other) {\n return true;\n }\n if (this.parent === null) {\n return false;\n }\n return this.parent.extends(other);\n }\n getExtensionIfDefined(base) {\n const result = [];\n let item = this;\n while (item && item !== base) {\n result.push(item.scopeName);\n item = item.parent;\n }\n return item === base ? result.reverse() : void 0;\n }\n};\nfunction _scopePathMatchesParentScopes(scopePath, parentScopes) {\n if (parentScopes.length === 0) {\n return true;\n }\n for (let index = 0; index < parentScopes.length; index++) {\n let scopePattern = parentScopes[index];\n let scopeMustMatch = false;\n if (scopePattern === \">\") {\n if (index === parentScopes.length - 1) {\n return false;\n }\n scopePattern = parentScopes[++index];\n scopeMustMatch = true;\n }\n while (scopePath) {\n if (_matchesScope(scopePath.scopeName, scopePattern)) {\n break;\n }\n if (scopeMustMatch) {\n return false;\n }\n scopePath = scopePath.parent;\n }\n if (!scopePath) {\n return false;\n }\n scopePath = scopePath.parent;\n }\n return true;\n}\nfunction _matchesScope(scopeName, scopePattern) {\n return scopePattern === scopeName || scopeName.startsWith(scopePattern) && scopeName[scopePattern.length] === \".\";\n}\nvar StyleAttributes = class {\n constructor(fontStyle, foregroundId, backgroundId) {\n this.fontStyle = fontStyle;\n this.foregroundId = foregroundId;\n this.backgroundId = backgroundId;\n }\n};\nfunction parseTheme(source) {\n if (!source) {\n return [];\n }\n if (!source.settings || !Array.isArray(source.settings)) {\n return [];\n }\n let settings = source.settings;\n let result = [], resultLen = 0;\n for (let i = 0, len = settings.length; i < len; i++) {\n let entry = settings[i];\n if (!entry.settings) {\n continue;\n }\n let scopes;\n if (typeof entry.scope === \"string\") {\n let _scope = entry.scope;\n _scope = _scope.replace(/^[,]+/, \"\");\n _scope = _scope.replace(/[,]+$/, \"\");\n scopes = _scope.split(\",\");\n } else if (Array.isArray(entry.scope)) {\n scopes = entry.scope;\n } else {\n scopes = [\"\"];\n }\n let fontStyle = -1 /* NotSet */;\n if (typeof entry.settings.fontStyle === \"string\") {\n fontStyle = 0 /* None */;\n let segments = entry.settings.fontStyle.split(\" \");\n for (let j = 0, lenJ = segments.length; j < lenJ; j++) {\n let segment = segments[j];\n switch (segment) {\n case \"italic\":\n fontStyle = fontStyle | 1 /* Italic */;\n break;\n case \"bold\":\n fontStyle = fontStyle | 2 /* Bold */;\n break;\n case \"underline\":\n fontStyle = fontStyle | 4 /* Underline */;\n break;\n case \"strikethrough\":\n fontStyle = fontStyle | 8 /* Strikethrough */;\n break;\n }\n }\n }\n let foreground = null;\n if (typeof entry.settings.foreground === \"string\" && isValidHexColor(entry.settings.foreground)) {\n foreground = entry.settings.foreground;\n }\n let background = null;\n if (typeof entry.settings.background === \"string\" && isValidHexColor(entry.settings.background)) {\n background = entry.settings.background;\n }\n for (let j = 0, lenJ = scopes.length; j < lenJ; j++) {\n let _scope = scopes[j].trim();\n let segments = _scope.split(\" \");\n let scope = segments[segments.length - 1];\n let parentScopes = null;\n if (segments.length > 1) {\n parentScopes = segments.slice(0, segments.length - 1);\n parentScopes.reverse();\n }\n result[resultLen++] = new ParsedThemeRule(\n scope,\n parentScopes,\n i,\n fontStyle,\n foreground,\n background\n );\n }\n }\n return result;\n}\nvar ParsedThemeRule = class {\n constructor(scope, parentScopes, index, fontStyle, foreground, background) {\n this.scope = scope;\n this.parentScopes = parentScopes;\n this.index = index;\n this.fontStyle = fontStyle;\n this.foreground = foreground;\n this.background = background;\n }\n};\nvar FontStyle = /* @__PURE__ */ ((FontStyle2) => {\n FontStyle2[FontStyle2[\"NotSet\"] = -1] = \"NotSet\";\n FontStyle2[FontStyle2[\"None\"] = 0] = \"None\";\n FontStyle2[FontStyle2[\"Italic\"] = 1] = \"Italic\";\n FontStyle2[FontStyle2[\"Bold\"] = 2] = \"Bold\";\n FontStyle2[FontStyle2[\"Underline\"] = 4] = \"Underline\";\n FontStyle2[FontStyle2[\"Strikethrough\"] = 8] = \"Strikethrough\";\n return FontStyle2;\n})(FontStyle || {});\nfunction resolveParsedThemeRules(parsedThemeRules, _colorMap) {\n parsedThemeRules.sort((a, b) => {\n let r = strcmp(a.scope, b.scope);\n if (r !== 0) {\n return r;\n }\n r = strArrCmp(a.parentScopes, b.parentScopes);\n if (r !== 0) {\n return r;\n }\n return a.index - b.index;\n });\n let defaultFontStyle = 0 /* None */;\n let defaultForeground = \"#000000\";\n let defaultBackground = \"#ffffff\";\n while (parsedThemeRules.length >= 1 && parsedThemeRules[0].scope === \"\") {\n let incomingDefaults = parsedThemeRules.shift();\n if (incomingDefaults.fontStyle !== -1 /* NotSet */) {\n defaultFontStyle = incomingDefaults.fontStyle;\n }\n if (incomingDefaults.foreground !== null) {\n defaultForeground = incomingDefaults.foreground;\n }\n if (incomingDefaults.background !== null) {\n defaultBackground = incomingDefaults.background;\n }\n }\n let colorMap = new ColorMap(_colorMap);\n let defaults = new StyleAttributes(defaultFontStyle, colorMap.getId(defaultForeground), colorMap.getId(defaultBackground));\n let root = new ThemeTrieElement(new ThemeTrieElementRule(0, null, -1 /* NotSet */, 0, 0), []);\n for (let i = 0, len = parsedThemeRules.length; i < len; i++) {\n let rule = parsedThemeRules[i];\n root.insert(0, rule.scope, rule.parentScopes, rule.fontStyle, colorMap.getId(rule.foreground), colorMap.getId(rule.background));\n }\n return new Theme(colorMap, defaults, root);\n}\nvar ColorMap = class {\n constructor(_colorMap) {\n this._lastColorId = 0;\n this._id2color = [];\n this._color2id = /* @__PURE__ */ Object.create(null);\n if (Array.isArray(_colorMap)) {\n this._isFrozen = true;\n for (let i = 0, len = _colorMap.length; i < len; i++) {\n this._color2id[_colorMap[i]] = i;\n this._id2color[i] = _colorMap[i];\n }\n } else {\n this._isFrozen = false;\n }\n }\n getId(color) {\n if (color === null) {\n return 0;\n }\n color = color.toUpperCase();\n let value = this._color2id[color];\n if (value) {\n return value;\n }\n if (this._isFrozen) {\n throw new Error(`Missing color in color map - ${color}`);\n }\n value = ++this._lastColorId;\n this._color2id[color] = value;\n this._id2color[value] = color;\n return value;\n }\n getColorMap() {\n return this._id2color.slice(0);\n }\n};\nvar emptyParentScopes = Object.freeze([]);\nvar ThemeTrieElementRule = class _ThemeTrieElementRule {\n constructor(scopeDepth, parentScopes, fontStyle, foreground, background) {\n this.scopeDepth = scopeDepth;\n this.parentScopes = parentScopes || emptyParentScopes;\n this.fontStyle = fontStyle;\n this.foreground = foreground;\n this.background = background;\n }\n clone() {\n return new _ThemeTrieElementRule(this.scopeDepth, this.parentScopes, this.fontStyle, this.foreground, this.background);\n }\n static cloneArr(arr) {\n let r = [];\n for (let i = 0, len = arr.length; i < len; i++) {\n r[i] = arr[i].clone();\n }\n return r;\n }\n acceptOverwrite(scopeDepth, fontStyle, foreground, background) {\n if (this.scopeDepth > scopeDepth) {\n console.log(\"how did this happen?\");\n } else {\n this.scopeDepth = scopeDepth;\n }\n if (fontStyle !== -1 /* NotSet */) {\n this.fontStyle = fontStyle;\n }\n if (foreground !== 0) {\n this.foreground = foreground;\n }\n if (background !== 0) {\n this.background = background;\n }\n }\n};\nvar ThemeTrieElement = class _ThemeTrieElement {\n constructor(_mainRule, rulesWithParentScopes = [], _children = {}) {\n this._mainRule = _mainRule;\n this._children = _children;\n this._rulesWithParentScopes = rulesWithParentScopes;\n }\n static _cmpBySpecificity(a, b) {\n if (a.scopeDepth !== b.scopeDepth) {\n return b.scopeDepth - a.scopeDepth;\n }\n let aParentIndex = 0;\n let bParentIndex = 0;\n while (true) {\n if (a.parentScopes[aParentIndex] === \">\") {\n aParentIndex++;\n }\n if (b.parentScopes[bParentIndex] === \">\") {\n bParentIndex++;\n }\n if (aParentIndex >= a.parentScopes.length || bParentIndex >= b.parentScopes.length) {\n break;\n }\n const parentScopeLengthDiff = b.parentScopes[bParentIndex].length - a.parentScopes[aParentIndex].length;\n if (parentScopeLengthDiff !== 0) {\n return parentScopeLengthDiff;\n }\n aParentIndex++;\n bParentIndex++;\n }\n return b.parentScopes.length - a.parentScopes.length;\n }\n match(scope) {\n if (scope !== \"\") {\n let dotIndex = scope.indexOf(\".\");\n let head;\n let tail;\n if (dotIndex === -1) {\n head = scope;\n tail = \"\";\n } else {\n head = scope.substring(0, dotIndex);\n tail = scope.substring(dotIndex + 1);\n }\n if (this._children.hasOwnProperty(head)) {\n return this._children[head].match(tail);\n }\n }\n const rules = this._rulesWithParentScopes.concat(this._mainRule);\n rules.sort(_ThemeTrieElement._cmpBySpecificity);\n return rules;\n }\n insert(scopeDepth, scope, parentScopes, fontStyle, foreground, background) {\n if (scope === \"\") {\n this._doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background);\n return;\n }\n let dotIndex = scope.indexOf(\".\");\n let head;\n let tail;\n if (dotIndex === -1) {\n head = scope;\n tail = \"\";\n } else {\n head = scope.substring(0, dotIndex);\n tail = scope.substring(dotIndex + 1);\n }\n let child;\n if (this._children.hasOwnProperty(head)) {\n child = this._children[head];\n } else {\n child = new _ThemeTrieElement(this._mainRule.clone(), ThemeTrieElementRule.cloneArr(this._rulesWithParentScopes));\n this._children[head] = child;\n }\n child.insert(scopeDepth + 1, tail, parentScopes, fontStyle, foreground, background);\n }\n _doInsertHere(scopeDepth, parentScopes, fontStyle, foreground, background) {\n if (parentScopes === null) {\n this._mainRule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);\n return;\n }\n for (let i = 0, len = this._rulesWithParentScopes.length; i < len; i++) {\n let rule = this._rulesWithParentScopes[i];\n if (strArrCmp(rule.parentScopes, parentScopes) === 0) {\n rule.acceptOverwrite(scopeDepth, fontStyle, foreground, background);\n return;\n }\n }\n if (fontStyle === -1 /* NotSet */) {\n fontStyle = this._mainRule.fontStyle;\n }\n if (foreground === 0) {\n foreground = this._mainRule.foreground;\n }\n if (background === 0) {\n background = this._mainRule.background;\n }\n this._rulesWithParentScopes.push(new ThemeTrieElementRule(scopeDepth, parentScopes, fontStyle, foreground, background));\n }\n};\n\n// src/encodedTokenAttributes.ts\nvar EncodedTokenMetadata = class _EncodedTokenMetadata {\n static toBinaryStr(encodedTokenAttributes) {\n return encodedTokenAttributes.toString(2).padStart(32, \"0\");\n }\n static print(encodedTokenAttributes) {\n const languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);\n const tokenType = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);\n const fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);\n const foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);\n const background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);\n console.log({\n languageId,\n tokenType,\n fontStyle,\n foreground,\n background\n });\n }\n static getLanguageId(encodedTokenAttributes) {\n return (encodedTokenAttributes & 255 /* LANGUAGEID_MASK */) >>> 0 /* LANGUAGEID_OFFSET */;\n }\n static getTokenType(encodedTokenAttributes) {\n return (encodedTokenAttributes & 768 /* TOKEN_TYPE_MASK */) >>> 8 /* TOKEN_TYPE_OFFSET */;\n }\n static containsBalancedBrackets(encodedTokenAttributes) {\n return (encodedTokenAttributes & 1024 /* BALANCED_BRACKETS_MASK */) !== 0;\n }\n static getFontStyle(encodedTokenAttributes) {\n return (encodedTokenAttributes & 30720 /* FONT_STYLE_MASK */) >>> 11 /* FONT_STYLE_OFFSET */;\n }\n static getForeground(encodedTokenAttributes) {\n return (encodedTokenAttributes & 16744448 /* FOREGROUND_MASK */) >>> 15 /* FOREGROUND_OFFSET */;\n }\n static getBackground(encodedTokenAttributes) {\n return (encodedTokenAttributes & 4278190080 /* BACKGROUND_MASK */) >>> 24 /* BACKGROUND_OFFSET */;\n }\n /**\n * Updates the fields in `metadata`.\n * A value of `0`, `NotSet` or `null` indicates that the corresponding field should be left as is.\n */\n static set(encodedTokenAttributes, languageId, tokenType, containsBalancedBrackets, fontStyle, foreground, background) {\n let _languageId = _EncodedTokenMetadata.getLanguageId(encodedTokenAttributes);\n let _tokenType = _EncodedTokenMetadata.getTokenType(encodedTokenAttributes);\n let _containsBalancedBracketsBit = _EncodedTokenMetadata.containsBalancedBrackets(encodedTokenAttributes) ? 1 : 0;\n let _fontStyle = _EncodedTokenMetadata.getFontStyle(encodedTokenAttributes);\n let _foreground = _EncodedTokenMetadata.getForeground(encodedTokenAttributes);\n let _background = _EncodedTokenMetadata.getBackground(encodedTokenAttributes);\n if (languageId !== 0) {\n _languageId = languageId;\n }\n if (tokenType !== 8 /* NotSet */) {\n _tokenType = fromOptionalTokenType(tokenType);\n }\n if (containsBalancedBrackets !== null) {\n _containsBalancedBracketsBit = containsBalancedBrackets ? 1 : 0;\n }\n if (fontStyle !== -1 /* NotSet */) {\n _fontStyle = fontStyle;\n }\n if (foreground !== 0) {\n _foreground = foreground;\n }\n if (background !== 0) {\n _background = background;\n }\n return (_languageId << 0 /* LANGUAGEID_OFFSET */ | _tokenType << 8 /* TOKEN_TYPE_OFFSET */ | _containsBalancedBracketsBit << 10 /* BALANCED_BRACKETS_OFFSET */ | _fontStyle << 11 /* FONT_STYLE_OFFSET */ | _foreground << 15 /* FOREGROUND_OFFSET */ | _background << 24 /* BACKGROUND_OFFSET */) >>> 0;\n }\n};\nfunction toOptionalTokenType(standardType) {\n return standardType;\n}\nfunction fromOptionalTokenType(standardType) {\n return standardType;\n}\n\n// src/matcher.ts\nfunction createMatchers(selector, matchesName) {\n const results = [];\n const tokenizer = newTokenizer(selector);\n let token = tokenizer.next();\n while (token !== null) {\n let priority = 0;\n if (token.length === 2 && token.charAt(1) === \":\") {\n switch (token.charAt(0)) {\n case \"R\":\n priority = 1;\n break;\n case \"L\":\n priority = -1;\n break;\n default:\n console.log(`Unknown priority ${token} in scope selector`);\n }\n token = tokenizer.next();\n }\n let matcher = parseConjunction();\n results.push({ matcher, priority });\n if (token !== \",\") {\n break;\n }\n token = tokenizer.next();\n }\n return results;\n function parseOperand() {\n if (token === \"-\") {\n token = tokenizer.next();\n const expressionToNegate = parseOperand();\n return (matcherInput) => !!expressionToNegate && !expressionToNegate(matcherInput);\n }\n if (token === \"(\") {\n token = tokenizer.next();\n const expressionInParents = parseInnerExpression();\n if (token === \")\") {\n token = tokenizer.next();\n }\n return expressionInParents;\n }\n if (isIdentifier(token)) {\n const identifiers = [];\n do {\n identifiers.push(token);\n token = tokenizer.next();\n } while (isIdentifier(token));\n return (matcherInput) => matchesName(identifiers, matcherInput);\n }\n return null;\n }\n function parseConjunction() {\n const matchers = [];\n let matcher = parseOperand();\n while (matcher) {\n matchers.push(matcher);\n matcher = parseOperand();\n }\n return (matcherInput) => matchers.every((matcher2) => matcher2(matcherInput));\n }\n function parseInnerExpression() {\n const matchers = [];\n let matcher = parseConjunction();\n while (matcher) {\n matchers.push(matcher);\n if (token === \"|\" || token === \",\") {\n do {\n token = tokenizer.next();\n } while (token === \"|\" || token === \",\");\n } else {\n break;\n }\n matcher = parseConjunction();\n }\n return (matcherInput) => matchers.some((matcher2) => matcher2(matcherInput));\n }\n}\nfunction isIdentifier(token) {\n return !!token && !!token.match(/[\\w\\.:]+/);\n}\nfunction newTokenizer(input) {\n let regex = /([LR]:|[\\w\\.:][\\w\\.:\\-]*|[\\,\\|\\-\\(\\)])/g;\n let match = regex.exec(input);\n return {\n next: () => {\n if (!match) {\n return null;\n }\n const res = match[0];\n match = regex.exec(input);\n return res;\n }\n };\n}\n\n// src/onigLib.ts\nvar FindOption = /* @__PURE__ */ ((FindOption2) => {\n FindOption2[FindOption2[\"None\"] = 0] = \"None\";\n FindOption2[FindOption2[\"NotBeginString\"] = 1] = \"NotBeginString\";\n FindOption2[FindOption2[\"NotEndString\"] = 2] = \"NotEndString\";\n FindOption2[FindOption2[\"NotBeginPosition\"] = 4] = \"NotBeginPosition\";\n FindOption2[FindOption2[\"DebugCall\"] = 8] = \"DebugCall\";\n return FindOption2;\n})(FindOption || {});\nfunction disposeOnigString(str) {\n if (typeof str.dispose === \"function\") {\n str.dispose();\n }\n}\n\n// src/grammar/grammarDependencies.ts\nvar TopLevelRuleReference = class {\n constructor(scopeName) {\n this.scopeName = scopeName;\n }\n toKey() {\n return this.scopeName;\n }\n};\nvar TopLevelRepositoryRuleReference = class {\n constructor(scopeName, ruleName) {\n this.scopeName = scopeName;\n this.ruleName = ruleName;\n }\n toKey() {\n return `${this.scopeName}#${this.ruleName}`;\n }\n};\nvar ExternalReferenceCollector = class {\n constructor() {\n this._references = [];\n this._seenReferenceKeys = /* @__PURE__ */ new Set();\n this.visitedRule = /* @__PURE__ */ new Set();\n }\n get references() {\n return this._references;\n }\n add(reference) {\n const key = reference.toKey();\n if (this._seenReferenceKeys.has(key)) {\n return;\n }\n this._seenReferenceKeys.add(key);\n this._references.push(reference);\n }\n};\nvar ScopeDependencyProcessor = class {\n constructor(repo, initialScopeName) {\n this.repo = repo;\n this.initialScopeName = initialScopeName;\n this.seenFullScopeRequests = /* @__PURE__ */ new Set();\n this.seenPartialScopeRequests = /* @__PURE__ */ new Set();\n this.seenFullScopeRequests.add(this.initialScopeName);\n this.Q = [new TopLevelRuleReference(this.initialScopeName)];\n }\n processQueue() {\n const q = this.Q;\n this.Q = [];\n const deps = new ExternalReferenceCollector();\n for (const dep of q) {\n collectReferencesOfReference(dep, this.initialScopeName, this.repo, deps);\n }\n for (const dep of deps.references) {\n if (dep instanceof TopLevelRuleReference) {\n if (this.seenFullScopeRequests.has(dep.scopeName)) {\n continue;\n }\n this.seenFullScopeRequests.add(dep.scopeName);\n this.Q.push(dep);\n } else {\n if (this.seenFullScopeRequests.has(dep.scopeName)) {\n continue;\n }\n if (this.seenPartialScopeRequests.has(dep.toKey())) {\n continue;\n }\n this.seenPartialScopeRequests.add(dep.toKey());\n this.Q.push(dep);\n }\n }\n }\n};\nfunction collectReferencesOfReference(reference, baseGrammarScopeName, repo, result) {\n const selfGrammar = repo.lookup(reference.scopeName);\n if (!selfGrammar) {\n if (reference.scopeName === baseGrammarScopeName) {\n throw new Error(`No grammar provided for <${baseGrammarScopeName}>`);\n }\n return;\n }\n const baseGrammar = repo.lookup(baseGrammarScopeName);\n if (reference instanceof TopLevelRuleReference) {\n collectExternalReferencesInTopLevelRule({ baseGrammar, selfGrammar }, result);\n } else {\n collectExternalReferencesInTopLevelRepositoryRule(\n reference.ruleName,\n { baseGrammar, selfGrammar, repository: selfGrammar.repository },\n result\n );\n }\n const injections = repo.injections(reference.scopeName);\n if (injections) {\n for (const injection of injections) {\n result.add(new TopLevelRuleReference(injection));\n }\n }\n}\nfunction collectExternalReferencesInTopLevelRepositoryRule(ruleName, context, result) {\n if (context.repository && context.repository[ruleName]) {\n const rule = context.repository[ruleName];\n collectExternalReferencesInRules([rule], context, result);\n }\n}\nfunction collectExternalReferencesInTopLevelRule(context, result) {\n if (context.selfGrammar.patterns && Array.isArray(context.selfGrammar.patterns)) {\n collectExternalReferencesInRules(\n context.selfGrammar.patterns,\n { ...context, repository: context.selfGrammar.repository },\n result\n );\n }\n if (context.selfGrammar.injections) {\n collectExternalReferencesInRules(\n Object.values(context.selfGrammar.injections),\n { ...context, repository: context.selfGrammar.repository },\n result\n );\n }\n}\nfunction collectExternalReferencesInRules(rules, context, result) {\n for (const rule of rules) {\n if (result.visitedRule.has(rule)) {\n continue;\n }\n result.visitedRule.add(rule);\n const patternRepository = rule.repository ? mergeObjects({}, context.repository, rule.repository) : context.repository;\n if (Array.isArray(rule.patterns)) {\n collectExternalReferencesInRules(rule.patterns, { ...context, repository: patternRepository }, result);\n }\n const include = rule.include;\n if (!include) {\n continue;\n }\n const reference = parseInclude(include);\n switch (reference.kind) {\n case 0 /* Base */:\n collectExternalReferencesInTopLevelRule({ ...context, selfGrammar: context.baseGrammar }, result);\n break;\n case 1 /* Self */:\n collectExternalReferencesInTopLevelRule(context, result);\n break;\n case 2 /* RelativeReference */:\n collectExternalReferencesInTopLevelRepositoryRule(reference.ruleName, { ...context, repository: patternRepository }, result);\n break;\n case 3 /* TopLevelReference */:\n case 4 /* TopLevelRepositoryReference */:\n const selfGrammar = reference.scopeName === context.selfGrammar.scopeName ? context.selfGrammar : reference.scopeName === context.baseGrammar.scopeName ? context.baseGrammar : void 0;\n if (selfGrammar) {\n const newContext = { baseGrammar: context.baseGrammar, selfGrammar, repository: patternRepository };\n if (reference.kind === 4 /* TopLevelRepositoryReference */) {\n collectExternalReferencesInTopLevelRepositoryRule(reference.ruleName, newContext, result);\n } else {\n collectExternalReferencesInTopLevelRule(newContext, result);\n }\n } else {\n if (reference.kind === 4 /* TopLevelRepositoryReference */) {\n result.add(new TopLevelRepositoryRuleReference(reference.scopeName, reference.ruleName));\n } else {\n result.add(new TopLevelRuleReference(reference.scopeName));\n }\n }\n break;\n }\n }\n}\nvar BaseReference = class {\n constructor() {\n this.kind = 0 /* Base */;\n }\n};\nvar SelfReference = class {\n constructor() {\n this.kind = 1 /* Self */;\n }\n};\nvar RelativeReference = class {\n constructor(ruleName) {\n this.ruleName = ruleName;\n this.kind = 2 /* RelativeReference */;\n }\n};\nvar TopLevelReference = class {\n constructor(scopeName) {\n this.scopeName = scopeName;\n this.kind = 3 /* TopLevelReference */;\n }\n};\nvar TopLevelRepositoryReference = class {\n constructor(scopeName, ruleName) {\n this.scopeName = scopeName;\n this.ruleName = ruleName;\n this.kind = 4 /* TopLevelRepositoryReference */;\n }\n};\nfunction parseInclude(include) {\n if (include === \"$base\") {\n return new BaseReference();\n } else if (include === \"$self\") {\n return new SelfReference();\n }\n const indexOfSharp = include.indexOf(\"#\");\n if (indexOfSharp === -1) {\n return new TopLevelReference(include);\n } else if (indexOfSharp === 0) {\n return new RelativeReference(include.substring(1));\n } else {\n const scopeName = include.substring(0, indexOfSharp);\n const ruleName = include.substring(indexOfSharp + 1);\n return new TopLevelRepositoryReference(scopeName, ruleName);\n }\n}\n\n// src/rule.ts\nvar HAS_BACK_REFERENCES = /\\\\(\\d+)/;\nvar BACK_REFERENCING_END = /\\\\(\\d+)/g;\nvar ruleIdSymbol = Symbol(\"RuleId\");\nvar endRuleId = -1;\nvar whileRuleId = -2;\nfunction ruleIdFromNumber(id) {\n return id;\n}\nfunction ruleIdToNumber(id) {\n return id;\n}\nvar Rule = class {\n constructor($location, id, name, contentName) {\n this.$location = $location;\n this.id = id;\n this._name = name || null;\n this._nameIsCapturing = RegexSource.hasCaptures(this._name);\n this._contentName = contentName || null;\n this._contentNameIsCapturing = RegexSource.hasCaptures(this._contentName);\n }\n get debugName() {\n const location = this.$location ? `${basename(this.$location.filename)}:${this.$location.line}` : \"unknown\";\n return `${this.constructor.name}#${this.id} @ ${location}`;\n }\n getName(lineText, captureIndices) {\n if (!this._nameIsCapturing || this._name === null || lineText === null || captureIndices === null) {\n return this._name;\n }\n return RegexSource.replaceCaptures(this._name, lineText, captureIndices);\n }\n getContentName(lineText, captureIndices) {\n if (!this._contentNameIsCapturing || this._contentName === null) {\n return this._contentName;\n }\n return RegexSource.replaceCaptures(this._contentName, lineText, captureIndices);\n }\n};\nvar CaptureRule = class extends Rule {\n constructor($location, id, name, contentName, retokenizeCapturedWithRuleId) {\n super($location, id, name, contentName);\n this.retokenizeCapturedWithRuleId = retokenizeCapturedWithRuleId;\n }\n dispose() {\n }\n collectPatterns(grammar, out) {\n throw new Error(\"Not supported!\");\n }\n compile(grammar, endRegexSource) {\n throw new Error(\"Not supported!\");\n }\n compileAG(grammar, endRegexSource, allowA, allowG) {\n throw new Error(\"Not supported!\");\n }\n};\nvar MatchRule = class extends Rule {\n constructor($location, id, name, match, captures) {\n super($location, id, name, null);\n this._match = new RegExpSource(match, this.id);\n this.captures = captures;\n this._cachedCompiledPatterns = null;\n }\n dispose() {\n if (this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns.dispose();\n this._cachedCompiledPatterns = null;\n }\n }\n get debugMatchRegExp() {\n return `${this._match.source}`;\n }\n collectPatterns(grammar, out) {\n out.push(this._match);\n }\n compile(grammar, endRegexSource) {\n return this._getCachedCompiledPatterns(grammar).compile(grammar);\n }\n compileAG(grammar, endRegexSource, allowA, allowG) {\n return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);\n }\n _getCachedCompiledPatterns(grammar) {\n if (!this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns = new RegExpSourceList();\n this.collectPatterns(grammar, this._cachedCompiledPatterns);\n }\n return this._cachedCompiledPatterns;\n }\n};\nvar IncludeOnlyRule = class extends Rule {\n constructor($location, id, name, contentName, patterns) {\n super($location, id, name, contentName);\n this.patterns = patterns.patterns;\n this.hasMissingPatterns = patterns.hasMissingPatterns;\n this._cachedCompiledPatterns = null;\n }\n dispose() {\n if (this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns.dispose();\n this._cachedCompiledPatterns = null;\n }\n }\n collectPatterns(grammar, out) {\n for (const pattern of this.patterns) {\n const rule = grammar.getRule(pattern);\n rule.collectPatterns(grammar, out);\n }\n }\n compile(grammar, endRegexSource) {\n return this._getCachedCompiledPatterns(grammar).compile(grammar);\n }\n compileAG(grammar, endRegexSource, allowA, allowG) {\n return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);\n }\n _getCachedCompiledPatterns(grammar) {\n if (!this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns = new RegExpSourceList();\n this.collectPatterns(grammar, this._cachedCompiledPatterns);\n }\n return this._cachedCompiledPatterns;\n }\n};\nvar BeginEndRule = class extends Rule {\n constructor($location, id, name, contentName, begin, beginCaptures, end, endCaptures, applyEndPatternLast, patterns) {\n super($location, id, name, contentName);\n this._begin = new RegExpSource(begin, this.id);\n this.beginCaptures = beginCaptures;\n this._end = new RegExpSource(end ? end : \"\\uFFFF\", -1);\n this.endHasBackReferences = this._end.hasBackReferences;\n this.endCaptures = endCaptures;\n this.applyEndPatternLast = applyEndPatternLast || false;\n this.patterns = patterns.patterns;\n this.hasMissingPatterns = patterns.hasMissingPatterns;\n this._cachedCompiledPatterns = null;\n }\n dispose() {\n if (this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns.dispose();\n this._cachedCompiledPatterns = null;\n }\n }\n get debugBeginRegExp() {\n return `${this._begin.source}`;\n }\n get debugEndRegExp() {\n return `${this._end.source}`;\n }\n getEndWithResolvedBackReferences(lineText, captureIndices) {\n return this._end.resolveBackReferences(lineText, captureIndices);\n }\n collectPatterns(grammar, out) {\n out.push(this._begin);\n }\n compile(grammar, endRegexSource) {\n return this._getCachedCompiledPatterns(grammar, endRegexSource).compile(grammar);\n }\n compileAG(grammar, endRegexSource, allowA, allowG) {\n return this._getCachedCompiledPatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);\n }\n _getCachedCompiledPatterns(grammar, endRegexSource) {\n if (!this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns = new RegExpSourceList();\n for (const pattern of this.patterns) {\n const rule = grammar.getRule(pattern);\n rule.collectPatterns(grammar, this._cachedCompiledPatterns);\n }\n if (this.applyEndPatternLast) {\n this._cachedCompiledPatterns.push(this._end.hasBackReferences ? this._end.clone() : this._end);\n } else {\n this._cachedCompiledPatterns.unshift(this._end.hasBackReferences ? this._end.clone() : this._end);\n }\n }\n if (this._end.hasBackReferences) {\n if (this.applyEndPatternLast) {\n this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length() - 1, endRegexSource);\n } else {\n this._cachedCompiledPatterns.setSource(0, endRegexSource);\n }\n }\n return this._cachedCompiledPatterns;\n }\n};\nvar BeginWhileRule = class extends Rule {\n constructor($location, id, name, contentName, begin, beginCaptures, _while, whileCaptures, patterns) {\n super($location, id, name, contentName);\n this._begin = new RegExpSource(begin, this.id);\n this.beginCaptures = beginCaptures;\n this.whileCaptures = whileCaptures;\n this._while = new RegExpSource(_while, whileRuleId);\n this.whileHasBackReferences = this._while.hasBackReferences;\n this.patterns = patterns.patterns;\n this.hasMissingPatterns = patterns.hasMissingPatterns;\n this._cachedCompiledPatterns = null;\n this._cachedCompiledWhilePatterns = null;\n }\n dispose() {\n if (this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns.dispose();\n this._cachedCompiledPatterns = null;\n }\n if (this._cachedCompiledWhilePatterns) {\n this._cachedCompiledWhilePatterns.dispose();\n this._cachedCompiledWhilePatterns = null;\n }\n }\n get debugBeginRegExp() {\n return `${this._begin.source}`;\n }\n get debugWhileRegExp() {\n return `${this._while.source}`;\n }\n getWhileWithResolvedBackReferences(lineText, captureIndices) {\n return this._while.resolveBackReferences(lineText, captureIndices);\n }\n collectPatterns(grammar, out) {\n out.push(this._begin);\n }\n compile(grammar, endRegexSource) {\n return this._getCachedCompiledPatterns(grammar).compile(grammar);\n }\n compileAG(grammar, endRegexSource, allowA, allowG) {\n return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG);\n }\n _getCachedCompiledPatterns(grammar) {\n if (!this._cachedCompiledPatterns) {\n this._cachedCompiledPatterns = new RegExpSourceList();\n for (const pattern of this.patterns) {\n const rule = grammar.getRule(pattern);\n rule.collectPatterns(grammar, this._cachedCompiledPatterns);\n }\n }\n return this._cachedCompiledPatterns;\n }\n compileWhile(grammar, endRegexSource) {\n return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compile(grammar);\n }\n compileWhileAG(grammar, endRegexSource, allowA, allowG) {\n return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG);\n }\n _getCachedCompiledWhilePatterns(grammar, endRegexSource) {\n if (!this._cachedCompiledWhilePatterns) {\n this._cachedCompiledWhilePatterns = new RegExpSourceList();\n this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences ? this._while.clone() : this._while);\n }\n if (this._while.hasBackReferences) {\n this._cachedCompiledWhilePatterns.setSource(0, endRegexSource ? endRegexSource : \"\\uFFFF\");\n }\n return this._cachedCompiledWhilePatterns;\n }\n};\nvar RuleFactory = class _RuleFactory {\n static createCaptureRule(helper, $location, name, contentName, retokenizeCapturedWithRuleId) {\n return helper.registerRule((id) => {\n return new CaptureRule($location, id, name, contentName, retokenizeCapturedWithRuleId);\n });\n }\n static getCompiledRuleId(desc, helper, repository) {\n if (!desc.id) {\n helper.registerRule((id) => {\n desc.id = id;\n if (desc.match) {\n return new MatchRule(\n desc.$vscodeTextmateLocation,\n desc.id,\n desc.name,\n desc.match,\n _RuleFactory._compileCaptures(desc.captures, helper, repository)\n );\n }\n if (typeof desc.begin === \"undefined\") {\n if (desc.repository) {\n repository = mergeObjects({}, repository, desc.repository);\n }\n let patterns = desc.patterns;\n if (typeof patterns === \"undefined\" && desc.include) {\n patterns = [{ include: desc.include }];\n }\n return new IncludeOnlyRule(\n desc.$vscodeTextmateLocation,\n desc.id,\n desc.name,\n desc.contentName,\n _RuleFactory._compilePatterns(patterns, helper, repository)\n );\n }\n if (desc.while) {\n return new BeginWhileRule(\n desc.$vscodeTextmateLocation,\n desc.id,\n desc.name,\n desc.contentName,\n desc.begin,\n _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository),\n desc.while,\n _RuleFactory._compileCaptures(desc.whileCaptures || desc.captures, helper, repository),\n _RuleFactory._compilePatterns(desc.patterns, helper, repository)\n );\n }\n return new BeginEndRule(\n desc.$vscodeTextmateLocation,\n desc.id,\n desc.name,\n desc.contentName,\n desc.begin,\n _RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository),\n desc.end,\n _RuleFactory._compileCaptures(desc.endCaptures || desc.captures, helper, repository),\n desc.applyEndPatternLast,\n _RuleFactory._compilePatterns(desc.patterns, helper, repository)\n );\n });\n }\n return desc.id;\n }\n static _compileCaptures(captures, helper, repository) {\n let r = [];\n if (captures) {\n let maximumCaptureId = 0;\n for (const captureId in captures) {\n if (captureId === \"$vscodeTextmateLocation\") {\n continue;\n }\n const numericCaptureId = parseInt(captureId, 10);\n if (numericCaptureId > maximumCaptureId) {\n maximumCaptureId = numericCaptureId;\n }\n }\n for (let i = 0; i <= maximumCaptureId; i++) {\n r[i] = null;\n }\n for (const captureId in captures) {\n if (captureId === \"$vscodeTextmateLocation\") {\n continue;\n }\n const numericCaptureId = parseInt(captureId, 10);\n let retokenizeCapturedWithRuleId = 0;\n if (captures[captureId].patterns) {\n retokenizeCapturedWithRuleId = _RuleFactory.getCompiledRuleId(captures[captureId], helper, repository);\n }\n r[numericCaptureId] = _RuleFactory.createCaptureRule(helper, captures[captureId].$vscodeTextmateLocation, captures[captureId].name, captures[captureId].contentName, retokenizeCapturedWithRuleId);\n }\n }\n return r;\n }\n static _compilePatterns(patterns, helper, repository) {\n let r = [];\n if (patterns) {\n for (let i = 0, len = patterns.length; i < len; i++) {\n const pattern = patterns[i];\n let ruleId = -1;\n if (pattern.include) {\n const reference = parseInclude(pattern.include);\n switch (reference.kind) {\n case 0 /* Base */:\n case 1 /* Self */:\n ruleId = _RuleFactory.getCompiledRuleId(repository[pattern.include], helper, repository);\n break;\n case 2 /* RelativeReference */:\n let localIncludedRule = repository[reference.ruleName];\n if (localIncludedRule) {\n ruleId = _RuleFactory.getCompiledRuleId(localIncludedRule, helper, repository);\n } else {\n }\n break;\n case 3 /* TopLevelReference */:\n case 4 /* TopLevelRepositoryReference */:\n const externalGrammarName = reference.scopeName;\n const externalGrammarInclude = reference.kind === 4 /* TopLevelRepositoryReference */ ? reference.ruleName : null;\n const externalGrammar = helper.getExternalGrammar(externalGrammarName, repository);\n if (externalGrammar) {\n if (externalGrammarInclude) {\n let externalIncludedRule = externalGrammar.repository[externalGrammarInclude];\n if (externalIncludedRule) {\n ruleId = _RuleFactory.getCompiledRuleId(externalIncludedRule, helper, externalGrammar.repository);\n } else {\n }\n } else {\n ruleId = _RuleFactory.getCompiledRuleId(externalGrammar.repository.$self, helper, externalGrammar.repository);\n }\n } else {\n }\n break;\n }\n } else {\n ruleId = _RuleFactory.getCompiledRuleId(pattern, helper, repository);\n }\n if (ruleId !== -1) {\n const rule = helper.getRule(ruleId);\n let skipRule = false;\n if (rule instanceof IncludeOnlyRule || rule instanceof BeginEndRule || rule instanceof BeginWhileRule) {\n if (rule.hasMissingPatterns && rule.patterns.length === 0) {\n skipRule = true;\n }\n }\n if (skipRule) {\n continue;\n }\n r.push(ruleId);\n }\n }\n }\n return {\n patterns: r,\n hasMissingPatterns: (patterns ? patterns.length : 0) !== r.length\n };\n }\n};\nvar RegExpSource = class _RegExpSource {\n constructor(regExpSource, ruleId) {\n if (regExpSource) {\n const len = regExpSource.length;\n let lastPushedPos = 0;\n let output = [];\n let hasAnchor = false;\n for (let pos = 0; pos < len; pos++) {\n const ch = regExpSource.charAt(pos);\n if (ch === \"\\\\\") {\n if (pos + 1 < len) {\n const nextCh = regExpSource.charAt(pos + 1);\n if (nextCh === \"z\") {\n output.push(regExpSource.substring(lastPushedPos, pos));\n output.push(\"$(?!\\\\n)(?<!\\\\n)\");\n lastPushedPos = pos + 2;\n } else if (nextCh === \"A\" || nextCh === \"G\") {\n hasAnchor = true;\n }\n pos++;\n }\n }\n }\n this.hasAnchor = hasAnchor;\n if (lastPushedPos === 0) {\n this.source = regExpSource;\n } else {\n output.push(regExpSource.substring(lastPushedPos, len));\n this.source = output.join(\"\");\n }\n } else {\n this.hasAnchor = false;\n this.source = regExpSource;\n }\n if (this.hasAnchor) {\n this._anchorCache = this._buildAnchorCache();\n } else {\n this._anchorCache = null;\n }\n this.ruleId = ruleId;\n this.hasBackReferences = HAS_BACK_REFERENCES.test(this.source);\n }\n clone() {\n return new _RegExpSource(this.source, this.ruleId);\n }\n setSource(newSource) {\n if (this.source === newSource) {\n return;\n }\n this.source = newSource;\n if (this.hasAnchor) {\n this._anchorCache = this._buildAnchorCache();\n }\n }\n resolveBackReferences(lineText, captureIndices) {\n let capturedValues = captureIndices.map((capture) => {\n return lineText.substring(capture.start, capture.end);\n });\n BACK_REFERENCING_END.lastIndex = 0;\n return this.source.replace(BACK_REFERENCING_END, (match, g1) => {\n return escapeRegExpCharacters(capturedValues[parseInt(g1, 10)] || \"\");\n });\n }\n _buildAnchorCache() {\n let A0_G0_result = [];\n let A0_G1_result = [];\n let A1_G0_result = [];\n let A1_G1_result = [];\n let pos, len, ch, nextCh;\n for (pos = 0, len = this.source.length; pos < len; pos++) {\n ch = this.source.charAt(pos);\n A0_G0_result[pos] = ch;\n A0_G1_result[pos] = ch;\n A1_G0_result[pos] = ch;\n A1_G1_result[pos] = ch;\n if (ch === \"\\\\\") {\n if (pos + 1 < len) {\n nextCh = this.source.charAt(pos + 1);\n if (nextCh === \"A\") {\n A0_G0_result[pos + 1] = \"\\uFFFF\";\n A0_G1_result[pos + 1] = \"\\uFFFF\";\n A1_G0_result[pos + 1] = \"A\";\n A1_G1_result[pos + 1] = \"A\";\n } else if (nextCh === \"G\") {\n A0_G0_result[pos + 1] = \"\\uFFFF\";\n A0_G1_result[pos + 1] = \"G\";\n A1_G0_result[pos + 1] = \"\\uFFFF\";\n A1_G1_result[pos + 1] = \"G\";\n } else {\n A0_G0_result[pos + 1] = nextCh;\n A0_G1_result[pos + 1] = nextCh;\n A1_G0_result[pos + 1] = nextCh;\n A1_G1_result[pos + 1] = nextCh;\n }\n pos++;\n }\n }\n }\n return {\n A0_G0: A0_G0_result.join(\"\"),\n A0_G1: A0_G1_result.join(\"\"),\n A1_G0: A1_G0_result.join(\"\"),\n A1_G1: A1_G1_result.join(\"\")\n };\n }\n resolveAnchors(allowA, allowG) {\n if (!this.hasAnchor || !this._anchorCache) {\n return this.source;\n }\n if (allowA) {\n if (allowG) {\n return this._anchorCache.A1_G1;\n } else {\n return this._anchorCache.A1_G0;\n }\n } else {\n if (allowG) {\n return this._anchorCache.A0_G1;\n } else {\n return this._anchorCache.A0_G0;\n }\n }\n }\n};\nvar RegExpSourceList = class {\n constructor() {\n this._items = [];\n this._hasAnchors = false;\n this._cached = null;\n this._anchorCache = {\n A0_G0: null,\n A0_G1: null,\n A1_G0: null,\n A1_G1: null\n };\n }\n dispose() {\n this._disposeCaches();\n }\n _disposeCaches() {\n if (this._cached) {\n this._cached.dispose();\n this._cached = null;\n }\n if (this._anchorCache.A0_G0) {\n this._anchorCache.A0_G0.dispose();\n this._anchorCache.A0_G0 = null;\n }\n if (this._anchorCache.A0_G1) {\n this._anchorCache.A0_G1.dispose();\n this._anchorCache.A0_G1 = null;\n }\n if (this._anchorCache.A1_G0) {\n this._anchorCache.A1_G0.dispose();\n this._anchorCache.A1_G0 = null;\n }\n if (this._anchorCache.A1_G1) {\n this._anchorCache.A1_G1.dispose();\n this._anchorCache.A1_G1 = null;\n }\n }\n push(item) {\n this._items.push(item);\n this._hasAnchors = this._hasAnchors || item.hasAnchor;\n }\n unshift(item) {\n this._items.unshift(item);\n this._hasAnchors = this._hasAnchors || item.hasAnchor;\n }\n length() {\n return this._items.length;\n }\n setSource(index, newSource) {\n if (this._items[index].source !== newSource) {\n this._disposeCaches();\n this._items[index].setSource(newSource);\n }\n }\n compile(onigLib) {\n if (!this._cached) {\n let regExps = this._items.map((e) => e.source);\n this._cached = new CompiledRule(onigLib, regExps, this._items.map((e) => e.ruleId));\n }\n return this._cached;\n }\n compileAG(onigLib, allowA, allowG) {\n if (!this._hasAnchors) {\n return this.compile(onigLib);\n } else {\n if (allowA) {\n if (allowG) {\n if (!this._anchorCache.A1_G1) {\n this._anchorCache.A1_G1 = this._resolveAnchors(onigLib, allowA, allowG);\n }\n return this._anchorCache.A1_G1;\n } else {\n if (!this._anchorCache.A1_G0) {\n this._anchorCache.A1_G0 = this._resolveAnchors(onigLib, allowA, allowG);\n }\n return this._anchorCache.A1_G0;\n }\n } else {\n if (allowG) {\n if (!this._anchorCache.A0_G1) {\n this._anchorCache.A0_G1 = this._resolveAnchors(onigLib, allowA, allowG);\n }\n return this._anchorCache.A0_G1;\n } else {\n if (!this._anchorCache.A0_G0) {\n this._anchorCache.A0_G0 = this._resolveAnchors(onigLib, allowA, allowG);\n }\n return this._anchorCache.A0_G0;\n }\n }\n }\n }\n _resolveAnchors(onigLib, allowA, allowG) {\n let regExps = this._items.map((e) => e.resolveAnchors(allowA, allowG));\n return new CompiledRule(onigLib, regExps, this._items.map((e) => e.ruleId));\n }\n};\nvar CompiledRule = class {\n constructor(onigLib, regExps, rules) {\n this.regExps = regExps;\n this.rules = rules;\n this.scanner = onigLib.createOnigScanner(regExps);\n }\n dispose() {\n if (typeof this.scanner.dispose === \"function\") {\n this.scanner.dispose();\n }\n }\n toString() {\n const r = [];\n for (let i = 0, len = this.rules.length; i < len; i++) {\n r.push(\" - \" + this.rules[i] + \": \" + this.regExps[i]);\n }\n return r.join(\"\\n\");\n }\n findNextMatchSync(string, startPosition, options) {\n const result = this.scanner.findNextMatchSync(string, startPosition, options);\n if (!result) {\n return null;\n }\n return {\n ruleId: this.rules[result.index],\n captureIndices: result.captureIndices\n };\n }\n};\n\n// src/grammar/basicScopesAttributeProvider.ts\nvar BasicScopeAttributes = class {\n constructor(languageId, tokenType) {\n this.languageId = languageId;\n this.tokenType = tokenType;\n }\n};\nvar _BasicScopeAttributesProvider = class _BasicScopeAttributesProvider {\n constructor(initialLanguageId, embeddedLanguages) {\n this._getBasicScopeAttributes = new CachedFn((scopeName) => {\n const languageId = this._scopeToLanguage(scopeName);\n const standardTokenType = this._toStandardTokenType(scopeName);\n return new BasicScopeAttributes(languageId, standardTokenType);\n });\n this._defaultAttributes = new BasicScopeAttributes(initialLanguageId, 8 /* NotSet */);\n this._embeddedLanguagesMatcher = new ScopeMatcher(Object.entries(embeddedLanguages || {}));\n }\n getDefaultAttributes() {\n return this._defaultAttributes;\n }\n getBasicScopeAttributes(scopeName) {\n if (scopeName === null) {\n return _BasicScopeAttributesProvider._NULL_SCOPE_METADATA;\n }\n return this._getBasicScopeAttributes.get(scopeName);\n }\n /**\n * Given a produced TM scope, return the language that token describes or null if unknown.\n * e.g. source.html => html, source.css.embedded.html => css, punctuation.definition.tag.html => null\n */\n _scopeToLanguage(scope) {\n return this._embeddedLanguagesMatcher.match(scope) || 0;\n }\n _toStandardTokenType(scopeName) {\n const m = scopeName.match(_BasicScopeAttributesProvider.STANDARD_TOKEN_TYPE_REGEXP);\n if (!m) {\n return 8 /* NotSet */;\n }\n switch (m[1]) {\n case \"comment\":\n return 1 /* Comment */;\n case \"string\":\n return 2 /* String */;\n case \"regex\":\n return 3 /* RegEx */;\n case \"meta.embedded\":\n return 0 /* Other */;\n }\n throw new Error(\"Unexpected match for standard token type!\");\n }\n};\n_BasicScopeAttributesProvider._NULL_SCOPE_METADATA = new BasicScopeAttributes(0, 0);\n_BasicScopeAttributesProvider.STANDARD_TOKEN_TYPE_REGEXP = /\\b(comment|string|regex|meta\\.embedded)\\b/;\nvar BasicScopeAttributesProvider = _BasicScopeAttributesProvider;\nvar ScopeMatcher = class {\n constructor(values) {\n if (values.length === 0) {\n this.values = null;\n this.scopesRegExp = null;\n } else {\n this.values = new Map(values);\n const escapedScopes = values.map(\n ([scopeName, value]) => escapeRegExpCharacters(scopeName)\n );\n escapedScopes.sort();\n escapedScopes.reverse();\n this.scopesRegExp = new RegExp(\n `^((${escapedScopes.join(\")|(\")}))($|\\\\.)`,\n \"\"\n );\n }\n }\n match(scope) {\n if (!this.scopesRegExp) {\n return void 0;\n }\n const m = scope.match(this.scopesRegExp);\n if (!m) {\n return void 0;\n }\n return this.values.get(m[1]);\n }\n};\n\n// src/debug.ts\nvar DebugFlags = {\n InDebugMode: typeof process !== \"undefined\" && !!process.env[\"VSCODE_TEXTMATE_DEBUG\"]\n};\nvar UseOnigurumaFindOptions = false;\n\n// src/grammar/tokenizeString.ts\nvar TokenizeStringResult = class {\n constructor(stack, stoppedEarly) {\n this.stack = stack;\n this.stoppedEarly = stoppedEarly;\n }\n};\nfunction _tokenizeString(grammar, lineText, isFirstLine, linePos, stack, lineTokens, checkWhileConditions, timeLimit) {\n const lineLength = lineText.content.length;\n let STOP = false;\n let anchorPosition = -1;\n if (checkWhileConditions) {\n const whileCheckResult = _checkWhileConditions(\n grammar,\n lineText,\n isFirstLine,\n linePos,\n stack,\n lineTokens\n );\n stack = whileCheckResult.stack;\n linePos = whileCheckResult.linePos;\n isFirstLine = whileCheckResult.isFirstLine;\n anchorPosition = whileCheckResult.anchorPosition;\n }\n const startTime = Date.now();\n while (!STOP) {\n if (timeLimit !== 0) {\n const elapsedTime = Date.now() - startTime;\n if (elapsedTime > timeLimit) {\n return new TokenizeStringResult(stack, true);\n }\n }\n scanNext();\n }\n return new TokenizeStringResult(stack, false);\n function scanNext() {\n if (false) {\n console.log(\"\");\n console.log(\n `@@scanNext ${linePos}: |${lineText.content.substr(linePos).replace(/\\n$/, \"\\\\n\")}|`\n );\n }\n const r = matchRuleOrInjections(\n grammar,\n lineText,\n isFirstLine,\n linePos,\n stack,\n anchorPosition\n );\n if (!r) {\n lineTokens.produce(stack, lineLength);\n STOP = true;\n return;\n }\n const captureIndices = r.captureIndices;\n const matchedRuleId = r.matchedRuleId;\n const hasAdvanced = captureIndices && captureIndices.length > 0 ? captureIndices[0].end > linePos : false;\n if (matchedRuleId === endRuleId) {\n const poppedRule = stack.getRule(grammar);\n if (false) {\n console.log(\n \" popping \" + poppedRule.debugName + \" - \" + poppedRule.debugEndRegExp\n );\n }\n lineTokens.produce(stack, captureIndices[0].start);\n stack = stack.withContentNameScopesList(stack.nameScopesList);\n handleCaptures(\n grammar,\n lineText,\n isFirstLine,\n stack,\n lineTokens,\n poppedRule.endCaptures,\n captureIndices\n );\n lineTokens.produce(stack, captureIndices[0].end);\n const popped = stack;\n stack = stack.parent;\n anchorPosition = popped.getAnchorPos();\n if (!hasAdvanced && popped.getEnterPos() === linePos) {\n if (false) {\n console.error(\n \"[1] - Grammar is in an endless loop - Grammar pushed & popped a rule without advancing\"\n );\n }\n stack = popped;\n lineTokens.produce(stack, lineLength);\n STOP = true;\n return;\n }\n } else {\n const _rule = grammar.getRule(matchedRuleId);\n lineTokens.produce(stack, captureIndices[0].start);\n const beforePush = stack;\n const scopeName = _rule.getName(lineText.content, captureIndices);\n const nameScopesList = stack.contentNameScopesList.pushAttributed(\n scopeName,\n grammar\n );\n stack = stack.push(\n matchedRuleId,\n linePos,\n anchorPosition,\n captureIndices[0].end === lineLength,\n null,\n nameScopesList,\n nameScopesList\n );\n if (_rule instanceof BeginEndRule) {\n const pushedRule = _rule;\n if (false) {\n console.log(\n \" pushing \" + pushedRule.debugName + \" - \" + pushedRule.debugBeginRegExp\n );\n }\n handleCaptures(\n grammar,\n lineText,\n isFirstLine,\n stack,\n lineTokens,\n pushedRule.beginCaptures,\n captureIndices\n );\n lineTokens.produce(stack, captureIndices[0].end);\n anchorPosition = captureIndices[0].end;\n const contentName = pushedRule.getContentName(\n lineText.content,\n captureIndices\n );\n const contentNameScopesList = nameScopesList.pushAttributed(\n contentName,\n grammar\n );\n stack = stack.withContentNameScopesList(contentNameScopesList);\n if (pushedRule.endHasBackReferences) {\n stack = stack.withEndRule(\n pushedRule.getEndWithResolvedBackReferences(\n lineText.content,\n captureIndices\n )\n );\n }\n if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {\n if (false) {\n console.error(\n \"[2] - Grammar is in an endless loop - Grammar pushed the same rule without advancing\"\n );\n }\n stack = stack.pop();\n lineTokens.produce(stack, lineLength);\n STOP = true;\n return;\n }\n } else if (_rule instanceof BeginWhileRule) {\n const pushedRule = _rule;\n if (false) {\n console.log(\" pushing \" + pushedRule.debugName);\n }\n handleCaptures(\n grammar,\n lineText,\n isFirstLine,\n stack,\n lineTokens,\n pushedRule.beginCaptures,\n captureIndices\n );\n lineTokens.produce(stack, captureIndices[0].end);\n anchorPosition = captureIndices[0].end;\n const contentName = pushedRule.getContentName(\n lineText.content,\n captureIndices\n );\n const contentNameScopesList = nameScopesList.pushAttributed(\n contentName,\n grammar\n );\n stack = stack.withContentNameScopesList(contentNameScopesList);\n if (pushedRule.whileHasBackReferences) {\n stack = stack.withEndRule(\n pushedRule.getWhileWithResolvedBackReferences(\n lineText.content,\n captureIndices\n )\n );\n }\n if (!hasAdvanced && beforePush.hasSameRuleAs(stack)) {\n if (false) {\n console.error(\n \"[3] - Grammar is in an endless loop - Grammar pushed the same rule without advancing\"\n );\n }\n stack = stack.pop();\n lineTokens.produce(stack, lineLength);\n STOP = true;\n return;\n }\n } else {\n const matchingRule = _rule;\n if (false) {\n console.log(\n \" matched \" + matchingRule.debugName + \" - \" + matchingRule.debugMatchRegExp\n );\n }\n handleCaptures(\n grammar,\n lineText,\n isFirstLine,\n stack,\n lineTokens,\n matchingRule.captures,\n captureIndices\n );\n lineTokens.produce(stack, captureIndices[0].end);\n stack = stack.pop();\n if (!hasAdvanced) {\n if (false) {\n console.error(\n \"[4] - Grammar is in an endless loop - Grammar is not advancing, nor is it pushing/popping\"\n );\n }\n stack = stack.safePop();\n lineTokens.produce(stack, lineLength);\n STOP = true;\n return;\n }\n }\n }\n if (captureIndices[0].end > linePos) {\n linePos = captureIndices[0].end;\n isFirstLine = false;\n }\n }\n}\nfunction _checkWhileConditions(grammar, lineText, isFirstLine, linePos, stack, lineTokens) {\n let anchorPosition = stack.beginRuleCapturedEOL ? 0 : -1;\n const whileRules = [];\n for (let node = stack; node; node = node.pop()) {\n const nodeRule = node.getRule(grammar);\n if (nodeRule instanceof BeginWhileRule) {\n whileRules.push({\n rule: nodeRule,\n stack: node\n });\n }\n }\n for (let whileRule = whileRules.pop(); whileRule; whileRule = whileRules.pop()) {\n const { ruleScanner, findOptions } = prepareRuleWhileSearch(whileRule.rule, grammar, whileRule.stack.endRule, isFirstLine, linePos === anchorPosition);\n const r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);\n if (false) {\n console.log(\" scanning for while rule\");\n console.log(ruleScanner.toString());\n }\n if (r) {\n const matchedRuleId = r.ruleId;\n if (matchedRuleId !== whileRuleId) {\n stack = whileRule.stack.pop();\n break;\n }\n if (r.captureIndices && r.captureIndices.length) {\n lineTokens.produce(whileRule.stack, r.captureIndices[0].start);\n handleCaptures(grammar, lineText, isFirstLine, whileRule.stack, lineTokens, whileRule.rule.whileCaptures, r.captureIndices);\n lineTokens.produce(whileRule.stack, r.captureIndices[0].end);\n anchorPosition = r.captureIndices[0].end;\n if (r.captureIndices[0].end > linePos) {\n linePos = r.captureIndices[0].end;\n isFirstLine = false;\n }\n }\n } else {\n if (false) {\n console.log(\" popping \" + whileRule.rule.debugName + \" - \" + whileRule.rule.debugWhileRegExp);\n }\n stack = whileRule.stack.pop();\n break;\n }\n }\n return { stack, linePos, anchorPosition, isFirstLine };\n}\nfunction matchRuleOrInjections(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {\n const matchResult = matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition);\n const injections = grammar.getInjections();\n if (injections.length === 0) {\n return matchResult;\n }\n const injectionResult = matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition);\n if (!injectionResult) {\n return matchResult;\n }\n if (!matchResult) {\n return injectionResult;\n }\n const matchResultScore = matchResult.captureIndices[0].start;\n const injectionResultScore = injectionResult.captureIndices[0].start;\n if (injectionResultScore < matchResultScore || injectionResult.priorityMatch && injectionResultScore === matchResultScore) {\n return injectionResult;\n }\n return matchResult;\n}\nfunction matchRule(grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {\n const rule = stack.getRule(grammar);\n const { ruleScanner, findOptions } = prepareRuleSearch(rule, grammar, stack.endRule, isFirstLine, linePos === anchorPosition);\n const r = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);\n if (r) {\n return {\n captureIndices: r.captureIndices,\n matchedRuleId: r.ruleId\n };\n }\n return null;\n}\nfunction matchInjections(injections, grammar, lineText, isFirstLine, linePos, stack, anchorPosition) {\n let bestMatchRating = Number.MAX_VALUE;\n let bestMatchCaptureIndices = null;\n let bestMatchRuleId;\n let bestMatchResultPriority = 0;\n const scopes = stack.contentNameScopesList.getScopeNames();\n for (let i = 0, len = injections.length; i < len; i++) {\n const injection = injections[i];\n if (!injection.matcher(scopes)) {\n continue;\n }\n const rule = grammar.getRule(injection.ruleId);\n const { ruleScanner, findOptions } = prepareRuleSearch(rule, grammar, null, isFirstLine, linePos === anchorPosition);\n const matchResult = ruleScanner.findNextMatchSync(lineText, linePos, findOptions);\n if (!matchResult) {\n continue;\n }\n if (false) {\n console.log(` matched injection: ${injection.debugSelector}`);\n console.log(ruleScanner.toString());\n }\n const matchRating = matchResult.captureIndices[0].start;\n if (matchRating >= bestMatchRating) {\n continue;\n }\n bestMatchRating = matchRating;\n bestMatchCaptureIndices = matchResult.captureIndices;\n bestMatchRuleId = matchResult.ruleId;\n bestMatchResultPriority = injection.priority;\n if (bestMatchRating === linePos) {\n break;\n }\n }\n if (bestMatchCaptureIndices) {\n return {\n priorityMatch: bestMatchResultPriority === -1,\n captureIndices: bestMatchCaptureIndices,\n matchedRuleId: bestMatchRuleId\n };\n }\n return null;\n}\nfunction prepareRuleSearch(rule, grammar, endRegexSource, allowA, allowG) {\n if (UseOnigurumaFindOptions) {\n const ruleScanner2 = rule.compile(grammar, endRegexSource);\n const findOptions = getFindOptions(allowA, allowG);\n return { ruleScanner: ruleScanner2, findOptions };\n }\n const ruleScanner = rule.compileAG(grammar, endRegexSource, allowA, allowG);\n return { ruleScanner, findOptions: 0 /* None */ };\n}\nfunction prepareRuleWhileSearch(rule, grammar, endRegexSource, allowA, allowG) {\n if (UseOnigurumaFindOptions) {\n const ruleScanner2 = rule.compileWhile(grammar, endRegexSource);\n const findOptions = getFindOptions(allowA, allowG);\n return { ruleScanner: ruleScanner2, findOptions };\n }\n const ruleScanner = rule.compileWhileAG(grammar, endRegexSource, allowA, allowG);\n return { ruleScanner, findOptions: 0 /* None */ };\n}\nfunction getFindOptions(allowA, allowG) {\n let options = 0 /* None */;\n if (!allowA) {\n options |= 1 /* NotBeginString */;\n }\n if (!allowG) {\n options |= 4 /* NotBeginPosition */;\n }\n return options;\n}\nfunction handleCaptures(grammar, lineText, isFirstLine, stack, lineTokens, captures, captureIndices) {\n if (captures.length === 0) {\n return;\n }\n const lineTextContent = lineText.content;\n const len = Math.min(captures.length, captureIndices.length);\n const localStack = [];\n const maxEnd = captureIndices[0].end;\n for (let i = 0; i < len; i++) {\n const captureRule = captures[i];\n if (captureRule === null) {\n continue;\n }\n const captureIndex = captureIndices[i];\n if (captureIndex.length === 0) {\n continue;\n }\n if (captureIndex.start > maxEnd) {\n break;\n }\n while (localStack.length > 0 && localStack[localStack.length - 1].endPos <= captureIndex.start) {\n lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);\n localStack.pop();\n }\n if (localStack.length > 0) {\n lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, captureIndex.start);\n } else {\n lineTokens.produce(stack, captureIndex.start);\n }\n if (captureRule.retokenizeCapturedWithRuleId) {\n const scopeName = captureRule.getName(lineTextContent, captureIndices);\n const nameScopesList = stack.contentNameScopesList.pushAttributed(scopeName, grammar);\n const contentName = captureRule.getContentName(lineTextContent, captureIndices);\n const contentNameScopesList = nameScopesList.pushAttributed(contentName, grammar);\n const stackClone = stack.push(captureRule.retokenizeCapturedWithRuleId, captureIndex.start, -1, false, null, nameScopesList, contentNameScopesList);\n const onigSubStr = grammar.createOnigString(lineTextContent.substring(0, captureIndex.end));\n _tokenizeString(\n grammar,\n onigSubStr,\n isFirstLine && captureIndex.start === 0,\n captureIndex.start,\n stackClone,\n lineTokens,\n false,\n /* no time limit */\n 0\n );\n disposeOnigString(onigSubStr);\n continue;\n }\n const captureRuleScopeName = captureRule.getName(lineTextContent, captureIndices);\n if (captureRuleScopeName !== null) {\n const base = localStack.length > 0 ? localStack[localStack.length - 1].scopes : stack.contentNameScopesList;\n const captureRuleScopesList = base.pushAttributed(captureRuleScopeName, grammar);\n localStack.push(new LocalStackElement(captureRuleScopesList, captureIndex.end));\n }\n }\n while (localStack.length > 0) {\n lineTokens.produceFromScopes(localStack[localStack.length - 1].scopes, localStack[localStack.length - 1].endPos);\n localStack.pop();\n }\n}\nvar LocalStackElement = class {\n constructor(scopes, endPos) {\n this.scopes = scopes;\n this.endPos = endPos;\n }\n};\n\n// src/grammar/grammar.ts\nfunction createGrammar(scopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, onigLib) {\n return new Grammar(\n scopeName,\n grammar,\n initialLanguage,\n embeddedLanguages,\n tokenTypes,\n balancedBracketSelectors,\n grammarRepository,\n onigLib\n );\n}\nfunction collectInjections(result, selector, rule, ruleFactoryHelper, grammar) {\n const matchers = createMatchers(selector, nameMatcher);\n const ruleId = RuleFactory.getCompiledRuleId(rule, ruleFactoryHelper, grammar.repository);\n for (const matcher of matchers) {\n result.push({\n debugSelector: selector,\n matcher: matcher.matcher,\n ruleId,\n grammar,\n priority: matcher.priority\n });\n }\n}\nfunction nameMatcher(identifers, scopes) {\n if (scopes.length < identifers.length) {\n return false;\n }\n let lastIndex = 0;\n return identifers.every((identifier) => {\n for (let i = lastIndex; i < scopes.length; i++) {\n if (scopesAreMatching(scopes[i], identifier)) {\n lastIndex = i + 1;\n return true;\n }\n }\n return false;\n });\n}\nfunction scopesAreMatching(thisScopeName, scopeName) {\n if (!thisScopeName) {\n return false;\n }\n if (thisScopeName === scopeName) {\n return true;\n }\n const len = scopeName.length;\n return thisScopeName.length > len && thisScopeName.substr(0, len) === scopeName && thisScopeName[len] === \".\";\n}\nvar Grammar = class {\n constructor(_rootScopeName, grammar, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors, grammarRepository, _onigLib) {\n this._rootScopeName = _rootScopeName;\n this.balancedBracketSelectors = balancedBracketSelectors;\n this._onigLib = _onigLib;\n this._basicScopeAttributesProvider = new BasicScopeAttributesProvider(\n initialLanguage,\n embeddedLanguages\n );\n this._rootId = -1;\n this._lastRuleId = 0;\n this._ruleId2desc = [null];\n this._includedGrammars = {};\n this._grammarRepository = grammarRepository;\n this._grammar = initGrammar(grammar, null);\n this._injections = null;\n this._tokenTypeMatchers = [];\n if (tokenTypes) {\n for (const selector of Object.keys(tokenTypes)) {\n const matchers = createMatchers(selector, nameMatcher);\n for (const matcher of matchers) {\n this._tokenTypeMatchers.push({\n matcher: matcher.matcher,\n type: tokenTypes[selector]\n });\n }\n }\n }\n }\n get themeProvider() {\n return this._grammarRepository;\n }\n dispose() {\n for (const rule of this._ruleId2desc) {\n if (rule) {\n rule.dispose();\n }\n }\n }\n createOnigScanner(sources) {\n return this._onigLib.createOnigScanner(sources);\n }\n createOnigString(sources) {\n return this._onigLib.createOnigString(sources);\n }\n getMetadataForScope(scope) {\n return this._basicScopeAttributesProvider.getBasicScopeAttributes(scope);\n }\n _collectInjections() {\n const grammarRepository = {\n lookup: (scopeName2) => {\n if (scopeName2 === this._rootScopeName) {\n return this._grammar;\n }\n return this.getExternalGrammar(scopeName2);\n },\n injections: (scopeName2) => {\n return this._grammarRepository.injections(scopeName2);\n }\n };\n const result = [];\n const scopeName = this._rootScopeName;\n const grammar = grammarRepository.lookup(scopeName);\n if (grammar) {\n const rawInjections = grammar.injections;\n if (rawInjections) {\n for (let expression in rawInjections) {\n collectInjections(\n result,\n expression,\n rawInjections[expression],\n this,\n grammar\n );\n }\n }\n const injectionScopeNames = this._grammarRepository.injections(scopeName);\n if (injectionScopeNames) {\n injectionScopeNames.forEach((injectionScopeName) => {\n const injectionGrammar = this.getExternalGrammar(injectionScopeName);\n if (injectionGrammar) {\n const selector = injectionGrammar.injectionSelector;\n if (selector) {\n collectInjections(\n result,\n selector,\n injectionGrammar,\n this,\n injectionGrammar\n );\n }\n }\n });\n }\n }\n result.sort((i1, i2) => i1.priority - i2.priority);\n return result;\n }\n getInjections() {\n if (this._injections === null) {\n this._injections = this._collectInjections();\n }\n return this._injections;\n }\n registerRule(factory) {\n const id = ++this._lastRuleId;\n const result = factory(ruleIdFromNumber(id));\n this._ruleId2desc[id] = result;\n return result;\n }\n getRule(ruleId) {\n return this._ruleId2desc[ruleIdToNumber(ruleId)];\n }\n getExternalGrammar(scopeName, repository) {\n if (this._includedGrammars[scopeName]) {\n return this._includedGrammars[scopeName];\n } else if (this._grammarRepository) {\n const rawIncludedGrammar = this._grammarRepository.lookup(scopeName);\n if (rawIncludedGrammar) {\n this._includedGrammars[scopeName] = initGrammar(\n rawIncludedGrammar,\n repository && repository.$base\n );\n return this._includedGrammars[scopeName];\n }\n }\n return void 0;\n }\n tokenizeLine(lineText, prevState, timeLimit = 0) {\n const r = this._tokenize(lineText, prevState, false, timeLimit);\n return {\n tokens: r.lineTokens.getResult(r.ruleStack, r.lineLength),\n ruleStack: r.ruleStack,\n stoppedEarly: r.stoppedEarly\n };\n }\n tokenizeLine2(lineText, prevState, timeLimit = 0) {\n const r = this._tokenize(lineText, prevState, true, timeLimit);\n return {\n tokens: r.lineTokens.getBinaryResult(r.ruleStack, r.lineLength),\n ruleStack: r.ruleStack,\n stoppedEarly: r.stoppedEarly\n };\n }\n _tokenize(lineText, prevState, emitBinaryTokens, timeLimit) {\n if (this._rootId === -1) {\n this._rootId = RuleFactory.getCompiledRuleId(\n this._grammar.repository.$self,\n this,\n this._grammar.repository\n );\n this.getInjections();\n }\n let isFirstLine;\n if (!prevState || prevState === StateStackImpl.NULL) {\n isFirstLine = true;\n const rawDefaultMetadata = this._basicScopeAttributesProvider.getDefaultAttributes();\n const defaultStyle = this.themeProvider.getDefaults();\n const defaultMetadata = EncodedTokenMetadata.set(\n 0,\n rawDefaultMetadata.languageId,\n rawDefaultMetadata.tokenType,\n null,\n defaultStyle.fontStyle,\n defaultStyle.foregroundId,\n defaultStyle.backgroundId\n );\n const rootScopeName = this.getRule(this._rootId).getName(\n null,\n null\n );\n let scopeList;\n if (rootScopeName) {\n scopeList = AttributedScopeStack.createRootAndLookUpScopeName(\n rootScopeName,\n defaultMetadata,\n this\n );\n } else {\n scopeList = AttributedScopeStack.createRoot(\n \"unknown\",\n defaultMetadata\n );\n }\n prevState = new StateStackImpl(\n null,\n this._rootId,\n -1,\n -1,\n false,\n null,\n scopeList,\n scopeList\n );\n } else {\n isFirstLine = false;\n prevState.reset();\n }\n lineText = lineText + \"\\n\";\n const onigLineText = this.createOnigString(lineText);\n const lineLength = onigLineText.content.length;\n const lineTokens = new LineTokens(\n emitBinaryTokens,\n lineText,\n this._tokenTypeMatchers,\n this.balancedBracketSelectors\n );\n const r = _tokenizeString(\n this,\n onigLineText,\n isFirstLine,\n 0,\n prevState,\n lineTokens,\n true,\n timeLimit\n );\n disposeOnigString(onigLineText);\n return {\n lineLength,\n lineTokens,\n ruleStack: r.stack,\n stoppedEarly: r.stoppedEarly\n };\n }\n};\nfunction initGrammar(grammar, base) {\n grammar = clone(grammar);\n grammar.repository = grammar.repository || {};\n grammar.repository.$self = {\n $vscodeTextmateLocation: grammar.$vscodeTextmateLocation,\n patterns: grammar.patterns,\n name: grammar.scopeName\n };\n grammar.repository.$base = base || grammar.repository.$self;\n return grammar;\n}\nvar AttributedScopeStack = class _AttributedScopeStack {\n /**\n * Invariant:\n * ```\n * if (parent && !scopePath.extends(parent.scopePath)) {\n * \tthrow new Error();\n * }\n * ```\n */\n constructor(parent, scopePath, tokenAttributes) {\n this.parent = parent;\n this.scopePath = scopePath;\n this.tokenAttributes = tokenAttributes;\n }\n static fromExtension(namesScopeList, contentNameScopesList) {\n let current = namesScopeList;\n let scopeNames = namesScopeList?.scopePath ?? null;\n for (const frame of contentNameScopesList) {\n scopeNames = ScopeStack.push(scopeNames, frame.scopeNames);\n current = new _AttributedScopeStack(current, scopeNames, frame.encodedTokenAttributes);\n }\n return current;\n }\n static createRoot(scopeName, tokenAttributes) {\n return new _AttributedScopeStack(null, new ScopeStack(null, scopeName), tokenAttributes);\n }\n static createRootAndLookUpScopeName(scopeName, tokenAttributes, grammar) {\n const rawRootMetadata = grammar.getMetadataForScope(scopeName);\n const scopePath = new ScopeStack(null, scopeName);\n const rootStyle = grammar.themeProvider.themeMatch(scopePath);\n const resolvedTokenAttributes = _AttributedScopeStack.mergeAttributes(\n tokenAttributes,\n rawRootMetadata,\n rootStyle\n );\n return new _AttributedScopeStack(null, scopePath, resolvedTokenAttributes);\n }\n get scopeName() {\n return this.scopePath.scopeName;\n }\n toString() {\n return this.getScopeNames().join(\" \");\n }\n equals(other) {\n return _AttributedScopeStack.equals(this, other);\n }\n static equals(a, b) {\n do {\n if (a === b) {\n return true;\n }\n if (!a && !b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n if (a.scopeName !== b.scopeName || a.tokenAttributes !== b.tokenAttributes) {\n return false;\n }\n a = a.parent;\n b = b.parent;\n } while (true);\n }\n static mergeAttributes(existingTokenAttributes, basicScopeAttributes, styleAttributes) {\n let fontStyle = -1 /* NotSet */;\n let foreground = 0;\n let background = 0;\n if (styleAttributes !== null) {\n fontStyle = styleAttributes.fontStyle;\n foreground = styleAttributes.foregroundId;\n background = styleAttributes.backgroundId;\n }\n return EncodedTokenMetadata.set(\n existingTokenAttributes,\n basicScopeAttributes.languageId,\n basicScopeAttributes.tokenType,\n null,\n fontStyle,\n foreground,\n background\n );\n }\n pushAttributed(scopePath, grammar) {\n if (scopePath === null) {\n return this;\n }\n if (scopePath.indexOf(\" \") === -1) {\n return _AttributedScopeStack._pushAttributed(this, scopePath, grammar);\n }\n const scopes = scopePath.split(/ /g);\n let result = this;\n for (const scope of scopes) {\n result = _AttributedScopeStack._pushAttributed(result, scope, grammar);\n }\n return result;\n }\n static _pushAttributed(target, scopeName, grammar) {\n const rawMetadata = grammar.getMetadataForScope(scopeName);\n const newPath = target.scopePath.push(scopeName);\n const scopeThemeMatchResult = grammar.themeProvider.themeMatch(newPath);\n const metadata = _AttributedScopeStack.mergeAttributes(\n target.tokenAttributes,\n rawMetadata,\n scopeThemeMatchResult\n );\n return new _AttributedScopeStack(target, newPath, metadata);\n }\n getScopeNames() {\n return this.scopePath.getSegments();\n }\n getExtensionIfDefined(base) {\n const result = [];\n let self = this;\n while (self && self !== base) {\n result.push({\n encodedTokenAttributes: self.tokenAttributes,\n scopeNames: self.scopePath.getExtensionIfDefined(self.parent?.scopePath ?? null)\n });\n self = self.parent;\n }\n return self === base ? result.reverse() : void 0;\n }\n};\nvar _StateStackImpl = class _StateStackImpl {\n /**\n * Invariant:\n * ```\n * if (contentNameScopesList !== nameScopesList && contentNameScopesList?.parent !== nameScopesList) {\n * \tthrow new Error();\n * }\n * if (this.parent && !nameScopesList.extends(this.parent.contentNameScopesList)) {\n * \tthrow new Error();\n * }\n * ```\n */\n constructor(parent, ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {\n this.parent = parent;\n this.ruleId = ruleId;\n this.beginRuleCapturedEOL = beginRuleCapturedEOL;\n this.endRule = endRule;\n this.nameScopesList = nameScopesList;\n this.contentNameScopesList = contentNameScopesList;\n this._stackElementBrand = void 0;\n this.depth = this.parent ? this.parent.depth + 1 : 1;\n this._enterPos = enterPos;\n this._anchorPos = anchorPos;\n }\n equals(other) {\n if (other === null) {\n return false;\n }\n return _StateStackImpl._equals(this, other);\n }\n static _equals(a, b) {\n if (a === b) {\n return true;\n }\n if (!this._structuralEquals(a, b)) {\n return false;\n }\n return AttributedScopeStack.equals(a.contentNameScopesList, b.contentNameScopesList);\n }\n /**\n * A structural equals check. Does not take into account `scopes`.\n */\n static _structuralEquals(a, b) {\n do {\n if (a === b) {\n return true;\n }\n if (!a && !b) {\n return true;\n }\n if (!a || !b) {\n return false;\n }\n if (a.depth !== b.depth || a.ruleId !== b.ruleId || a.endRule !== b.endRule) {\n return false;\n }\n a = a.parent;\n b = b.parent;\n } while (true);\n }\n clone() {\n return this;\n }\n static _reset(el) {\n while (el) {\n el._enterPos = -1;\n el._anchorPos = -1;\n el = el.parent;\n }\n }\n reset() {\n _StateStackImpl._reset(this);\n }\n pop() {\n return this.parent;\n }\n safePop() {\n if (this.parent) {\n return this.parent;\n }\n return this;\n }\n push(ruleId, enterPos, anchorPos, beginRuleCapturedEOL, endRule, nameScopesList, contentNameScopesList) {\n return new _StateStackImpl(\n this,\n ruleId,\n enterPos,\n anchorPos,\n beginRuleCapturedEOL,\n endRule,\n nameScopesList,\n contentNameScopesList\n );\n }\n getEnterPos() {\n return this._enterPos;\n }\n getAnchorPos() {\n return this._anchorPos;\n }\n getRule(grammar) {\n return grammar.getRule(this.ruleId);\n }\n toString() {\n const r = [];\n this._writeString(r, 0);\n return \"[\" + r.join(\",\") + \"]\";\n }\n _writeString(res, outIndex) {\n if (this.parent) {\n outIndex = this.parent._writeString(res, outIndex);\n }\n res[outIndex++] = `(${this.ruleId}, ${this.nameScopesList?.toString()}, ${this.contentNameScopesList?.toString()})`;\n return outIndex;\n }\n withContentNameScopesList(contentNameScopeStack) {\n if (this.contentNameScopesList === contentNameScopeStack) {\n return this;\n }\n return this.parent.push(\n this.ruleId,\n this._enterPos,\n this._anchorPos,\n this.beginRuleCapturedEOL,\n this.endRule,\n this.nameScopesList,\n contentNameScopeStack\n );\n }\n withEndRule(endRule) {\n if (this.endRule === endRule) {\n return this;\n }\n return new _StateStackImpl(\n this.parent,\n this.ruleId,\n this._enterPos,\n this._anchorPos,\n this.beginRuleCapturedEOL,\n endRule,\n this.nameScopesList,\n this.contentNameScopesList\n );\n }\n // Used to warn of endless loops\n hasSameRuleAs(other) {\n let el = this;\n while (el && el._enterPos === other._enterPos) {\n if (el.ruleId === other.ruleId) {\n return true;\n }\n el = el.parent;\n }\n return false;\n }\n toStateStackFrame() {\n return {\n ruleId: ruleIdToNumber(this.ruleId),\n beginRuleCapturedEOL: this.beginRuleCapturedEOL,\n endRule: this.endRule,\n nameScopesList: this.nameScopesList?.getExtensionIfDefined(this.parent?.nameScopesList ?? null) ?? [],\n contentNameScopesList: this.contentNameScopesList?.getExtensionIfDefined(this.nameScopesList) ?? []\n };\n }\n static pushFrame(self, frame) {\n const namesScopeList = AttributedScopeStack.fromExtension(self?.nameScopesList ?? null, frame.nameScopesList);\n return new _StateStackImpl(\n self,\n ruleIdFromNumber(frame.ruleId),\n frame.enterPos ?? -1,\n frame.anchorPos ?? -1,\n frame.beginRuleCapturedEOL,\n frame.endRule,\n namesScopeList,\n AttributedScopeStack.fromExtension(namesScopeList, frame.contentNameScopesList)\n );\n }\n};\n// TODO remove me\n_StateStackImpl.NULL = new _StateStackImpl(\n null,\n 0,\n 0,\n 0,\n false,\n null,\n null,\n null\n);\nvar StateStackImpl = _StateStackImpl;\nvar BalancedBracketSelectors = class {\n constructor(balancedBracketScopes, unbalancedBracketScopes) {\n this.allowAny = false;\n this.balancedBracketScopes = balancedBracketScopes.flatMap(\n (selector) => {\n if (selector === \"*\") {\n this.allowAny = true;\n return [];\n }\n return createMatchers(selector, nameMatcher).map((m) => m.matcher);\n }\n );\n this.unbalancedBracketScopes = unbalancedBracketScopes.flatMap(\n (selector) => createMatchers(selector, nameMatcher).map((m) => m.matcher)\n );\n }\n get matchesAlways() {\n return this.allowAny && this.unbalancedBracketScopes.length === 0;\n }\n get matchesNever() {\n return this.balancedBracketScopes.length === 0 && !this.allowAny;\n }\n match(scopes) {\n for (const excluder of this.unbalancedBracketScopes) {\n if (excluder(scopes)) {\n return false;\n }\n }\n for (const includer of this.balancedBracketScopes) {\n if (includer(scopes)) {\n return true;\n }\n }\n return this.allowAny;\n }\n};\nvar LineTokens = class {\n constructor(emitBinaryTokens, lineText, tokenTypeOverrides, balancedBracketSelectors) {\n this.balancedBracketSelectors = balancedBracketSelectors;\n this._emitBinaryTokens = emitBinaryTokens;\n this._tokenTypeOverrides = tokenTypeOverrides;\n if (false) {\n this._lineText = lineText;\n } else {\n this._lineText = null;\n }\n this._tokens = [];\n this._binaryTokens = [];\n this._lastTokenEndIndex = 0;\n }\n produce(stack, endIndex) {\n this.produceFromScopes(stack.contentNameScopesList, endIndex);\n }\n produceFromScopes(scopesList, endIndex) {\n if (this._lastTokenEndIndex >= endIndex) {\n return;\n }\n if (this._emitBinaryTokens) {\n let metadata = scopesList?.tokenAttributes ?? 0;\n let containsBalancedBrackets = false;\n if (this.balancedBracketSelectors?.matchesAlways) {\n containsBalancedBrackets = true;\n }\n if (this._tokenTypeOverrides.length > 0 || this.balancedBracketSelectors && !this.balancedBracketSelectors.matchesAlways && !this.balancedBracketSelectors.matchesNever) {\n const scopes2 = scopesList?.getScopeNames() ?? [];\n for (const tokenType of this._tokenTypeOverrides) {\n if (tokenType.matcher(scopes2)) {\n metadata = EncodedTokenMetadata.set(\n metadata,\n 0,\n toOptionalTokenType(tokenType.type),\n null,\n -1 /* NotSet */,\n 0,\n 0\n );\n }\n }\n if (this.balancedBracketSelectors) {\n containsBalancedBrackets = this.balancedBracketSelectors.match(scopes2);\n }\n }\n if (containsBalancedBrackets) {\n metadata = EncodedTokenMetadata.set(\n metadata,\n 0,\n 8 /* NotSet */,\n containsBalancedBrackets,\n -1 /* NotSet */,\n 0,\n 0\n );\n }\n if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 1] === metadata) {\n this._lastTokenEndIndex = endIndex;\n return;\n }\n this._binaryTokens.push(this._lastTokenEndIndex);\n this._binaryTokens.push(metadata);\n this._lastTokenEndIndex = endIndex;\n return;\n }\n const scopes = scopesList?.getScopeNames() ?? [];\n this._tokens.push({\n startIndex: this._lastTokenEndIndex,\n endIndex,\n // value: lineText.substring(lastTokenEndIndex, endIndex),\n scopes\n });\n this._lastTokenEndIndex = endIndex;\n }\n getResult(stack, lineLength) {\n if (this._tokens.length > 0 && this._tokens[this._tokens.length - 1].startIndex === lineLength - 1) {\n this._tokens.pop();\n }\n if (this._tokens.length === 0) {\n this._lastTokenEndIndex = -1;\n this.produce(stack, lineLength);\n this._tokens[this._tokens.length - 1].startIndex = 0;\n }\n return this._tokens;\n }\n getBinaryResult(stack, lineLength) {\n if (this._binaryTokens.length > 0 && this._binaryTokens[this._binaryTokens.length - 2] === lineLength - 1) {\n this._binaryTokens.pop();\n this._binaryTokens.pop();\n }\n if (this._binaryTokens.length === 0) {\n this._lastTokenEndIndex = -1;\n this.produce(stack, lineLength);\n this._binaryTokens[this._binaryTokens.length - 2] = 0;\n }\n const result = new Uint32Array(this._binaryTokens.length);\n for (let i = 0, len = this._binaryTokens.length; i < len; i++) {\n result[i] = this._binaryTokens[i];\n }\n return result;\n }\n};\n\n// src/registry.ts\nvar SyncRegistry = class {\n constructor(theme, _onigLib) {\n this._onigLib = _onigLib;\n this._grammars = /* @__PURE__ */ new Map();\n this._rawGrammars = /* @__PURE__ */ new Map();\n this._injectionGrammars = /* @__PURE__ */ new Map();\n this._theme = theme;\n }\n dispose() {\n for (const grammar of this._grammars.values()) {\n grammar.dispose();\n }\n }\n setTheme(theme) {\n this._theme = theme;\n }\n getColorMap() {\n return this._theme.getColorMap();\n }\n /**\n * Add `grammar` to registry and return a list of referenced scope names\n */\n addGrammar(grammar, injectionScopeNames) {\n this._rawGrammars.set(grammar.scopeName, grammar);\n if (injectionScopeNames) {\n this._injectionGrammars.set(grammar.scopeName, injectionScopeNames);\n }\n }\n /**\n * Lookup a raw grammar.\n */\n lookup(scopeName) {\n return this._rawGrammars.get(scopeName);\n }\n /**\n * Returns the injections for the given grammar\n */\n injections(targetScope) {\n return this._injectionGrammars.get(targetScope);\n }\n /**\n * Get the default theme settings\n */\n getDefaults() {\n return this._theme.getDefaults();\n }\n /**\n * Match a scope in the theme.\n */\n themeMatch(scopePath) {\n return this._theme.match(scopePath);\n }\n /**\n * Lookup a grammar.\n */\n grammarForScopeName(scopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {\n if (!this._grammars.has(scopeName)) {\n let rawGrammar = this._rawGrammars.get(scopeName);\n if (!rawGrammar) {\n return null;\n }\n this._grammars.set(scopeName, createGrammar(\n scopeName,\n rawGrammar,\n initialLanguage,\n embeddedLanguages,\n tokenTypes,\n balancedBracketSelectors,\n this,\n this._onigLib\n ));\n }\n return this._grammars.get(scopeName);\n }\n};\n\n// src/index.ts\nvar Registry = class {\n constructor(options) {\n this._options = options;\n this._syncRegistry = new SyncRegistry(\n Theme.createFromRawTheme(options.theme, options.colorMap),\n options.onigLib\n );\n this._ensureGrammarCache = /* @__PURE__ */ new Map();\n }\n dispose() {\n this._syncRegistry.dispose();\n }\n /**\n * Change the theme. Once called, no previous `ruleStack` should be used anymore.\n */\n setTheme(theme, colorMap) {\n this._syncRegistry.setTheme(Theme.createFromRawTheme(theme, colorMap));\n }\n /**\n * Returns a lookup array for color ids.\n */\n getColorMap() {\n return this._syncRegistry.getColorMap();\n }\n /**\n * Load the grammar for `scopeName` and all referenced included grammars asynchronously.\n * Please do not use language id 0.\n */\n loadGrammarWithEmbeddedLanguages(initialScopeName, initialLanguage, embeddedLanguages) {\n return this.loadGrammarWithConfiguration(initialScopeName, initialLanguage, { embeddedLanguages });\n }\n /**\n * Load the grammar for `scopeName` and all referenced included grammars asynchronously.\n * Please do not use language id 0.\n */\n loadGrammarWithConfiguration(initialScopeName, initialLanguage, configuration) {\n return this._loadGrammar(\n initialScopeName,\n initialLanguage,\n configuration.embeddedLanguages,\n configuration.tokenTypes,\n new BalancedBracketSelectors(\n configuration.balancedBracketSelectors || [],\n configuration.unbalancedBracketSelectors || []\n )\n );\n }\n /**\n * Load the grammar for `scopeName` and all referenced included grammars asynchronously.\n */\n loadGrammar(initialScopeName) {\n return this._loadGrammar(initialScopeName, 0, null, null, null);\n }\n _loadGrammar(initialScopeName, initialLanguage, embeddedLanguages, tokenTypes, balancedBracketSelectors) {\n const dependencyProcessor = new ScopeDependencyProcessor(this._syncRegistry, initialScopeName);\n while (dependencyProcessor.Q.length > 0) {\n dependencyProcessor.Q.map((request) => this._loadSingleGrammar(request.scopeName));\n dependencyProcessor.processQueue();\n }\n return this._grammarForScopeName(\n initialScopeName,\n initialLanguage,\n embeddedLanguages,\n tokenTypes,\n balancedBracketSelectors\n );\n }\n _loadSingleGrammar(scopeName) {\n if (!this._ensureGrammarCache.has(scopeName)) {\n this._doLoadSingleGrammar(scopeName);\n this._ensureGrammarCache.set(scopeName, true);\n }\n }\n _doLoadSingleGrammar(scopeName) {\n const grammar = this._options.loadGrammar(scopeName);\n if (grammar) {\n const injections = typeof this._options.getInjections === \"function\" ? this._options.getInjections(scopeName) : void 0;\n this._syncRegistry.addGrammar(grammar, injections);\n }\n }\n /**\n * Adds a rawGrammar.\n */\n addGrammar(rawGrammar, injections = [], initialLanguage = 0, embeddedLanguages = null) {\n this._syncRegistry.addGrammar(rawGrammar, injections);\n return this._grammarForScopeName(rawGrammar.scopeName, initialLanguage, embeddedLanguages);\n }\n /**\n * Get the grammar for `scopeName`. The grammar must first be created via `loadGrammar` or `addGrammar`.\n */\n _grammarForScopeName(scopeName, initialLanguage = 0, embeddedLanguages = null, tokenTypes = null, balancedBracketSelectors = null) {\n return this._syncRegistry.grammarForScopeName(\n scopeName,\n initialLanguage,\n embeddedLanguages,\n tokenTypes,\n balancedBracketSelectors\n );\n }\n};\nvar INITIAL = StateStackImpl.NULL;\nexport {\n EncodedTokenMetadata,\n FindOption,\n FontStyle,\n INITIAL,\n Registry,\n Theme,\n disposeOnigString\n};\n","import {\n boolean,\n overloadedBoolean,\n booleanish,\n number,\n spaceSeparated,\n commaSeparated\n} from './util/types.js'\nimport {create} from './util/create.js'\nimport {caseInsensitiveTransform} from './util/case-insensitive-transform.js'\n\nexport const html = create({\n space: 'html',\n attributes: {\n acceptcharset: 'accept-charset',\n classname: 'class',\n htmlfor: 'for',\n httpequiv: 'http-equiv'\n },\n transform: caseInsensitiveTransform,\n mustUseProperty: ['checked', 'multiple', 'muted', 'selected'],\n properties: {\n // Standard Properties.\n abbr: null,\n accept: commaSeparated,\n acceptCharset: spaceSeparated,\n accessKey: spaceSeparated,\n action: null,\n allow: null,\n allowFullScreen: boolean,\n allowPaymentRequest: boolean,\n allowUserMedia: boolean,\n alt: null,\n as: null,\n async: boolean,\n autoCapitalize: null,\n autoComplete: spaceSeparated,\n autoFocus: boolean,\n autoPlay: boolean,\n blocking: spaceSeparated,\n capture: null,\n charSet: null,\n checked: boolean,\n cite: null,\n className: spaceSeparated,\n cols: number,\n colSpan: null,\n content: null,\n contentEditable: booleanish,\n controls: boolean,\n controlsList: spaceSeparated,\n coords: number | commaSeparated,\n crossOrigin: null,\n data: null,\n dateTime: null,\n decoding: null,\n default: boolean,\n defer: boolean,\n dir: null,\n dirName: null,\n disabled: boolean,\n download: overloadedBoolean,\n draggable: booleanish,\n encType: null,\n enterKeyHint: null,\n fetchPriority: null,\n form: null,\n formAction: null,\n formEncType: null,\n formMethod: null,\n formNoValidate: boolean,\n formTarget: null,\n headers: spaceSeparated,\n height: number,\n hidden: boolean,\n high: number,\n href: null,\n hrefLang: null,\n htmlFor: spaceSeparated,\n httpEquiv: spaceSeparated,\n id: null,\n imageSizes: null,\n imageSrcSet: null,\n inert: boolean,\n inputMode: null,\n integrity: null,\n is: null,\n isMap: boolean,\n itemId: null,\n itemProp: spaceSeparated,\n itemRef: spaceSeparated,\n itemScope: boolean,\n itemType: spaceSeparated,\n kind: null,\n label: null,\n lang: null,\n language: null,\n list: null,\n loading: null,\n loop: boolean,\n low: number,\n manifest: null,\n max: null,\n maxLength: number,\n media: null,\n method: null,\n min: null,\n minLength: number,\n multiple: boolean,\n muted: boolean,\n name: null,\n nonce: null,\n noModule: boolean,\n noValidate: boolean,\n onAbort: null,\n onAfterPrint: null,\n onAuxClick: null,\n onBeforeMatch: null,\n onBeforePrint: null,\n onBeforeToggle: null,\n onBeforeUnload: null,\n onBlur: null,\n onCancel: null,\n onCanPlay: null,\n onCanPlayThrough: null,\n onChange: null,\n onClick: null,\n onClose: null,\n onContextLost: null,\n onContextMenu: null,\n onContextRestored: null,\n onCopy: null,\n onCueChange: null,\n onCut: null,\n onDblClick: null,\n onDrag: null,\n onDragEnd: null,\n onDragEnter: null,\n onDragExit: null,\n onDragLeave: null,\n onDragOver: null,\n onDragStart: null,\n onDrop: null,\n onDurationChange: null,\n onEmptied: null,\n onEnded: null,\n onError: null,\n onFocus: null,\n onFormData: null,\n onHashChange: null,\n onInput: null,\n onInvalid: null,\n onKeyDown: null,\n onKeyPress: null,\n onKeyUp: null,\n onLanguageChange: null,\n onLoad: null,\n onLoadedData: null,\n onLoadedMetadata: null,\n onLoadEnd: null,\n onLoadStart: null,\n onMessage: null,\n onMessageError: null,\n onMouseDown: null,\n onMouseEnter: null,\n onMouseLeave: null,\n onMouseMove: null,\n onMouseOut: null,\n onMouseOver: null,\n onMouseUp: null,\n onOffline: null,\n onOnline: null,\n onPageHide: null,\n onPageShow: null,\n onPaste: null,\n onPause: null,\n onPlay: null,\n onPlaying: null,\n onPopState: null,\n onProgress: null,\n onRateChange: null,\n onRejectionHandled: null,\n onReset: null,\n onResize: null,\n onScroll: null,\n onScrollEnd: null,\n onSecurityPolicyViolation: null,\n onSeeked: null,\n onSeeking: null,\n onSelect: null,\n onSlotChange: null,\n onStalled: null,\n onStorage: null,\n onSubmit: null,\n onSuspend: null,\n onTimeUpdate: null,\n onToggle: null,\n onUnhandledRejection: null,\n onUnload: null,\n onVolumeChange: null,\n onWaiting: null,\n onWheel: null,\n open: boolean,\n optimum: number,\n pattern: null,\n ping: spaceSeparated,\n placeholder: null,\n playsInline: boolean,\n popover: null,\n popoverTarget: null,\n popoverTargetAction: null,\n poster: null,\n preload: null,\n readOnly: boolean,\n referrerPolicy: null,\n rel: spaceSeparated,\n required: boolean,\n reversed: boolean,\n rows: number,\n rowSpan: number,\n sandbox: spaceSeparated,\n scope: null,\n scoped: boolean,\n seamless: boolean,\n selected: boolean,\n shadowRootClonable: boolean,\n shadowRootDelegatesFocus: boolean,\n shadowRootMode: null,\n shape: null,\n size: number,\n sizes: null,\n slot: null,\n span: number,\n spellCheck: booleanish,\n src: null,\n srcDoc: null,\n srcLang: null,\n srcSet: null,\n start: number,\n step: null,\n style: null,\n tabIndex: number,\n target: null,\n title: null,\n translate: null,\n type: null,\n typeMustMatch: boolean,\n useMap: null,\n value: booleanish,\n width: number,\n wrap: null,\n writingSuggestions: null,\n\n // Legacy.\n // See: https://html.spec.whatwg.org/#other-elements,-attributes-and-apis\n align: null, // Several. Use CSS `text-align` instead,\n aLink: null, // `<body>`. Use CSS `a:active {color}` instead\n archive: spaceSeparated, // `<object>`. List of URIs to archives\n axis: null, // `<td>` and `<th>`. Use `scope` on `<th>`\n background: null, // `<body>`. Use CSS `background-image` instead\n bgColor: null, // `<body>` and table elements. Use CSS `background-color` instead\n border: number, // `<table>`. Use CSS `border-width` instead,\n borderColor: null, // `<table>`. Use CSS `border-color` instead,\n bottomMargin: number, // `<body>`\n cellPadding: null, // `<table>`\n cellSpacing: null, // `<table>`\n char: null, // Several table elements. When `align=char`, sets the character to align on\n charOff: null, // Several table elements. When `char`, offsets the alignment\n classId: null, // `<object>`\n clear: null, // `<br>`. Use CSS `clear` instead\n code: null, // `<object>`\n codeBase: null, // `<object>`\n codeType: null, // `<object>`\n color: null, // `<font>` and `<hr>`. Use CSS instead\n compact: boolean, // Lists. Use CSS to reduce space between items instead\n declare: boolean, // `<object>`\n event: null, // `<script>`\n face: null, // `<font>`. Use CSS instead\n frame: null, // `<table>`\n frameBorder: null, // `<iframe>`. Use CSS `border` instead\n hSpace: number, // `<img>` and `<object>`\n leftMargin: number, // `<body>`\n link: null, // `<body>`. Use CSS `a:link {color: *}` instead\n longDesc: null, // `<frame>`, `<iframe>`, and `<img>`. Use an `<a>`\n lowSrc: null, // `<img>`. Use a `<picture>`\n marginHeight: number, // `<body>`\n marginWidth: number, // `<body>`\n noResize: boolean, // `<frame>`\n noHref: boolean, // `<area>`. Use no href instead of an explicit `nohref`\n noShade: boolean, // `<hr>`. Use background-color and height instead of borders\n noWrap: boolean, // `<td>` and `<th>`\n object: null, // `<applet>`\n profile: null, // `<head>`\n prompt: null, // `<isindex>`\n rev: null, // `<link>`\n rightMargin: number, // `<body>`\n rules: null, // `<table>`\n scheme: null, // `<meta>`\n scrolling: booleanish, // `<frame>`. Use overflow in the child context\n standby: null, // `<object>`\n summary: null, // `<table>`\n text: null, // `<body>`. Use CSS `color` instead\n topMargin: number, // `<body>`\n valueType: null, // `<param>`\n version: null, // `<html>`. Use a doctype.\n vAlign: null, // Several. Use CSS `vertical-align` instead\n vLink: null, // `<body>`. Use CSS `a:visited {color}` instead\n vSpace: number, // `<img>` and `<object>`\n\n // Non-standard Properties.\n allowTransparency: null,\n autoCorrect: null,\n autoSave: null,\n disablePictureInPicture: boolean,\n disableRemotePlayback: boolean,\n prefix: null,\n property: null,\n results: number,\n security: null,\n unselectable: null\n }\n})\n","/**\n * @import {Element, Parents, Properties} from 'hast'\n * @import {State} from '../index.js'\n */\n\nimport {ccount} from 'ccount'\nimport {stringify as commas} from 'comma-separated-tokens'\nimport {find, svg} from 'property-information'\nimport {stringify as spaces} from 'space-separated-tokens'\nimport {stringifyEntities} from 'stringify-entities'\nimport {closing} from '../omission/closing.js'\nimport {opening} from '../omission/opening.js'\n\n/**\n * Maps of subsets.\n *\n * Each value is a matrix of tuples.\n * The value at `0` causes parse errors, the value at `1` is valid.\n * Of both, the value at `0` is unsafe, and the value at `1` is safe.\n *\n * @type {Record<'double' | 'name' | 'single' | 'unquoted', Array<[Array<string>, Array<string>]>>}\n */\nconst constants = {\n // See: <https://html.spec.whatwg.org/#attribute-name-state>.\n name: [\n ['\\t\\n\\f\\r &/=>'.split(''), '\\t\\n\\f\\r \"&\\'/=>`'.split('')],\n ['\\0\\t\\n\\f\\r \"&\\'/<=>'.split(''), '\\0\\t\\n\\f\\r \"&\\'/<=>`'.split('')]\n ],\n // See: <https://html.spec.whatwg.org/#attribute-value-(unquoted)-state>.\n unquoted: [\n ['\\t\\n\\f\\r &>'.split(''), '\\0\\t\\n\\f\\r \"&\\'<=>`'.split('')],\n ['\\0\\t\\n\\f\\r \"&\\'<=>`'.split(''), '\\0\\t\\n\\f\\r \"&\\'<=>`'.split('')]\n ],\n // See: <https://html.spec.whatwg.org/#attribute-value-(single-quoted)-state>.\n single: [\n [\"&'\".split(''), '\"&\\'`'.split('')],\n [\"\\0&'\".split(''), '\\0\"&\\'`'.split('')]\n ],\n // See: <https://html.spec.whatwg.org/#attribute-value-(double-quoted)-state>.\n double: [\n ['\"&'.split(''), '\"&\\'`'.split('')],\n ['\\0\"&'.split(''), '\\0\"&\\'`'.split('')]\n ]\n}\n\n/**\n * Serialize an element node.\n *\n * @param {Element} node\n * Node to handle.\n * @param {number | undefined} index\n * Index of `node` in `parent.\n * @param {Parents | undefined} parent\n * Parent of `node`.\n * @param {State} state\n * Info passed around about the current state.\n * @returns {string}\n * Serialized node.\n */\nexport function element(node, index, parent, state) {\n const schema = state.schema\n const omit = schema.space === 'svg' ? false : state.settings.omitOptionalTags\n let selfClosing =\n schema.space === 'svg'\n ? state.settings.closeEmptyElements\n : state.settings.voids.includes(node.tagName.toLowerCase())\n /** @type {Array<string>} */\n const parts = []\n /** @type {string} */\n let last\n\n if (schema.space === 'html' && node.tagName === 'svg') {\n state.schema = svg\n }\n\n const attributes = serializeAttributes(state, node.properties)\n\n const content = state.all(\n schema.space === 'html' && node.tagName === 'template' ? node.content : node\n )\n\n state.schema = schema\n\n // If the node is categorised as void, but it has children, remove the\n // categorisation.\n // This enables for example `menuitem`s, which are void in W3C HTML but not\n // void in WHATWG HTML, to be stringified properly.\n // Note: `menuitem` has since been removed from the HTML spec, and so is no\n // longer void.\n if (content) selfClosing = false\n\n if (attributes || !omit || !opening(node, index, parent)) {\n parts.push('<', node.tagName, attributes ? ' ' + attributes : '')\n\n if (\n selfClosing &&\n (schema.space === 'svg' || state.settings.closeSelfClosing)\n ) {\n last = attributes.charAt(attributes.length - 1)\n if (\n !state.settings.tightSelfClosing ||\n last === '/' ||\n (last && last !== '\"' && last !== \"'\")\n ) {\n parts.push(' ')\n }\n\n parts.push('/')\n }\n\n parts.push('>')\n }\n\n parts.push(content)\n\n if (!selfClosing && (!omit || !closing(node, index, parent))) {\n parts.push('</' + node.tagName + '>')\n }\n\n return parts.join('')\n}\n\n/**\n * @param {State} state\n * @param {Properties | null | undefined} properties\n * @returns {string}\n */\nfunction serializeAttributes(state, properties) {\n /** @type {Array<string>} */\n const values = []\n let index = -1\n /** @type {string} */\n let key\n\n if (properties) {\n for (key in properties) {\n if (properties[key] !== null && properties[key] !== undefined) {\n const value = serializeAttribute(state, key, properties[key])\n if (value) values.push(value)\n }\n }\n }\n\n while (++index < values.length) {\n const last = state.settings.tightAttributes\n ? values[index].charAt(values[index].length - 1)\n : undefined\n\n // In tight mode, don’t add a space after quoted attributes.\n if (index !== values.length - 1 && last !== '\"' && last !== \"'\") {\n values[index] += ' '\n }\n }\n\n return values.join('')\n}\n\n/**\n * @param {State} state\n * @param {string} key\n * @param {Properties[keyof Properties]} value\n * @returns {string}\n */\nfunction serializeAttribute(state, key, value) {\n const info = find(state.schema, key)\n const x =\n state.settings.allowParseErrors && state.schema.space === 'html' ? 0 : 1\n const y = state.settings.allowDangerousCharacters ? 0 : 1\n let quote = state.quote\n /** @type {string | undefined} */\n let result\n\n if (info.overloadedBoolean && (value === info.attribute || value === '')) {\n value = true\n } else if (\n info.boolean ||\n (info.overloadedBoolean && typeof value !== 'string')\n ) {\n value = Boolean(value)\n }\n\n if (\n value === null ||\n value === undefined ||\n value === false ||\n (typeof value === 'number' && Number.isNaN(value))\n ) {\n return ''\n }\n\n const name = stringifyEntities(\n info.attribute,\n Object.assign({}, state.settings.characterReferences, {\n // Always encode without parse errors in non-HTML.\n subset: constants.name[x][y]\n })\n )\n\n // No value.\n // There is currently only one boolean property in SVG: `[download]` on\n // `<a>`.\n // This property does not seem to work in browsers (Firefox, Safari, Chrome),\n // so I can’t test if dropping the value works.\n // But I assume that it should:\n //\n // ```html\n // <!doctype html>\n // <svg viewBox=\"0 0 100 100\">\n // <a href=https://example.com download>\n // <circle cx=50 cy=40 r=35 />\n // </a>\n // </svg>\n // ```\n //\n // See: <https://github.com/wooorm/property-information/blob/main/lib/svg.js>\n if (value === true) return name\n\n // `spaces` doesn’t accept a second argument, but it’s given here just to\n // keep the code cleaner.\n value = Array.isArray(value)\n ? (info.commaSeparated ? commas : spaces)(value, {\n padLeft: !state.settings.tightCommaSeparatedLists\n })\n : String(value)\n\n if (state.settings.collapseEmptyAttributes && !value) return name\n\n // Check unquoted value.\n if (state.settings.preferUnquoted) {\n result = stringifyEntities(\n value,\n Object.assign({}, state.settings.characterReferences, {\n attribute: true,\n subset: constants.unquoted[x][y]\n })\n )\n }\n\n // If we don’t want unquoted, or if `value` contains character references when\n // unquoted…\n if (result !== value) {\n // If the alternative is less common than `quote`, switch.\n if (\n state.settings.quoteSmart &&\n ccount(value, quote) > ccount(value, state.alternative)\n ) {\n quote = state.alternative\n }\n\n result =\n quote +\n stringifyEntities(\n value,\n Object.assign({}, state.settings.characterReferences, {\n // Always encode without parse errors in non-HTML.\n subset: (quote === \"'\" ? constants.single : constants.double)[x][y],\n attribute: true\n })\n ) +\n quote\n }\n\n // Don’t add a `=` for unquoted empties.\n return name + (result ? '=' + result : result)\n}\n","import {Pattern, pattern} from './pattern.js';\nimport {Context, forEachUnescaped, replaceUnescaped} from 'regex-utilities';\n\nexport const RegexContext = {\n DEFAULT: 'DEFAULT',\n CHAR_CLASS: 'CHAR_CLASS',\n ENCLOSED_P: 'ENCLOSED_P',\n ENCLOSED_U: 'ENCLOSED_U',\n GROUP_NAME: 'GROUP_NAME',\n INTERVAL_QUANTIFIER: 'INTERVAL_QUANTIFIER',\n INVALID_INCOMPLETE_TOKEN: 'INVALID_INCOMPLETE_TOKEN',\n};\n\nexport const CharClassContext = {\n DEFAULT: 'DEFAULT',\n ENCLOSED_P: 'ENCLOSED_P',\n ENCLOSED_Q: 'ENCLOSED_Q',\n ENCLOSED_U: 'ENCLOSED_U',\n INVALID_INCOMPLETE_TOKEN: 'INVALID_INCOMPLETE_TOKEN',\n RANGE: 'RANGE',\n};\n\nexport const enclosedTokenRegexContexts = new Set([\n RegexContext.ENCLOSED_P,\n RegexContext.ENCLOSED_U,\n]);\n\nexport const enclosedTokenCharClassContexts = new Set([\n CharClassContext.ENCLOSED_P,\n CharClassContext.ENCLOSED_Q,\n CharClassContext.ENCLOSED_U,\n]);\n\nexport const patternModsSupported = (() => {\n try {\n new RegExp('(?i:)');\n } catch (e) {\n return false;\n }\n return true;\n})();\n\nexport const flagVSupported = (() => {\n try {\n new RegExp('', 'v');\n } catch (e) {\n return false;\n }\n return true;\n})();\n\n// This marker was chosen because it's impossible to match (so its extemely unlikely to be used in\n// a user-provided regex); it's not at risk of being optimized away, transformed, or flagged as an\n// error by a plugin; and it ends with an unquantifiable token\nexport const emulationGroupMarker = '$E$';\nexport const doublePunctuatorChars = '&!#$%*+,.:;<=>?@^`~';\nexport const namedCapturingDelim = String.raw`\\(\\?<(?![=!])(?<captureName>[^>]+)>`;\nexport const capturingDelim = String.raw`\\((?!\\?)(?!(?<=\\(\\?\\()DEFINE\\))|${namedCapturingDelim}`;\nexport const noncapturingDelim = String.raw`\\(\\?(?:[:=!>A-Za-z\\-]|<[=!]|\\(DEFINE\\))`;\n\n/**\n@param {string} expression\n@param {number} precedingCaptures\n@returns {string}\n*/\nexport function adjustNumberedBackrefs(expression, precedingCaptures) {\n return replaceUnescaped(\n expression,\n String.raw`\\\\(?<num>[1-9]\\d*)`,\n ({groups: {num}}) => `\\\\${+num + precedingCaptures}`,\n Context.DEFAULT\n );\n}\n\n// Properties of strings as of ES2024\nconst stringPropertyNames = [\n 'Basic_Emoji',\n 'Emoji_Keycap_Sequence',\n 'RGI_Emoji_Modifier_Sequence',\n 'RGI_Emoji_Flag_Sequence',\n 'RGI_Emoji_Tag_Sequence',\n 'RGI_Emoji_ZWJ_Sequence',\n 'RGI_Emoji',\n].join('|');\nconst charClassUnionToken = new RegExp(String.raw`\n\\\\(?: c[A-Za-z]\n | p\\{(?<pStrProp>${stringPropertyNames})\\}\n | [pP]\\{[^\\}]+\\}\n | (?<qStrProp>q)\n | u(?:[A-Fa-f\\d]{4}|\\{[A-Fa-f\\d]+\\})\n | x[A-Fa-f\\d]{2}\n | .\n)\n| --\n| &&\n| .\n`.replace(/\\s+/g, ''), 'gsu');\n\n// Assumes flag v and doesn't worry about syntax errors that are caught by it\nexport function containsCharClassUnion(charClassPattern) {\n // Return `true` if it contains:\n // - `\\p` (lowercase only) and the name is a property of strings (case sensitive).\n // - `\\q`.\n // - Two single-char-matching tokens in sequence.\n // - One single-char-matching token followed immediately by unescaped `[`.\n // - One single-char-matching token preceded immediately by unescaped `]`.\n // Else, `false`.\n // Ranges with `-` create a single token.\n // Subtraction and intersection with `--` and `&&` create a single token.\n // Supports any number of nested classes\n let hasFirst = false;\n let lastM;\n for (const {0: m, groups} of charClassPattern.matchAll(charClassUnionToken)) {\n if (groups.pStrProp || groups.qStrProp) {\n return true;\n }\n if (m === '[' && hasFirst) {\n return true;\n }\n if (['-', '--', '&&'].includes(m)) {\n hasFirst = false;\n } else if (m !== '[' && m !== ']') {\n if (hasFirst || lastM === ']') {\n return true;\n }\n hasFirst = true;\n }\n lastM = m;\n }\n return false;\n}\n\n/**\n@param {string} expression\n@returns {number}\n*/\nexport function countCaptures(expression) {\n let num = 0;\n forEachUnescaped(expression, capturingDelim, () => num++, Context.DEFAULT);\n return num;\n}\n\n/**\nEscape special characters for the given context, assuming flag v.\n@param {string} str String to escape\n@param {'DEFAULT' | 'CHAR_CLASS'} context `Context` option from lib `regex-utilities`\n@returns {string} Escaped string\n*/\nexport function escapeV(str, context) {\n if (context === Context.CHAR_CLASS) {\n // Escape all double punctuators (including ^, which is special on its own in the first\n // position) in case they're bordered by the same character in or outside of the escaped string\n return str.replace(new RegExp(String.raw`[()\\[\\]{}|\\\\/\\-${doublePunctuatorChars}]`, 'g'), '\\\\$&');\n }\n return str.replace(/[()\\[\\]{}|\\\\^$*+?.]/g, '\\\\$&');\n}\n\n// Look for characters that would change the meaning of subsequent tokens outside an interpolated value\nexport function getBreakoutChar(expression, regexContext, charClassContext) {\n const escapesRemoved = expression.replace(/\\\\./gsu, '');\n // Trailing unescaped `\\`; checking `.includes('\\\\')` would also work\n if (escapesRemoved.endsWith('\\\\')) {\n return '\\\\';\n }\n if (regexContext === RegexContext.DEFAULT) {\n // Unbalanced `[` or `]` are also errors but don't breakout; they're caught by the wrapper\n return getUnbalancedChar(escapesRemoved, '(', ')');\n } else if (\n regexContext === RegexContext.CHAR_CLASS &&\n !enclosedTokenCharClassContexts.has(charClassContext)\n ) {\n return getUnbalancedChar(escapesRemoved, '[', ']');\n } else if (\n regexContext === RegexContext.INTERVAL_QUANTIFIER ||\n enclosedTokenRegexContexts.has(regexContext) ||\n enclosedTokenCharClassContexts.has(charClassContext)\n ) {\n if (escapesRemoved.includes('}')) {\n return '}';\n }\n } else if (regexContext === RegexContext.GROUP_NAME) {\n if (escapesRemoved.includes('>')) {\n return '>';\n }\n }\n return '';\n}\n\nconst contextToken = new RegExp(String.raw`\n(?<groupN>\\(\\?<(?![=!])|\\\\[gk]<)\n| (?<enclosedPU>\\\\[pPu]\\{)\n| (?<enclosedQ>\\\\q\\{)\n| (?<intervalQ>\\{)\n| (?<incompleteT>\\\\(?: $\n | c(?![A-Za-z])\n | u(?![A-Fa-f\\d]{4})[A-Fa-f\\d]{0,3}\n | x(?![A-Fa-f\\d]{2})[A-Fa-f\\d]?\n )\n)\n| --\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\n@typedef {{\n regexContext: string;\n charClassContext: string;\n charClassDepth: number;\n lastPos: number;\n}} RunningContext\n*/\n/**\nAccepts and returns its full state so it doesn't have to reprocess parts that have already been\nseen. Assumes flag v and doesn't worry about syntax errors that are caught by it.\n@param {string} incompleteExpression\n@param {Partial<RunningContext>} [runningContext]\n@returns {RunningContext}\n*/\nexport function getEndContextForIncompleteExpression(incompleteExpression, {\n regexContext = RegexContext.DEFAULT,\n charClassContext = CharClassContext.DEFAULT,\n charClassDepth = 0,\n lastPos = 0,\n} = {}) {\n contextToken.lastIndex = lastPos;\n let match;\n while (match = contextToken.exec(incompleteExpression)) {\n const {0: m, groups: {groupN, enclosedPU, enclosedQ, intervalQ, incompleteT}} = match;\n if (m === '[') {\n charClassDepth++;\n regexContext = RegexContext.CHAR_CLASS;\n charClassContext = CharClassContext.DEFAULT;\n } else if (m === ']' && regexContext === RegexContext.CHAR_CLASS) {\n if (charClassDepth) {\n charClassDepth--;\n }\n if (!charClassDepth) {\n regexContext = RegexContext.DEFAULT;\n }\n charClassContext = CharClassContext.DEFAULT;\n } else if (regexContext === RegexContext.CHAR_CLASS) {\n if (incompleteT) {\n charClassContext = CharClassContext.INVALID_INCOMPLETE_TOKEN;\n } else if (m === '-') {\n charClassContext = CharClassContext.RANGE;\n } else if (enclosedPU) {\n charClassContext = m[1] === 'u' ? CharClassContext.ENCLOSED_U : CharClassContext.ENCLOSED_P;\n } else if (enclosedQ) {\n charClassContext = CharClassContext.ENCLOSED_Q;\n } else if (\n (m === '}' && enclosedTokenCharClassContexts.has(charClassContext)) ||\n // Don't continue in these contexts since we've advanced another token\n charClassContext === CharClassContext.INVALID_INCOMPLETE_TOKEN ||\n charClassContext === CharClassContext.RANGE\n ) {\n charClassContext = CharClassContext.DEFAULT;\n }\n } else {\n if (incompleteT) {\n regexContext = RegexContext.INVALID_INCOMPLETE_TOKEN;\n } else if (groupN) {\n regexContext = RegexContext.GROUP_NAME;\n } else if (enclosedPU) {\n regexContext = m[1] === 'u' ? RegexContext.ENCLOSED_U : RegexContext.ENCLOSED_P;\n } else if (intervalQ) {\n regexContext = RegexContext.INTERVAL_QUANTIFIER;\n } else if (\n (m === '>' && regexContext === RegexContext.GROUP_NAME) ||\n (m === '}' && (regexContext === RegexContext.INTERVAL_QUANTIFIER || enclosedTokenRegexContexts.has(regexContext))) ||\n // Don't continue in this context since we've advanced another token\n regexContext === RegexContext.INVALID_INCOMPLETE_TOKEN\n ) {\n regexContext = RegexContext.DEFAULT;\n }\n }\n }\n return {\n regexContext,\n charClassContext,\n charClassDepth,\n lastPos: incompleteExpression.length,\n };\n}\n\n// No special handling for escaped versions of the characters\nfunction getUnbalancedChar(expression, leftChar, rightChar) {\n let numOpen = 0;\n for (const [m] of expression.matchAll(new RegExp(`[${escapeV(leftChar + rightChar, Context.CHAR_CLASS)}]`, 'g'))) {\n numOpen += m === leftChar ? 1 : -1;\n if (numOpen < 0) {\n return rightChar;\n }\n }\n if (numOpen > 0) {\n return leftChar;\n }\n return '';\n}\n\n/**\n@typedef {import('./regex.js').InterpolatedValue} InterpolatedValue\n@typedef {import('./regex.js').RawTemplate} RawTemplate\n@typedef {import('./regex.js').RegexTagOptions} RegexTagOptions\n@typedef {(\n value: InterpolatedValue,\n runningContext: RunningContext,\n options: Required<RegexTagOptions>\n) => {\n transformed: string;\n runningContext: RunningContext;\n}} Preprocessor\n*/\n/**\nReturns transformed versions of a template and substitutions, using the given preprocessor. Only\nprocesses substitutions that are instanceof `Pattern`.\n@param {RawTemplate} template\n@param {ReadonlyArray<InterpolatedValue>} substitutions\n@param {Preprocessor} preprocessor\n@param {Required<RegexTagOptions>} options\n@returns {{template: RawTemplate; substitutions: ReadonlyArray<InterpolatedValue>;}}\n*/\nexport function preprocess(template, substitutions, preprocessor, options) {\n let /** @type {RawTemplate} */ newTemplate = {raw: []};\n let newSubstitutions = [];\n let runningContext;\n template.raw.forEach((raw, i) => {\n const result = preprocessor(raw, {...runningContext, lastPos: 0}, options);\n newTemplate.raw.push(result.transformed);\n runningContext = result.runningContext;\n if (i < template.raw.length - 1) {\n const substitution = substitutions[i];\n if (substitution instanceof Pattern) {\n const result = preprocessor(substitution, {...runningContext, lastPos: 0}, options);\n newSubstitutions.push(pattern(result.transformed));\n runningContext = result.runningContext;\n } else {\n newSubstitutions.push(substitution);\n }\n }\n });\n return {\n template: newTemplate,\n substitutions: newSubstitutions,\n };\n}\n\n// Sandbox `^` if relevant, done so it can't change the meaning of the surrounding character class\n// if we happen to be at the first position. See `sandboxLoneDoublePunctuatorChar` for more details\nexport function sandboxLoneCharClassCaret(str) {\n return str.replace(/^\\^/, '\\\\^^');\n}\n\n// Sandbox without escaping by repeating the character and escaping only the first one. The second\n// one is so that, if followed by the same symbol, the resulting double punctuator will still throw\n// as expected. Details:\n// - Only need to check the first position because, if it's part of an implicit union,\n// interpolation handling will wrap it in nested `[…]`.\n// - Can't just wrap in nested `[…]` here, since the value might be used in a range.\n// - Can't add a second unescaped symbol if a lone symbol is the entire string because it might be\n// followed by the same unescaped symbol outside an interpolation, and since it won't be wrapped,\n// the second symbol wouldn't be sandboxed from the one following it.\nexport function sandboxLoneDoublePunctuatorChar(str) {\n return str.replace(new RegExp(`^([${doublePunctuatorChars}])(?!\\\\1)`), (m, _, pos) => {\n return `\\\\${m}${pos + 1 === str.length ? '' : m}`;\n });\n}\n\n/**\nConverts `\\0` tokens to `\\x00` in the given context.\n@param {string} str\n@param {'DEFAULT' | 'CHAR_CLASS'} [context] `Context` option from lib `regex-utilities`\n@returns {string}\n*/\nexport function sandboxUnsafeNulls(str, context) {\n // regex`[\\0${0}]` and regex`[${pattern`\\0`}0]` can't be guarded against via nested `[…]`\n // sandboxing in character classes if the interpolated value doesn't contain union (since it\n // might be placed on a range boundary). So escape `\\0` in character classes as `\\x00`\n return replaceUnescaped(str, String.raw`\\\\0(?!\\d)`, '\\\\x00', context);\n}\n\n/**\n@param {string} str\n@param {number} pos\n@param {string} oldValue\n@param {string} newValue\n@returns {string}\n*/\nexport function spliceStr(str, pos, oldValue, newValue) {\n return str.slice(0, pos) + newValue + str.slice(pos + oldValue.length);\n}\n","import {emulationGroupMarker, noncapturingDelim, spliceStr} from './utils.js';\nimport {Context, replaceUnescaped} from 'regex-utilities';\n\nconst atomicPluginToken = new RegExp(String.raw`(?<noncapturingStart>${noncapturingDelim})|(?<capturingStart>\\((?:\\?<[^>]+>)?)|\\\\?.`, 'gsu');\n\n/**\nApply transformations for atomic groups: `(?>…)`.\n@param {string} expression\n@param {import('./regex.js').PluginData} [data]\n@returns {string}\n*/\nexport function atomic(expression, data) {\n if (!/\\(\\?>/.test(expression)) {\n return expression;\n }\n const aGDelim = '(?>';\n const emulatedAGDelim = `(?:(?=(${data?.useEmulationGroups ? emulationGroupMarker : ''}`;\n const captureNumMap = [0];\n let numCapturesBeforeAG = 0;\n let numAGs = 0;\n let aGPos = NaN;\n let hasProcessedAG;\n do {\n hasProcessedAG = false;\n let numCharClassesOpen = 0;\n let numGroupsOpenInAG = 0;\n let inAG = false;\n let match;\n atomicPluginToken.lastIndex = Number.isNaN(aGPos) ? 0 : aGPos + emulatedAGDelim.length;\n while (match = atomicPluginToken.exec(expression)) {\n const {0: m, index, groups: {capturingStart, noncapturingStart}} = match;\n if (m === '[') {\n numCharClassesOpen++;\n } else if (!numCharClassesOpen) {\n\n if (m === aGDelim && !inAG) {\n aGPos = index;\n inAG = true;\n } else if (inAG && noncapturingStart) {\n numGroupsOpenInAG++;\n } else if (capturingStart) {\n if (inAG) {\n numGroupsOpenInAG++;\n } else {\n numCapturesBeforeAG++;\n captureNumMap.push(numCapturesBeforeAG + numAGs);\n }\n } else if (m === ')' && inAG) {\n if (!numGroupsOpenInAG) {\n numAGs++;\n // Replace `expression` and use `<$$N>` as a temporary wrapper for the backref so it\n // can avoid backref renumbering afterward. Need to wrap the whole substitution\n // (including the lookahead and following backref) in a noncapturing group to handle\n // following quantifiers and literal digits\n expression = `${expression.slice(0, aGPos)}${emulatedAGDelim}${\n expression.slice(aGPos + aGDelim.length, index)\n }))<$$${numAGs + numCapturesBeforeAG}>)${expression.slice(index + 1)}`;\n hasProcessedAG = true;\n break;\n }\n numGroupsOpenInAG--;\n }\n\n } else if (m === ']') {\n numCharClassesOpen--;\n }\n }\n // Start over from the beginning of the last atomic group's contents, in case the processed group\n // contains additional atomic groups\n } while (hasProcessedAG);\n\n // Second pass to adjust numbered backrefs\n expression = replaceUnescaped(\n expression,\n String.raw`\\\\(?<backrefNum>[1-9]\\d*)|<\\$\\$(?<wrappedBackrefNum>\\d+)>`,\n ({0: m, groups: {backrefNum, wrappedBackrefNum}}) => {\n if (backrefNum) {\n const bNum = +backrefNum;\n if (bNum > captureNumMap.length - 1) {\n throw new Error(`Backref \"${m}\" greater than number of captures`);\n }\n return `\\\\${captureNumMap[bNum]}`;\n }\n return `\\\\${wrappedBackrefNum}`;\n },\n Context.DEFAULT\n );\n return expression;\n}\n\nconst baseQuantifier = String.raw`(?:[?*+]|\\{\\d+(?:,\\d*)?\\})`;\n// Complete tokenizer for base syntax; doesn't (need to) know about character-class-only syntax\nconst possessivePluginToken = new RegExp(String.raw`\n\\\\(?: \\d+\n | c[A-Za-z]\n | [gk]<[^>]+>\n | [pPu]\\{[^\\}]+\\}\n | u[A-Fa-f\\d]{4}\n | x[A-Fa-f\\d]{2}\n )\n| \\((?: \\? (?: [:=!>]\n | <(?:[=!]|[^>]+>)\n | [A-Za-z\\-]+:\n | \\(DEFINE\\)\n ))?\n| (?<qBase>${baseQuantifier})(?<qMod>[?+]?)(?<invalidQ>[?*+\\{]?)\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\nTransform posessive quantifiers into atomic groups. The posessessive quantifiers are:\n`?+`, `*+`, `++`, `{N}+`, `{N,}+`, `{N,N}+`.\nThis follows Java, PCRE, Perl, and Python.\nPossessive quantifiers in Oniguruma and Onigmo are only: `?+`, `*+`, `++`.\n@param {string} expression\n@returns {string}\n*/\nexport function possessive(expression) {\n if (!(new RegExp(`${baseQuantifier}\\\\+`).test(expression))) {\n return expression;\n }\n const openGroupIndices = [];\n let lastGroupIndex = null;\n let lastCharClassIndex = null;\n let lastToken = '';\n let numCharClassesOpen = 0;\n let match;\n possessivePluginToken.lastIndex = 0;\n while (match = possessivePluginToken.exec(expression)) {\n const {0: m, index, groups: {qBase, qMod, invalidQ}} = match;\n if (m === '[') {\n if (!numCharClassesOpen) {\n lastCharClassIndex = index;\n }\n numCharClassesOpen++;\n } else if (m === ']') {\n if (numCharClassesOpen) {\n numCharClassesOpen--;\n // Unmatched `]`\n } else {\n lastCharClassIndex = null;\n }\n } else if (!numCharClassesOpen) {\n\n if (qMod === '+' && lastToken && !lastToken.startsWith('(')) {\n // Invalid following quantifier would become valid via the wrapping group\n if (invalidQ) {\n throw new Error(`Invalid quantifier \"${m}\"`);\n }\n let charsAdded = -1; // -1 for removed trailing `+`\n // Possessivizing fixed repetition quantifiers like `{2}` does't change their behavior, so\n // avoid doing so (convert them to greedy)\n if (/^\\{\\d+\\}$/.test(qBase)) {\n expression = spliceStr(expression, index + qBase.length, qMod, '');\n } else {\n if (lastToken === ')' || lastToken === ']') {\n const nodeIndex = lastToken === ')' ? lastGroupIndex : lastCharClassIndex;\n // Unmatched `)` would break out of the wrapping group and mess with handling.\n // Unmatched `]` wouldn't be a problem, but it's unnecessary to have dedicated support\n // for unescaped `]++` since this won't work with flag u or v anyway\n if (nodeIndex === null) {\n throw new Error(`Invalid unmatched \"${lastToken}\"`);\n }\n expression = `${expression.slice(0, nodeIndex)}(?>${expression.slice(nodeIndex, index)}${qBase})${expression.slice(index + m.length)}`;\n } else {\n expression = `${expression.slice(0, index - lastToken.length)}(?>${lastToken}${qBase})${expression.slice(index + m.length)}`;\n }\n charsAdded += 4; // `(?>)`\n }\n possessivePluginToken.lastIndex += charsAdded;\n } else if (m[0] === '(') {\n openGroupIndices.push(index);\n } else if (m === ')') {\n lastGroupIndex = openGroupIndices.length ? openGroupIndices.pop() : null;\n }\n\n }\n lastToken = m;\n }\n return expression;\n}\n","import {doublePunctuatorChars} from './utils.js';\n\nconst incompatibleEscapeChars = '&!#%,:;<=>@`~';\nconst token = new RegExp(String.raw`\n\\[\\^?-?\n| --?\\]\n| (?<dp>[${doublePunctuatorChars}])\\k<dp>\n| --\n| \\\\(?<vOnlyEscape>[${incompatibleEscapeChars}])\n| \\\\[pPu]\\{[^}]+\\}\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\nApplies flag v rules when using flag u, for forward compatibility.\nAssumes flag u and doesn't worry about syntax errors that are caught by it.\n@param {string} expression\n@returns {string}\n*/\nexport function backcompatPlugin(expression) {\n const unescapedLiteralHyphenMsg = 'Invalid unescaped \"-\" in character class';\n let inCharClass = false;\n let result = '';\n for (const {0: m, groups: {dp, vOnlyEscape}} of expression.matchAll(token)) {\n if (m[0] === '[') {\n if (inCharClass) {\n throw new Error('Invalid nested character class when flag v not supported; possibly from interpolation');\n }\n if (m.endsWith('-')) {\n throw new Error(unescapedLiteralHyphenMsg);\n }\n inCharClass = true;\n } else if (m.endsWith(']')) {\n if (m[0] === '-') {\n throw new Error(unescapedLiteralHyphenMsg);\n }\n inCharClass = false;\n } else if (inCharClass) {\n if (m === '&&' || m === '--') {\n throw new Error(`Invalid set operator \"${m}\" when flag v not supported`);\n } else if (dp) {\n throw new Error(`Invalid double punctuator \"${m}\", reserved by flag v`);\n } else if ('(){}/|'.includes(m)) {\n throw new Error(`Invalid unescaped \"${m}\" in character class`);\n } else if (vOnlyEscape) {\n // Remove the escaping backslash to emulate flag v rules, since this character is allowed\n // to be escaped within character classes with flag v but not with flag u\n result += vOnlyEscape;\n continue;\n }\n }\n result += m;\n }\n return result;\n}\n","import {getEndContextForIncompleteExpression, noncapturingDelim, RegexContext} from './utils.js';\n\nconst token = new RegExp(String.raw`\n${noncapturingDelim}\n| \\(\\?<\n| (?<backrefNum>\\\\[1-9]\\d*)\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\nApply transformations for flag n (named capture only).\n\nPreprocessors are applied to the outer regex and interpolated patterns, but not interpolated\nregexes or strings.\n@type {import('./utils.js').Preprocessor}\n*/\nexport function flagNPreprocessor(value, runningContext) {\n value = String(value);\n let expression = '';\n let transformed = '';\n for (const {0: m, groups: {backrefNum}} of value.matchAll(token)) {\n expression += m;\n runningContext = getEndContextForIncompleteExpression(expression, runningContext);\n const {regexContext} = runningContext;\n if (regexContext === RegexContext.DEFAULT) {\n if (m === '(') {\n transformed += '(?:';\n } else if (backrefNum) {\n throw new Error(`Invalid decimal escape \"${m}\" with implicit flag n; replace with named backreference`);\n } else {\n transformed += m;\n }\n } else {\n transformed += m;\n }\n }\n return {\n transformed,\n runningContext,\n };\n}\n","import {CharClassContext, doublePunctuatorChars, emulationGroupMarker, getEndContextForIncompleteExpression, noncapturingDelim, RegexContext, sandboxLoneDoublePunctuatorChar, sandboxUnsafeNulls} from './utils.js';\nimport {Context, replaceUnescaped} from 'regex-utilities';\n\nconst ws = /^\\s$/;\nconst escapedWsOrHash = /^\\\\[\\s#]$/;\nconst charClassWs = /^[ \\t]$/;\nconst escapedCharClassWs = /^\\\\[ \\t]$/;\nconst token = new RegExp(String.raw`\n\\\\(?: [gk]<\n | [pPu]\\{\n | c[A-Za-z]\n | u[A-Fa-f\\d]{4}\n | x[A-Fa-f\\d]{2}\n | 0\\d+\n)\n| \\[\\^\n| ${noncapturingDelim}\n| \\(\\?<\n| (?<dp>[${doublePunctuatorChars}])\\k<dp>\n| --\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\nApply transformations for flag x (insignificant whitespace and line comments).\n\nPreprocessors are applied to the outer regex and interpolated patterns, but not interpolated\nregexes or strings.\n@type {import('./utils.js').Preprocessor}\n*/\nexport function flagXPreprocessor(value, runningContext, options) {\n value = String(value);\n let ignoringWs = false;\n let ignoringCharClassWs = false;\n let ignoringComment = false;\n let expression = '';\n let transformed = '';\n let lastSignificantToken = '';\n let lastSignificantCharClassContext = '';\n let separatorNeeded = false;\n const update = (str, {prefix = true, postfix = false} = {}) => {\n str = (separatorNeeded && prefix ? '(?:)' : '') + str + (postfix ? '(?:)' : '');\n separatorNeeded = false;\n return str;\n };\n for (const {0: m, index} of value.matchAll(token)) {\n if (ignoringComment) {\n if (m === '\\n') {\n ignoringComment = false;\n separatorNeeded = true;\n }\n continue;\n }\n if (ignoringWs) {\n if (ws.test(m)) {\n continue;\n }\n ignoringWs = false;\n separatorNeeded = true;\n } else if (ignoringCharClassWs) {\n if (charClassWs.test(m)) {\n continue;\n }\n ignoringCharClassWs = false;\n }\n\n expression += m;\n runningContext = getEndContextForIncompleteExpression(expression, runningContext);\n const {regexContext, charClassContext} = runningContext;\n if (\n // `--` is matched in one step, so boundary chars aren't `-` unless separated by whitespace\n m === '-' &&\n regexContext === RegexContext.CHAR_CLASS &&\n lastSignificantCharClassContext === CharClassContext.RANGE &&\n (options.flags.includes('v') || options.unicodeSetsPlugin)\n ) {\n // Need to handle this here since the main regex-parsing code would think the hyphen forms\n // part of a subtraction operator since we've removed preceding whitespace\n throw new Error('Invalid unescaped hyphen as the end value for a range');\n }\n if (\n // `??` is matched in one step by the double punctuator token\n (regexContext === RegexContext.DEFAULT && /^(?:[?*+]|\\?\\?)$/.test(m)) ||\n (regexContext === RegexContext.INTERVAL_QUANTIFIER && m === '{')\n ) {\n // Skip the separator prefix and connect the quantifier to the previous token. This also\n // allows whitespace between a quantifier and the `?` that makes it lazy. Add a postfix\n // separator if `m` is `?` and we're following token `(`, to sandbox the `?` from following\n // tokens (since `?` can be a group-type marker). Ex: `( ?:)` becomes `(?(?:):)` and throws.\n // The loop we're in matches valid group openings in one step, so we won't arrive here if\n // matching e.g. `(?:`. Flag n could prevent the need for the postfix since bare `(` is\n // converted to `(?:`, but flag x handling always comes first and flag n can be turned off\n transformed += update(m, {prefix: false, postfix: lastSignificantToken === '(' && m === '?'});\n } else if (regexContext === RegexContext.DEFAULT) {\n if (ws.test(m)) {\n ignoringWs = true;\n } else if (m.startsWith('#')) {\n ignoringComment = true;\n } else if (escapedWsOrHash.test(m)) {\n transformed += update(m[1], {prefix: false});\n } else {\n transformed += update(m);\n }\n } else if (regexContext === RegexContext.CHAR_CLASS && m !== '[' && m !== '[^') {\n if (\n charClassWs.test(m) &&\n ( charClassContext === CharClassContext.DEFAULT ||\n charClassContext === CharClassContext.ENCLOSED_Q ||\n charClassContext === CharClassContext.RANGE\n )\n ) {\n ignoringCharClassWs = true;\n } else if (charClassContext === CharClassContext.INVALID_INCOMPLETE_TOKEN) {\n // Need to handle this here since the main regex-parsing code wouldn't know where the token\n // ends if we removed whitespace after an incomplete token that is followed by something\n // that completes the token\n throw new Error(`Invalid incomplete token in character class: \"${m}\"`);\n } else if (\n escapedCharClassWs.test(m) &&\n (charClassContext === CharClassContext.DEFAULT || charClassContext === CharClassContext.ENCLOSED_Q)\n ) {\n transformed += update(m[1], {prefix: false});\n } else if (charClassContext === CharClassContext.DEFAULT) {\n const nextChar = value[index + 1] ?? '';\n let updated = sandboxUnsafeNulls(m);\n // Avoid escaping lone double punctuators unless required, since some of them are not\n // allowed to be escaped with flag u (the `unicodeSetsPlugin` already unescapes them when\n // using flag u, but it can be set to `null` via an option)\n if (charClassWs.test(nextChar) || m === '^') {\n updated = sandboxLoneDoublePunctuatorChar(updated);\n }\n transformed += update(updated);\n } else {\n transformed += update(m);\n }\n } else {\n transformed += update(m);\n }\n if (!(ignoringWs || ignoringCharClassWs || ignoringComment)) {\n lastSignificantToken = m;\n lastSignificantCharClassContext = charClassContext;\n }\n }\n return {\n transformed,\n runningContext,\n };\n}\n\n/**\nRemove `(?:)` token separators (most likely added by flag x) in cases where it's safe to do so.\n@param {string} expression\n@returns {string}\n*/\nexport function clean(expression) {\n const sep = String.raw`\\(\\?:\\)`;\n // No need for repeated separators\n expression = replaceUnescaped(expression, `(?:${sep}){2,}`, '(?:)', Context.DEFAULT);\n // No need for separators at:\n // - The beginning, if not followed by a quantifier.\n // - The end.\n // - Outside of character classes:\n // - If followed by one of `)|.[$\\\\`, or `(` if that's not followed by `DEFINE)`.\n // - Technically we shouldn't remove `(?:)` if preceded by `(?(DEFINE` and followed by `)`,\n // but in this case flag x injects a sandboxing `(?:)` after the preceding invalid `(?`,\n // so we already get an error from that.\n // - If preceded by one of `()|.]^>`, `\\\\[bBdDfnrsStvwW]`, `(?:`, or a lookaround opening.\n // - So long as the separator is not followed by a quantifier.\n // - And, not followed by an emulation group marker.\n // Examples of things that are not safe to remove `(?:)` at the boundaries of:\n // - Anywhere: Letters, numbers, or any of `-=_,<?*+{}`.\n // - If followed by any of `:!>`.\n // - If preceded by any of `\\\\[cgkpPux]`.\n // - Anything inside character classes.\n const marker = emulationGroupMarker.replace(/\\$/g, '\\\\$');\n expression = replaceUnescaped(\n expression,\n String.raw`(?:${sep}(?=[)|.[$\\\\]|\\((?!DEFINE)|$)|(?<=[()|.\\]^>]|\\\\[bBdDfnrsStvwW]|\\(\\?(?:[:=!]|<[=!])|^)${sep}(?![?*+{]))(?!${marker})`,\n '',\n Context.DEFAULT\n );\n return expression;\n}\n","import {capturingDelim, countCaptures, emulationGroupMarker, namedCapturingDelim, spliceStr} from './utils.js';\nimport {Context, execUnescaped, forEachUnescaped, getGroupContents, hasUnescaped, replaceUnescaped} from 'regex-utilities';\n\n/**\n@param {string} expression\n@param {import('./regex.js').PluginData} [data]\n@returns {string}\n*/\nexport function subroutines(expression, data) {\n // NOTE: subroutines and definition groups fully support numbered backreferences and unnamed\n // captures (from interpolated regexes or from turning implicit flag n off), and all of the\n // complex forward and backward backreference adjustments that can result\n const namedGroups = getNamedCapturingGroups(expression, {includeContents: true});\n const transformed = processSubroutines(expression, namedGroups, !!data?.useEmulationGroups);\n return processDefinitionGroup(transformed, namedGroups);\n}\n\n// Explicitly exclude `&` from subroutine name chars because it's used by extension\n// `regex-recursion` for recursive subroutines via `\\g<name&R=N>`\nconst subroutinePattern = String.raw`\\\\g<(?<subroutineName>[^>&]+)>`;\nconst token = new RegExp(String.raw`\n${subroutinePattern}\n| (?<capturingStart>${capturingDelim})\n| \\\\(?<backrefNum>[1-9]\\d*)\n| \\\\k<(?<backrefName>[^>]+)>\n| \\\\?.\n`.replace(/\\s+/g, ''), 'gsu');\n\n/**\n@typedef {\n Map<string, {\n isUnique: boolean;\n contents?: string;\n groupNum?: number;\n numCaptures?: number;\n }>} NamedCapturingGroupsMap\n*/\n/**\nApply transformations for subroutines: `\\g<name>`.\n@param {string} expression\n@param {NamedCapturingGroupsMap} namedGroups\n@param {boolean} useEmulationGroups\n@returns {string}\n*/\nfunction processSubroutines(expression, namedGroups, useEmulationGroups) {\n if (!/\\\\g</.test(expression)) {\n return expression;\n }\n // Can skip a lot of processing and avoid adding captures if there are no backrefs\n const hasBackrefs = hasUnescaped(expression, '\\\\\\\\(?:[1-9]|k<[^>]+>)', Context.DEFAULT);\n const subroutineWrapper = hasBackrefs ? `(${useEmulationGroups ? emulationGroupMarker : ''}` : '(?:';\n const openSubroutines = new Map();\n const openSubroutinesStack = [];\n const captureNumMap = [0];\n let numCapturesPassedOutsideSubroutines = 0;\n let numCapturesPassedInsideSubroutines = 0;\n let numCapturesPassedInsideThisSubroutine = 0;\n let numSubroutineCapturesTrackedInRemap = 0;\n let numCharClassesOpen = 0;\n let result = expression;\n let match;\n token.lastIndex = 0;\n while (match = token.exec(result)) {\n const {0: m, index, groups: {subroutineName, capturingStart, backrefNum, backrefName}} = match;\n if (m === '[') {\n numCharClassesOpen++;\n } else if (!numCharClassesOpen) {\n\n if (subroutineName) {\n if (!namedGroups.has(subroutineName)) {\n throw new Error(`Invalid named capture referenced by subroutine ${m}`);\n }\n if (openSubroutines.has(subroutineName)) {\n throw new Error(`Subroutine ${m} followed a recursive reference`);\n }\n const contents = namedGroups.get(subroutineName).contents;\n // Wrap value in case it has top-level alternation or is followed by a quantifier. The\n // wrapper also marks the end of the expanded contents, which we'll track using\n // `unclosedGroupCount`. If there are any backrefs in the expression, wrap with `()`\n // instead of `(?:)` in case there are backrefs inside the subroutine that refer to their\n // containing capturing group\n const subroutineValue = `${subroutineWrapper}${contents})`;\n if (hasBackrefs) {\n numCapturesPassedInsideThisSubroutine = 0;\n numCapturesPassedInsideSubroutines++;\n }\n openSubroutines.set(subroutineName, {\n // Incrementally decremented to track when we've left the group\n unclosedGroupCount: countOpenParens(subroutineValue),\n });\n openSubroutinesStack.push(subroutineName);\n // Expand the subroutine's contents into the pattern we're looping over\n result = spliceStr(result, index, m, subroutineValue);\n token.lastIndex -= m.length - subroutineWrapper.length;\n } else if (capturingStart) {\n // Somewhere within an expanded subroutine\n if (openSubroutines.size) {\n if (hasBackrefs) {\n numCapturesPassedInsideThisSubroutine++;\n numCapturesPassedInsideSubroutines++;\n }\n // Named capturing group\n if (m !== '(') {\n // Replace named with unnamed capture. Subroutines ideally wouldn't create any new\n // captures, but it can't be helped since we need any backrefs to this capture to work.\n // Given that flag n prevents unnamed capture and thereby requires you to rely on named\n // backrefs and `groups`, switching to unnamed essentially accomplishes not creating a\n // capture. Can fully avoid capturing if there are no backrefs in the expression\n result = spliceStr(result, index, m, subroutineWrapper);\n token.lastIndex -= m.length - subroutineWrapper.length;\n }\n } else if (hasBackrefs) {\n captureNumMap.push(\n lastOf(captureNumMap) + 1 +\n numCapturesPassedInsideSubroutines -\n numSubroutineCapturesTrackedInRemap\n );\n numSubroutineCapturesTrackedInRemap = numCapturesPassedInsideSubroutines;\n numCapturesPassedOutsideSubroutines++;\n }\n } else if ((backrefNum || backrefName) && openSubroutines.size) {\n // Unify handling for named and unnamed by always using the backref num\n const num = backrefNum ? +backrefNum : namedGroups.get(backrefName)?.groupNum;\n let isGroupFromThisSubroutine = false;\n // Search for the group in the contents of the subroutine stack\n for (const s of openSubroutinesStack) {\n const group = namedGroups.get(s);\n if (num >= group.groupNum && num <= (group.groupNum + group.numCaptures)) {\n isGroupFromThisSubroutine = true;\n break;\n }\n }\n if (isGroupFromThisSubroutine) {\n const group = namedGroups.get(lastOf(openSubroutinesStack));\n // Replace the backref with metadata we'll need to rewrite it later, using\n // `\\k<$$bNsNrNcN>` as a temporary wrapper:\n // - b: The unmodified matched backref num, or the corresponding num of a named backref\n // - s: The capture num of the subroutine we're most deeply nested in, including captures\n // added by expanding the contents of preceding subroutines\n // - r: The original capture num of the group that the subroutine we're most deeply\n // nested in references, not counting the effects of subroutines\n // - c: The number of captures within `r`, not counting the effects of subroutines\n const subroutineNum = numCapturesPassedOutsideSubroutines + numCapturesPassedInsideSubroutines - numCapturesPassedInsideThisSubroutine;\n const metadata = `\\\\k<$$b${num}s${subroutineNum}r${group.groupNum}c${group.numCaptures}>`;\n result = spliceStr(result, index, m, metadata);\n token.lastIndex += metadata.length - m.length;\n }\n } else if (m === ')') {\n if (openSubroutines.size) {\n const subroutine = openSubroutines.get(lastOf(openSubroutinesStack));\n subroutine.unclosedGroupCount--;\n if (!subroutine.unclosedGroupCount) {\n openSubroutines.delete(openSubroutinesStack.pop());\n }\n }\n }\n\n } else if (m === ']') {\n numCharClassesOpen--;\n }\n }\n\n if (hasBackrefs) {\n // Second pass to adjust backrefs\n result = replaceUnescaped(\n result,\n String.raw`\\\\(?:(?<bNum>[1-9]\\d*)|k<\\$\\$b(?<bNumSub>\\d+)s(?<subNum>\\d+)r(?<refNum>\\d+)c(?<refCaps>\\d+)>)`,\n ({0: m, groups: {bNum, bNumSub, subNum, refNum, refCaps}}) => {\n if (bNum) {\n const backrefNum = +bNum;\n if (backrefNum > captureNumMap.length - 1) {\n throw new Error(`Backref \"${m}\" greater than number of captures`);\n }\n return `\\\\${captureNumMap[backrefNum]}`;\n }\n const backrefNumInSubroutine = +bNumSub;\n const subroutineGroupNum = +subNum;\n const refGroupNum = +refNum;\n const numCapturesInRef = +refCaps;\n if (backrefNumInSubroutine < refGroupNum || backrefNumInSubroutine > (refGroupNum + numCapturesInRef)) {\n return `\\\\${captureNumMap[backrefNumInSubroutine]}`;\n }\n return `\\\\${subroutineGroupNum - refGroupNum + backrefNumInSubroutine}`;\n },\n Context.DEFAULT\n );\n }\n\n return result;\n}\n\n// `(?:)` allowed because it can be added by flag x's preprocessing of whitespace and comments\nconst defineGroupToken = new RegExp(String.raw`${namedCapturingDelim}|\\(\\?:\\)|(?<invalid>\\\\?.)`, 'gsu');\n\n/**\nRemove valid subroutine definition groups: `(?(DEFINE)…)`.\n@param {string} expression\n@param {NamedCapturingGroupsMap} namedGroups\nIMPORTANT: Avoid using the `contents` property of `namedGroups` objects, because at this point\nsubroutine substitution has been performed on the corresponding substrings in `expression`\n@returns {string}\n*/\nfunction processDefinitionGroup(expression, namedGroups) {\n const defineMatch = execUnescaped(expression, String.raw`\\(\\?\\(DEFINE\\)`, 0, Context.DEFAULT);\n if (!defineMatch) {\n return expression;\n }\n const defineGroup = getGroup(expression, defineMatch);\n if (defineGroup.afterPos < expression.length) {\n // Supporting DEFINE at positions other than the end would complicate backref handling.\n // NOTE: Flag x's preprocessing permits trailing whitespace and comments\n throw new Error('DEFINE group allowed only at the end of a regex');\n } else if (defineGroup.afterPos > expression.length) {\n throw new Error('DEFINE group is unclosed');\n }\n let match;\n defineGroupToken.lastIndex = 0;\n while (match = defineGroupToken.exec(defineGroup.contents)) {\n const {captureName, invalid} = match.groups;\n if (captureName) {\n const group = getGroup(defineGroup.contents, match);\n let duplicateName;\n if (!namedGroups.get(captureName).isUnique) {\n duplicateName = captureName;\n } else {\n const nestedNamedGroups = getNamedCapturingGroups(group.contents);\n for (const name of nestedNamedGroups.keys()) {\n if (!namedGroups.get(name).isUnique) {\n duplicateName = name;\n break;\n }\n }\n }\n if (duplicateName) {\n throw new Error(`Duplicate group name \"${duplicateName}\" within DEFINE`);\n }\n defineGroupToken.lastIndex = group.afterPos;\n } else if (invalid) {\n // Since a DEFINE group is stripped from its expression, we can't easily determine whether\n // unreferenced top-level syntax within it is valid. Such syntax serves no purpose, so it's\n // easiest to not allow it\n throw new Error(`DEFINE group includes unsupported syntax at top level`);\n }\n }\n return expression.slice(0, defineMatch.index);\n}\n\n/**\nCounts unescaped open parens outside of character classes, regardless of group type\n@param {string} expression\n@returns {number}\n*/\nfunction countOpenParens(expression) {\n let num = 0;\n forEachUnescaped(expression, '\\\\(', () => num++, Context.DEFAULT);\n return num;\n}\n\n/**\n@param {string} expression\n@param {string} groupName\n@returns {number}\n*/\nfunction getCaptureNum(expression, groupName) {\n let num = 0;\n let pos = 0;\n let match;\n while (match = execUnescaped(expression, capturingDelim, pos, Context.DEFAULT)) {\n const {0: m, index, groups: {captureName}} = match;\n num++;\n if (captureName === groupName) {\n break;\n }\n pos = index + m.length;\n }\n return num;\n}\n\n/**\n@param {string} expression\n@param {RegExpExecArray} delimMatch\n@returns {{contents: string; afterPos: number}}\n*/\nfunction getGroup(expression, delimMatch) {\n const contentsStart = delimMatch.index + delimMatch[0].length;\n const contents = getGroupContents(expression, contentsStart);\n const afterPos = contentsStart + contents.length + 1;\n return {\n contents,\n afterPos,\n };\n}\n\n/**\n@param {string} expression\n@param {{includeContents: boolean}} [options]\n@returns {NamedCapturingGroupsMap}\n*/\nfunction getNamedCapturingGroups(expression, {includeContents} = {}) {\n const namedGroups = new Map();\n forEachUnescaped(\n expression,\n namedCapturingDelim,\n ({0: m, index, groups: {captureName}}) => {\n // If there are duplicate capture names, subroutines refer to the first instance of the given\n // group (matching the behavior of PCRE and Perl)\n if (namedGroups.has(captureName)) {\n namedGroups.get(captureName).isUnique = false;\n } else {\n const group = {isUnique: true};\n if (includeContents) {\n const contents = getGroupContents(expression, index + m.length);\n Object.assign(group, {\n contents,\n groupNum: getCaptureNum(expression, captureName),\n numCaptures: countCaptures(contents),\n });\n }\n namedGroups.set(captureName, group);\n }\n },\n Context.DEFAULT\n );\n return namedGroups;\n}\n\n/**\n@param {Array<any>} arr\n@returns {any}\n*/\nfunction lastOf(arr) {\n // Remove when support for ES2022 array method `at` (Node.js 16.6) is no longer an issue:\n // <https://caniuse.com/mdn-javascript_builtins_array_at>\n return arr[arr.length - 1];\n}\n","import { rewrite } from 'regex';\n\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => {\n __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nclass RegExpConversionError extends SyntaxError {\n constructor(message, options) {\n super(message, { cause: options.cause });\n __publicField(this, \"patternOriginal\");\n __publicField(this, \"patternConverted\");\n __publicField(this, \"cursorPosition\");\n this.patternOriginal = options.pattern;\n this.patternConverted = options.converted;\n this.cursorPosition = options.cursor;\n }\n}\n\nconst UNNECESSARY_ESCAPE_CHAR_CLASS = new Set(\"!?:=+$(){}_><# \");\nconst UNNECESSARY_ESCAPE = new Set(\"-!:=_>< \");\nconst TABLE_POSIX = {\n alnum: \"0-9A-Za-z\",\n alpha: \"A-Za-z\",\n ascii: \"\\0-\\x7F\",\n blank: \" \\\\t\",\n cntrl: \"\\0-\u001f\\x7F\",\n digit: \"\\\\d\",\n graph: \"!-~\",\n lower: \"a-z\",\n print: \" -~\",\n punct: \"!-/:-@[-`{-~\",\n space: \"\\\\s\",\n upper: \"A-Z\",\n xdigit: \"0-9A-Fa-f\",\n word: \"\\\\w\"\n};\nconst TABLE_SLASH_P = {\n alnum: \"0-9A-Za-z\",\n alpha: \"A-Za-z\",\n alphabetic: \"A-Za-z\",\n blank: \"\\\\s\",\n greek: \"\\\\p{Script=Greek}\",\n print: \"\\\\p{L}\\\\p{N}\\\\p{P}\\\\p{S}\\\\p{Zs}\",\n word: \"\\\\w\"\n};\nconst KNOWN_FLAGS = /* @__PURE__ */ new Set(\"gimsuyx\");\nfunction syntaxLowering(input, options = {}) {\n const {\n useRegex = false,\n preserveFlags = false,\n removePossessiveQuantifier = false,\n removeAtomicGroup = false,\n convertHexDigitsShorthand = false,\n convertUnicodeCategory = false,\n expandNestedCharacterClass = false\n } = options;\n let output = \"\";\n const flags = /* @__PURE__ */ new Set();\n const stack = [];\n const freeSpacingLocal = [];\n let freeSpacingGlobal = false;\n let isInNestedCharClass = false;\n let i = 0;\n try {\n while (i < input.length) {\n const char = input[i];\n while (freeSpacingLocal.length && freeSpacingLocal[0] > stack.length) {\n freeSpacingLocal.shift();\n }\n const head = stack[0];\n const freeSpacing = freeSpacingGlobal || freeSpacingLocal.length;\n if (char === \"\\\\\") {\n if (convertHexDigitsShorthand) {\n if (input[i + 1] === \"h\") {\n const body = `0-9A-Fa-f`;\n if (head === \"[\") {\n output += body;\n } else {\n output += `[${body}]`;\n }\n i += 2;\n continue;\n }\n if (input[i + 1] === \"H\") {\n if (head === \"[\") {\n throw new RegExpConversionError(\n \"Expending \\\\H in character class is not supported\",\n { pattern: input, converted: output, cursor: i }\n );\n } else {\n output += `[^0-9A-Fa-f]`;\n }\n i += 2;\n continue;\n }\n }\n if (convertUnicodeCategory && input[i + 1] === \"p\" && input[i + 2] === \"{\") {\n const end = input.indexOf(\"}\", i + 3);\n if (end === -1) {\n throw new RegExpConversionError(\n \"Unmatched \\\\p{...}\",\n { pattern: input, converted: output, cursor: i }\n );\n }\n const name = input.slice(i + 3, end);\n const resolved = TABLE_SLASH_P[name.toLowerCase()];\n if (resolved) {\n if (head === \"[\") {\n output += resolved;\n } else {\n output += `[${resolved}]`;\n }\n i = end + 1;\n continue;\n }\n }\n if (head === \"[\" && UNNECESSARY_ESCAPE_CHAR_CLASS.has(input[i + 1])) {\n output += input[i + 1];\n i += 2;\n continue;\n }\n if (head !== \"[\" && UNNECESSARY_ESCAPE.has(input[i + 1])) {\n output += input[i + 1];\n i += 2;\n continue;\n }\n output += char + input[i + 1];\n i += 2;\n continue;\n }\n if (char === \"#\" && freeSpacing && input[i - 1].match(/\\s/) && head !== \"[\") {\n for (let j = i + 1; j <= input.length; j++) {\n if (input[j] === \"\\n\" || j === input.length) {\n i = j;\n break;\n }\n }\n continue;\n }\n if (char === \"(\" && head !== \"[\") {\n if (input[i + 1] === \"?\") {\n if (input[i + 2] === \"#\") {\n for (let j = i + 3; j < input.length; j++) {\n if (input[j] === \")\" && input[j - 1] !== \"\\\\\") {\n i = j + 1;\n break;\n }\n }\n continue;\n }\n if (removeAtomicGroup && input[i + 2] === \">\") {\n output += \"(?:\";\n i += 3;\n continue;\n }\n if (KNOWN_FLAGS.has(input[i + 2])) {\n let end = i + 3;\n for (; end < input.length; end++) {\n if (!KNOWN_FLAGS.has(input[end]))\n break;\n }\n const flagStr2 = input.slice(i + 2, end);\n const hasX = flagStr2.includes(\"x\") && flagStr2[0] !== \"-\";\n let remainFlags = [...flagStr2].filter((x) => x !== \"x\").join(\"\");\n if (!preserveFlags) {\n if (remainFlags[0] === \"-\") {\n remainFlags = remainFlags.slice(1);\n for (const flag of flagStr2) {\n flags.delete(flag);\n }\n } else {\n for (const flag of remainFlags) {\n flags.add(flag);\n }\n }\n remainFlags = \"\";\n }\n if (input[end] === \")\") {\n i = end + 1;\n if (hasX) {\n freeSpacingGlobal = true;\n }\n if (remainFlags.length) {\n output += `(?${remainFlags})`;\n }\n continue;\n } else if (input[end] === \":\") {\n i = end + 1;\n stack.unshift(char);\n if (hasX) {\n freeSpacingLocal.unshift(stack.length);\n }\n output += `(?${remainFlags}:`;\n continue;\n }\n }\n stack.unshift(char);\n output += char + input[i + 1] + input[i + 2];\n i += 3;\n } else {\n stack.unshift(char);\n output += char;\n i += 1;\n }\n continue;\n }\n if (char === \")\" && head !== \"[\") {\n if (head === \"(\")\n stack.shift();\n output += char;\n i += 1;\n continue;\n }\n if (char === \"[\") {\n if (input[i + 1] === \":\") {\n let name = \"\";\n let negated = false;\n if (input[i + 2] === \"^\") {\n negated = true;\n i += 1;\n }\n for (let j = i + 2; j < input.length; j++) {\n if (input[j] === \":\") {\n i = j + 2;\n break;\n }\n if (!input[j].match(/[a-z]/i)) {\n name = \"\";\n break;\n }\n name += input[j];\n }\n if (name) {\n let resolved = TABLE_POSIX[name];\n if (!resolved) {\n throw new RegExpConversionError(\n `Unknown posix class \"${name}\"`,\n { pattern: input, converted: output, cursor: i }\n );\n }\n if (negated)\n resolved = `^${resolved}`;\n if (head === \"[\")\n output += resolved;\n else\n output += `[${resolved}]`;\n continue;\n }\n }\n if (head !== \"[\") {\n stack.unshift(char);\n }\n if (head === \"[\" && expandNestedCharacterClass) {\n isInNestedCharClass = true;\n i += 1;\n if (input[i] === \"-\") {\n output += \"\\\\-\";\n i += 1;\n }\n continue;\n }\n output += char;\n i += 1;\n continue;\n }\n if (char === \"]\") {\n if (isInNestedCharClass) {\n isInNestedCharClass = false;\n i += 1;\n continue;\n }\n if (head === \"[\")\n stack.shift();\n output += char;\n i += 1;\n continue;\n }\n if (removePossessiveQuantifier && char === \"+\" && head !== \"[\") {\n if (\"?+}*\".includes(input[i - 1])) {\n i += 1;\n continue;\n }\n }\n if (char === \"*\" && head !== \"[\" && input[i - 1] === \"|\" && input[i - 2] !== \"\\\\\") {\n output += \"\\\\\";\n }\n if (!(freeSpacing && head !== \"[\" && char.match(/\\s/))) {\n output += char;\n }\n i += 1;\n }\n } catch (e) {\n if (e instanceof RegExpConversionError)\n throw e;\n throw new RegExpConversionError(\n `Error lowering regex at position ${i}`,\n { pattern: input, converted: output, cursor: i, cause: e }\n );\n }\n const flagStr = [...flags].join(\"\");\n if (useRegex) {\n output = rewrite(\n output,\n {\n flags: flagStr,\n unicodeSetsPlugin: null,\n disable: {\n n: true,\n v: true,\n x: true\n }\n }\n ).expression;\n }\n return {\n pattern: output,\n flags: flagStr\n };\n}\n\nexport { RegExpConversionError as R, syntaxLowering as s };\n","import { ShikiError as ShikiError$1 } from '@shikijs/types';\nexport * from '@shikijs/types';\nimport { createOnigurumaEngine as createOnigurumaEngine$1, loadWasm as loadWasm$1, getDefaultWasmLoader } from '@shikijs/engine-oniguruma';\nimport { w as warnDeprecated } from './shared/core.afb6276c.mjs';\nexport { e as enableDeprecationWarnings } from './shared/core.afb6276c.mjs';\nimport { FontStyle, INITIAL, EncodedTokenMetadata, Registry as Registry$1, Theme } from '@shikijs/vscode-textmate';\nexport { FontStyle, EncodedTokenMetadata as StackElementMetadata } from '@shikijs/vscode-textmate';\nimport { toHtml } from 'hast-util-to-html';\nexport { toHtml as hastToHtml } from 'hast-util-to-html';\nimport { createJavaScriptRegexEngine as createJavaScriptRegexEngine$1, defaultJavaScriptRegexConstructor as defaultJavaScriptRegexConstructor$1 } from '@shikijs/engine-javascript';\n\nfunction createOnigurumaEngine(options) {\n warnDeprecated(\"import `createOnigurumaEngine` from `@shikijs/engine-oniguruma` or `shiki/engine/oniguruma` instead\");\n return createOnigurumaEngine$1(options);\n}\nfunction createWasmOnigEngine(options) {\n warnDeprecated(\"import `createOnigurumaEngine` from `@shikijs/engine-oniguruma` or `shiki/engine/oniguruma` instead\");\n return createOnigurumaEngine$1(options);\n}\nfunction loadWasm(options) {\n warnDeprecated(\"import `loadWasm` from `@shikijs/engine-oniguruma` or `shiki/engine/oniguruma` instead\");\n return loadWasm$1(options);\n}\n\nfunction toArray(x) {\n return Array.isArray(x) ? x : [x];\n}\nfunction splitLines(code, preserveEnding = false) {\n const parts = code.split(/(\\r?\\n)/g);\n let index = 0;\n const lines = [];\n for (let i = 0; i < parts.length; i += 2) {\n const line = preserveEnding ? parts[i] + (parts[i + 1] || \"\") : parts[i];\n lines.push([line, index]);\n index += parts[i].length;\n index += parts[i + 1]?.length || 0;\n }\n return lines;\n}\nfunction isPlainLang(lang) {\n return !lang || [\"plaintext\", \"txt\", \"text\", \"plain\"].includes(lang);\n}\nfunction isSpecialLang(lang) {\n return lang === \"ansi\" || isPlainLang(lang);\n}\nfunction isNoneTheme(theme) {\n return theme === \"none\";\n}\nfunction isSpecialTheme(theme) {\n return isNoneTheme(theme);\n}\nfunction addClassToHast(node, className) {\n var _a;\n if (!className)\n return node;\n node.properties || (node.properties = {});\n (_a = node.properties).class || (_a.class = []);\n if (typeof node.properties.class === \"string\")\n node.properties.class = node.properties.class.split(/\\s+/g);\n if (!Array.isArray(node.properties.class))\n node.properties.class = [];\n const targets = Array.isArray(className) ? className : className.split(/\\s+/g);\n for (const c of targets) {\n if (c && !node.properties.class.includes(c))\n node.properties.class.push(c);\n }\n return node;\n}\nfunction splitToken(token, offsets) {\n let lastOffset = 0;\n const tokens = [];\n for (const offset of offsets) {\n if (offset > lastOffset) {\n tokens.push({\n ...token,\n content: token.content.slice(lastOffset, offset),\n offset: token.offset + lastOffset\n });\n }\n lastOffset = offset;\n }\n if (lastOffset < token.content.length) {\n tokens.push({\n ...token,\n content: token.content.slice(lastOffset),\n offset: token.offset + lastOffset\n });\n }\n return tokens;\n}\nfunction splitTokens(tokens, breakpoints) {\n const sorted = Array.from(breakpoints instanceof Set ? breakpoints : new Set(breakpoints)).sort((a, b) => a - b);\n if (!sorted.length)\n return tokens;\n return tokens.map((line) => {\n return line.flatMap((token) => {\n const breakpointsInToken = sorted.filter((i) => token.offset < i && i < token.offset + token.content.length).map((i) => i - token.offset).sort((a, b) => a - b);\n if (!breakpointsInToken.length)\n return token;\n return splitToken(token, breakpointsInToken);\n });\n });\n}\nasync function normalizeGetter(p) {\n return Promise.resolve(typeof p === \"function\" ? p() : p).then((r) => r.default || r);\n}\nfunction resolveColorReplacements(theme, options) {\n const replacements = typeof theme === \"string\" ? {} : { ...theme.colorReplacements };\n const themeName = typeof theme === \"string\" ? theme : theme.name;\n for (const [key, value] of Object.entries(options?.colorReplacements || {})) {\n if (typeof value === \"string\")\n replacements[key] = value;\n else if (key === themeName)\n Object.assign(replacements, value);\n }\n return replacements;\n}\nfunction applyColorReplacements(color, replacements) {\n if (!color)\n return color;\n return replacements?.[color?.toLowerCase()] || color;\n}\nfunction getTokenStyleObject(token) {\n const styles = {};\n if (token.color)\n styles.color = token.color;\n if (token.bgColor)\n styles[\"background-color\"] = token.bgColor;\n if (token.fontStyle) {\n if (token.fontStyle & FontStyle.Italic)\n styles[\"font-style\"] = \"italic\";\n if (token.fontStyle & FontStyle.Bold)\n styles[\"font-weight\"] = \"bold\";\n if (token.fontStyle & FontStyle.Underline)\n styles[\"text-decoration\"] = \"underline\";\n }\n return styles;\n}\nfunction stringifyTokenStyle(token) {\n if (typeof token === \"string\")\n return token;\n return Object.entries(token).map(([key, value]) => `${key}:${value}`).join(\";\");\n}\nfunction createPositionConverter(code) {\n const lines = splitLines(code, true).map(([line]) => line);\n function indexToPos(index) {\n if (index === code.length) {\n return {\n line: lines.length - 1,\n character: lines[lines.length - 1].length\n };\n }\n let character = index;\n let line = 0;\n for (const lineText of lines) {\n if (character < lineText.length)\n break;\n character -= lineText.length;\n line++;\n }\n return { line, character };\n }\n function posToIndex(line, character) {\n let index = 0;\n for (let i = 0; i < line; i++)\n index += lines[i].length;\n index += character;\n return index;\n }\n return {\n lines,\n indexToPos,\n posToIndex\n };\n}\n\nclass ShikiError extends Error {\n constructor(message) {\n super(message);\n this.name = \"ShikiError\";\n }\n}\n\nvar __defProp$2 = Object.defineProperty;\nvar __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField$2 = (obj, key, value) => {\n __defNormalProp$2(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nconst _grammarStateMap = /* @__PURE__ */ new WeakMap();\nfunction setLastGrammarStateToMap(keys, state) {\n _grammarStateMap.set(keys, state);\n}\nfunction getLastGrammarStateFromMap(keys) {\n return _grammarStateMap.get(keys);\n}\nclass GrammarState {\n constructor(...args) {\n /**\n * Theme to Stack mapping\n */\n __publicField$2(this, \"_stacks\", {});\n __publicField$2(this, \"lang\");\n if (args.length === 2) {\n const [stacksMap, lang] = args;\n this.lang = lang;\n this._stacks = stacksMap;\n } else {\n const [stack, lang, theme] = args;\n this.lang = lang;\n this._stacks = { [theme]: stack };\n }\n }\n get themes() {\n return Object.keys(this._stacks);\n }\n get theme() {\n return this.themes[0];\n }\n get _stack() {\n return this._stacks[this.theme];\n }\n /**\n * Static method to create a initial grammar state.\n */\n static initial(lang, themes) {\n return new GrammarState(\n Object.fromEntries(toArray(themes).map((theme) => [theme, INITIAL])),\n lang\n );\n }\n /**\n * Get the internal stack object.\n * @internal\n */\n getInternalStack(theme = this.theme) {\n return this._stacks[theme];\n }\n /**\n * @deprecated use `getScopes` instead\n */\n get scopes() {\n return getScopes(this._stacks[this.theme]);\n }\n getScopes(theme = this.theme) {\n return getScopes(this._stacks[theme]);\n }\n toJSON() {\n return {\n lang: this.lang,\n theme: this.theme,\n themes: this.themes,\n scopes: this.scopes\n };\n }\n}\nfunction getScopes(stack) {\n const scopes = [];\n const visited = /* @__PURE__ */ new Set();\n function pushScope(stack2) {\n if (visited.has(stack2))\n return;\n visited.add(stack2);\n const name = stack2?.nameScopesList?.scopeName;\n if (name)\n scopes.push(name);\n if (stack2.parent)\n pushScope(stack2.parent);\n }\n pushScope(stack);\n return scopes;\n}\nfunction getGrammarStack(state, theme) {\n if (!(state instanceof GrammarState))\n throw new ShikiError(\"Invalid grammar state\");\n return state.getInternalStack(theme);\n}\n\nfunction transformerDecorations() {\n const map = /* @__PURE__ */ new WeakMap();\n function getContext(shiki) {\n if (!map.has(shiki.meta)) {\n let normalizePosition = function(p) {\n if (typeof p === \"number\") {\n if (p < 0 || p > shiki.source.length)\n throw new ShikiError(`Invalid decoration offset: ${p}. Code length: ${shiki.source.length}`);\n return {\n ...converter.indexToPos(p),\n offset: p\n };\n } else {\n const line = converter.lines[p.line];\n if (line === void 0)\n throw new ShikiError(`Invalid decoration position ${JSON.stringify(p)}. Lines length: ${converter.lines.length}`);\n if (p.character < 0 || p.character > line.length)\n throw new ShikiError(`Invalid decoration position ${JSON.stringify(p)}. Line ${p.line} length: ${line.length}`);\n return {\n ...p,\n offset: converter.posToIndex(p.line, p.character)\n };\n }\n };\n const converter = createPositionConverter(shiki.source);\n const decorations = (shiki.options.decorations || []).map((d) => ({\n ...d,\n start: normalizePosition(d.start),\n end: normalizePosition(d.end)\n }));\n verifyIntersections(decorations);\n map.set(shiki.meta, {\n decorations,\n converter,\n source: shiki.source\n });\n }\n return map.get(shiki.meta);\n }\n return {\n name: \"shiki:decorations\",\n tokens(tokens) {\n if (!this.options.decorations?.length)\n return;\n const ctx = getContext(this);\n const breakpoints = ctx.decorations.flatMap((d) => [d.start.offset, d.end.offset]);\n const splitted = splitTokens(tokens, breakpoints);\n return splitted;\n },\n code(codeEl) {\n if (!this.options.decorations?.length)\n return;\n const ctx = getContext(this);\n const lines = Array.from(codeEl.children).filter((i) => i.type === \"element\" && i.tagName === \"span\");\n if (lines.length !== ctx.converter.lines.length)\n throw new ShikiError(`Number of lines in code element (${lines.length}) does not match the number of lines in the source (${ctx.converter.lines.length}). Failed to apply decorations.`);\n function applyLineSection(line, start, end, decoration) {\n const lineEl = lines[line];\n let text = \"\";\n let startIndex = -1;\n let endIndex = -1;\n if (start === 0)\n startIndex = 0;\n if (end === 0)\n endIndex = 0;\n if (end === Number.POSITIVE_INFINITY)\n endIndex = lineEl.children.length;\n if (startIndex === -1 || endIndex === -1) {\n for (let i = 0; i < lineEl.children.length; i++) {\n text += stringify(lineEl.children[i]);\n if (startIndex === -1 && text.length === start)\n startIndex = i + 1;\n if (endIndex === -1 && text.length === end)\n endIndex = i + 1;\n }\n }\n if (startIndex === -1)\n throw new ShikiError(`Failed to find start index for decoration ${JSON.stringify(decoration.start)}`);\n if (endIndex === -1)\n throw new ShikiError(`Failed to find end index for decoration ${JSON.stringify(decoration.end)}`);\n const children = lineEl.children.slice(startIndex, endIndex);\n if (!decoration.alwaysWrap && children.length === lineEl.children.length) {\n applyDecoration(lineEl, decoration, \"line\");\n } else if (!decoration.alwaysWrap && children.length === 1 && children[0].type === \"element\") {\n applyDecoration(children[0], decoration, \"token\");\n } else {\n const wrapper = {\n type: \"element\",\n tagName: \"span\",\n properties: {},\n children\n };\n applyDecoration(wrapper, decoration, \"wrapper\");\n lineEl.children.splice(startIndex, children.length, wrapper);\n }\n }\n function applyLine(line, decoration) {\n lines[line] = applyDecoration(lines[line], decoration, \"line\");\n }\n function applyDecoration(el, decoration, type) {\n const properties = decoration.properties || {};\n const transform = decoration.transform || ((i) => i);\n el.tagName = decoration.tagName || \"span\";\n el.properties = {\n ...el.properties,\n ...properties,\n class: el.properties.class\n };\n if (decoration.properties?.class)\n addClassToHast(el, decoration.properties.class);\n el = transform(el, type) || el;\n return el;\n }\n const lineApplies = [];\n const sorted = ctx.decorations.sort((a, b) => b.start.offset - a.start.offset);\n for (const decoration of sorted) {\n const { start, end } = decoration;\n if (start.line === end.line) {\n applyLineSection(start.line, start.character, end.character, decoration);\n } else if (start.line < end.line) {\n applyLineSection(start.line, start.character, Number.POSITIVE_INFINITY, decoration);\n for (let i = start.line + 1; i < end.line; i++)\n lineApplies.unshift(() => applyLine(i, decoration));\n applyLineSection(end.line, 0, end.character, decoration);\n }\n }\n lineApplies.forEach((i) => i());\n }\n };\n}\nfunction verifyIntersections(items) {\n for (let i = 0; i < items.length; i++) {\n const foo = items[i];\n if (foo.start.offset > foo.end.offset)\n throw new ShikiError(`Invalid decoration range: ${JSON.stringify(foo.start)} - ${JSON.stringify(foo.end)}`);\n for (let j = i + 1; j < items.length; j++) {\n const bar = items[j];\n const isFooHasBarStart = foo.start.offset < bar.start.offset && bar.start.offset < foo.end.offset;\n const isFooHasBarEnd = foo.start.offset < bar.end.offset && bar.end.offset < foo.end.offset;\n const isBarHasFooStart = bar.start.offset < foo.start.offset && foo.start.offset < bar.end.offset;\n const isBarHasFooEnd = bar.start.offset < foo.end.offset && foo.end.offset < bar.end.offset;\n if (isFooHasBarStart || isFooHasBarEnd || isBarHasFooStart || isBarHasFooEnd) {\n if (isFooHasBarEnd && isFooHasBarEnd)\n continue;\n if (isBarHasFooStart && isBarHasFooEnd)\n continue;\n throw new ShikiError(`Decorations ${JSON.stringify(foo.start)} and ${JSON.stringify(bar.start)} intersect.`);\n }\n }\n }\n}\nfunction stringify(el) {\n if (el.type === \"text\")\n return el.value;\n if (el.type === \"element\")\n return el.children.map(stringify).join(\"\");\n return \"\";\n}\n\nconst builtInTransformers = [\n /* @__PURE__ */ transformerDecorations()\n];\nfunction getTransformers(options) {\n return [\n ...options.transformers || [],\n ...builtInTransformers\n ];\n}\n\n// src/colors.ts\nvar namedColors = [\n \"black\",\n \"red\",\n \"green\",\n \"yellow\",\n \"blue\",\n \"magenta\",\n \"cyan\",\n \"white\",\n \"brightBlack\",\n \"brightRed\",\n \"brightGreen\",\n \"brightYellow\",\n \"brightBlue\",\n \"brightMagenta\",\n \"brightCyan\",\n \"brightWhite\"\n];\n\n// src/decorations.ts\nvar decorations = {\n 1: \"bold\",\n 2: \"dim\",\n 3: \"italic\",\n 4: \"underline\",\n 7: \"reverse\",\n 9: \"strikethrough\"\n};\n\n// src/parser.ts\nfunction findSequence(value, position) {\n const nextEscape = value.indexOf(\"\\x1B[\", position);\n if (nextEscape !== -1) {\n const nextClose = value.indexOf(\"m\", nextEscape);\n return {\n sequence: value.substring(nextEscape + 2, nextClose).split(\";\"),\n startPosition: nextEscape,\n position: nextClose + 1\n };\n }\n return {\n position: value.length\n };\n}\nfunction parseColor(sequence, index) {\n let offset = 1;\n const colorMode = sequence[index + offset++];\n let color;\n if (colorMode === \"2\") {\n const rgb = [\n sequence[index + offset++],\n sequence[index + offset++],\n sequence[index + offset]\n ].map((x) => Number.parseInt(x));\n if (rgb.length === 3 && !rgb.some((x) => Number.isNaN(x))) {\n color = {\n type: \"rgb\",\n rgb\n };\n }\n } else if (colorMode === \"5\") {\n const colorIndex = Number.parseInt(sequence[index + offset]);\n if (!Number.isNaN(colorIndex)) {\n color = { type: \"table\", index: Number(colorIndex) };\n }\n }\n return [offset, color];\n}\nfunction parseSequence(sequence) {\n const commands = [];\n for (let i = 0; i < sequence.length; i++) {\n const code = sequence[i];\n const codeInt = Number.parseInt(code);\n if (Number.isNaN(codeInt))\n continue;\n if (codeInt === 0) {\n commands.push({ type: \"resetAll\" });\n } else if (codeInt <= 9) {\n const decoration = decorations[codeInt];\n if (decoration) {\n commands.push({\n type: \"setDecoration\",\n value: decorations[codeInt]\n });\n }\n } else if (codeInt <= 29) {\n const decoration = decorations[codeInt - 20];\n if (decoration) {\n commands.push({\n type: \"resetDecoration\",\n value: decoration\n });\n }\n } else if (codeInt <= 37) {\n commands.push({\n type: \"setForegroundColor\",\n value: { type: \"named\", name: namedColors[codeInt - 30] }\n });\n } else if (codeInt === 38) {\n const [offset, color] = parseColor(sequence, i);\n if (color) {\n commands.push({\n type: \"setForegroundColor\",\n value: color\n });\n }\n i += offset;\n } else if (codeInt === 39) {\n commands.push({\n type: \"resetForegroundColor\"\n });\n } else if (codeInt <= 47) {\n commands.push({\n type: \"setBackgroundColor\",\n value: { type: \"named\", name: namedColors[codeInt - 40] }\n });\n } else if (codeInt === 48) {\n const [offset, color] = parseColor(sequence, i);\n if (color) {\n commands.push({\n type: \"setBackgroundColor\",\n value: color\n });\n }\n i += offset;\n } else if (codeInt === 49) {\n commands.push({\n type: \"resetBackgroundColor\"\n });\n } else if (codeInt >= 90 && codeInt <= 97) {\n commands.push({\n type: \"setForegroundColor\",\n value: { type: \"named\", name: namedColors[codeInt - 90 + 8] }\n });\n } else if (codeInt >= 100 && codeInt <= 107) {\n commands.push({\n type: \"setBackgroundColor\",\n value: { type: \"named\", name: namedColors[codeInt - 100 + 8] }\n });\n }\n }\n return commands;\n}\nfunction createAnsiSequenceParser() {\n let foreground = null;\n let background = null;\n let decorations2 = /* @__PURE__ */ new Set();\n return {\n parse(value) {\n const tokens = [];\n let position = 0;\n do {\n const findResult = findSequence(value, position);\n const text = findResult.sequence ? value.substring(position, findResult.startPosition) : value.substring(position);\n if (text.length > 0) {\n tokens.push({\n value: text,\n foreground,\n background,\n decorations: new Set(decorations2)\n });\n }\n if (findResult.sequence) {\n const commands = parseSequence(findResult.sequence);\n for (const styleToken of commands) {\n if (styleToken.type === \"resetAll\") {\n foreground = null;\n background = null;\n decorations2.clear();\n } else if (styleToken.type === \"resetForegroundColor\") {\n foreground = null;\n } else if (styleToken.type === \"resetBackgroundColor\") {\n background = null;\n } else if (styleToken.type === \"resetDecoration\") {\n decorations2.delete(styleToken.value);\n }\n }\n for (const styleToken of commands) {\n if (styleToken.type === \"setForegroundColor\") {\n foreground = styleToken.value;\n } else if (styleToken.type === \"setBackgroundColor\") {\n background = styleToken.value;\n } else if (styleToken.type === \"setDecoration\") {\n decorations2.add(styleToken.value);\n }\n }\n }\n position = findResult.position;\n } while (position < value.length);\n return tokens;\n }\n };\n}\n\n// src/palette.ts\nvar defaultNamedColorsMap = {\n black: \"#000000\",\n red: \"#bb0000\",\n green: \"#00bb00\",\n yellow: \"#bbbb00\",\n blue: \"#0000bb\",\n magenta: \"#ff00ff\",\n cyan: \"#00bbbb\",\n white: \"#eeeeee\",\n brightBlack: \"#555555\",\n brightRed: \"#ff5555\",\n brightGreen: \"#00ff00\",\n brightYellow: \"#ffff55\",\n brightBlue: \"#5555ff\",\n brightMagenta: \"#ff55ff\",\n brightCyan: \"#55ffff\",\n brightWhite: \"#ffffff\"\n};\nfunction createColorPalette(namedColorsMap = defaultNamedColorsMap) {\n function namedColor(name) {\n return namedColorsMap[name];\n }\n function rgbColor(rgb) {\n return `#${rgb.map((x) => Math.max(0, Math.min(x, 255)).toString(16).padStart(2, \"0\")).join(\"\")}`;\n }\n let colorTable;\n function getColorTable() {\n if (colorTable) {\n return colorTable;\n }\n colorTable = [];\n for (let i = 0; i < namedColors.length; i++) {\n colorTable.push(namedColor(namedColors[i]));\n }\n let levels = [0, 95, 135, 175, 215, 255];\n for (let r = 0; r < 6; r++) {\n for (let g = 0; g < 6; g++) {\n for (let b = 0; b < 6; b++) {\n colorTable.push(rgbColor([levels[r], levels[g], levels[b]]));\n }\n }\n }\n let level = 8;\n for (let i = 0; i < 24; i++, level += 10) {\n colorTable.push(rgbColor([level, level, level]));\n }\n return colorTable;\n }\n function tableColor(index) {\n return getColorTable()[index];\n }\n function value(color) {\n switch (color.type) {\n case \"named\":\n return namedColor(color.name);\n case \"rgb\":\n return rgbColor(color.rgb);\n case \"table\":\n return tableColor(color.index);\n }\n }\n return {\n value\n };\n}\n\nfunction tokenizeAnsiWithTheme(theme, fileContents, options) {\n const colorReplacements = resolveColorReplacements(theme, options);\n const lines = splitLines(fileContents);\n const colorPalette = createColorPalette(\n Object.fromEntries(\n namedColors.map((name) => [\n name,\n theme.colors?.[`terminal.ansi${name[0].toUpperCase()}${name.substring(1)}`]\n ])\n )\n );\n const parser = createAnsiSequenceParser();\n return lines.map(\n (line) => parser.parse(line[0]).map((token) => {\n let color;\n let bgColor;\n if (token.decorations.has(\"reverse\")) {\n color = token.background ? colorPalette.value(token.background) : theme.bg;\n bgColor = token.foreground ? colorPalette.value(token.foreground) : theme.fg;\n } else {\n color = token.foreground ? colorPalette.value(token.foreground) : theme.fg;\n bgColor = token.background ? colorPalette.value(token.background) : void 0;\n }\n color = applyColorReplacements(color, colorReplacements);\n bgColor = applyColorReplacements(bgColor, colorReplacements);\n if (token.decorations.has(\"dim\"))\n color = dimColor(color);\n let fontStyle = FontStyle.None;\n if (token.decorations.has(\"bold\"))\n fontStyle |= FontStyle.Bold;\n if (token.decorations.has(\"italic\"))\n fontStyle |= FontStyle.Italic;\n if (token.decorations.has(\"underline\"))\n fontStyle |= FontStyle.Underline;\n return {\n content: token.value,\n offset: line[1],\n // TODO: more accurate offset? might need to fork ansi-sequence-parser\n color,\n bgColor,\n fontStyle\n };\n })\n );\n}\nfunction dimColor(color) {\n const hexMatch = color.match(/#([0-9a-f]{3})([0-9a-f]{3})?([0-9a-f]{2})?/);\n if (hexMatch) {\n if (hexMatch[3]) {\n const alpha = Math.round(Number.parseInt(hexMatch[3], 16) / 2).toString(16).padStart(2, \"0\");\n return `#${hexMatch[1]}${hexMatch[2]}${alpha}`;\n } else if (hexMatch[2]) {\n return `#${hexMatch[1]}${hexMatch[2]}80`;\n } else {\n return `#${Array.from(hexMatch[1]).map((x) => `${x}${x}`).join(\"\")}80`;\n }\n }\n const cssVarMatch = color.match(/var\\((--[\\w-]+-ansi-[\\w-]+)\\)/);\n if (cssVarMatch)\n return `var(${cssVarMatch[1]}-dim)`;\n return color;\n}\n\nfunction codeToTokensBase(internal, code, options = {}) {\n const {\n lang = \"text\",\n theme: themeName = internal.getLoadedThemes()[0]\n } = options;\n if (isPlainLang(lang) || isNoneTheme(themeName))\n return splitLines(code).map((line) => [{ content: line[0], offset: line[1] }]);\n const { theme, colorMap } = internal.setTheme(themeName);\n if (lang === \"ansi\")\n return tokenizeAnsiWithTheme(theme, code, options);\n const _grammar = internal.getLanguage(lang);\n if (options.grammarState) {\n if (options.grammarState.lang !== _grammar.name) {\n throw new ShikiError$1(`Grammar state language \"${options.grammarState.lang}\" does not match highlight language \"${_grammar.name}\"`);\n }\n if (!options.grammarState.themes.includes(theme.name)) {\n throw new ShikiError$1(`Grammar state themes \"${options.grammarState.themes}\" do not contain highlight theme \"${theme.name}\"`);\n }\n }\n return tokenizeWithTheme(code, _grammar, theme, colorMap, options);\n}\nfunction getLastGrammarState(...args) {\n if (args.length === 2) {\n return getLastGrammarStateFromMap(args[1]);\n }\n const [internal, code, options = {}] = args;\n const {\n lang = \"text\",\n theme: themeName = internal.getLoadedThemes()[0]\n } = options;\n if (isPlainLang(lang) || isNoneTheme(themeName))\n throw new ShikiError$1(\"Plain language does not have grammar state\");\n if (lang === \"ansi\")\n throw new ShikiError$1(\"ANSI language does not have grammar state\");\n const { theme, colorMap } = internal.setTheme(themeName);\n const _grammar = internal.getLanguage(lang);\n return new GrammarState(\n _tokenizeWithTheme(code, _grammar, theme, colorMap, options).stateStack,\n _grammar.name,\n theme.name\n );\n}\nfunction tokenizeWithTheme(code, grammar, theme, colorMap, options) {\n const result = _tokenizeWithTheme(code, grammar, theme, colorMap, options);\n const grammarState = new GrammarState(\n _tokenizeWithTheme(code, grammar, theme, colorMap, options).stateStack,\n grammar.name,\n theme.name\n );\n setLastGrammarStateToMap(result.tokens, grammarState);\n return result.tokens;\n}\nfunction _tokenizeWithTheme(code, grammar, theme, colorMap, options) {\n const colorReplacements = resolveColorReplacements(theme, options);\n const {\n tokenizeMaxLineLength = 0,\n tokenizeTimeLimit = 500\n } = options;\n const lines = splitLines(code);\n let stateStack = options.grammarState ? getGrammarStack(options.grammarState, theme.name) ?? INITIAL : options.grammarContextCode != null ? _tokenizeWithTheme(\n options.grammarContextCode,\n grammar,\n theme,\n colorMap,\n {\n ...options,\n grammarState: void 0,\n grammarContextCode: void 0\n }\n ).stateStack : INITIAL;\n let actual = [];\n const final = [];\n for (let i = 0, len = lines.length; i < len; i++) {\n const [line, lineOffset] = lines[i];\n if (line === \"\") {\n actual = [];\n final.push([]);\n continue;\n }\n if (tokenizeMaxLineLength > 0 && line.length >= tokenizeMaxLineLength) {\n actual = [];\n final.push([{\n content: line,\n offset: lineOffset,\n color: \"\",\n fontStyle: 0\n }]);\n continue;\n }\n let resultWithScopes;\n let tokensWithScopes;\n let tokensWithScopesIndex;\n if (options.includeExplanation) {\n resultWithScopes = grammar.tokenizeLine(line, stateStack);\n tokensWithScopes = resultWithScopes.tokens;\n tokensWithScopesIndex = 0;\n }\n const result = grammar.tokenizeLine2(line, stateStack, tokenizeTimeLimit);\n const tokensLength = result.tokens.length / 2;\n for (let j = 0; j < tokensLength; j++) {\n const startIndex = result.tokens[2 * j];\n const nextStartIndex = j + 1 < tokensLength ? result.tokens[2 * j + 2] : line.length;\n if (startIndex === nextStartIndex)\n continue;\n const metadata = result.tokens[2 * j + 1];\n const color = applyColorReplacements(\n colorMap[EncodedTokenMetadata.getForeground(metadata)],\n colorReplacements\n );\n const fontStyle = EncodedTokenMetadata.getFontStyle(metadata);\n const token = {\n content: line.substring(startIndex, nextStartIndex),\n offset: lineOffset + startIndex,\n color,\n fontStyle\n };\n if (options.includeExplanation) {\n const themeSettingsSelectors = [];\n if (options.includeExplanation !== \"scopeName\") {\n for (const setting of theme.settings) {\n let selectors;\n switch (typeof setting.scope) {\n case \"string\":\n selectors = setting.scope.split(/,/).map((scope) => scope.trim());\n break;\n case \"object\":\n selectors = setting.scope;\n break;\n default:\n continue;\n }\n themeSettingsSelectors.push({\n settings: setting,\n selectors: selectors.map((selector) => selector.split(/ /))\n });\n }\n }\n token.explanation = [];\n let offset = 0;\n while (startIndex + offset < nextStartIndex) {\n const tokenWithScopes = tokensWithScopes[tokensWithScopesIndex];\n const tokenWithScopesText = line.substring(\n tokenWithScopes.startIndex,\n tokenWithScopes.endIndex\n );\n offset += tokenWithScopesText.length;\n token.explanation.push({\n content: tokenWithScopesText,\n scopes: options.includeExplanation === \"scopeName\" ? explainThemeScopesNameOnly(\n tokenWithScopes.scopes\n ) : explainThemeScopesFull(\n themeSettingsSelectors,\n tokenWithScopes.scopes\n )\n });\n tokensWithScopesIndex += 1;\n }\n }\n actual.push(token);\n }\n final.push(actual);\n actual = [];\n stateStack = result.ruleStack;\n }\n return {\n tokens: final,\n stateStack\n };\n}\nfunction explainThemeScopesNameOnly(scopes) {\n return scopes.map((scope) => ({ scopeName: scope }));\n}\nfunction explainThemeScopesFull(themeSelectors, scopes) {\n const result = [];\n for (let i = 0, len = scopes.length; i < len; i++) {\n const scope = scopes[i];\n result[i] = {\n scopeName: scope,\n themeMatches: explainThemeScope(themeSelectors, scope, scopes.slice(0, i))\n };\n }\n return result;\n}\nfunction matchesOne(selector, scope) {\n return selector === scope || scope.substring(0, selector.length) === selector && scope[selector.length] === \".\";\n}\nfunction matches(selectors, scope, parentScopes) {\n if (!matchesOne(selectors[selectors.length - 1], scope))\n return false;\n let selectorParentIndex = selectors.length - 2;\n let parentIndex = parentScopes.length - 1;\n while (selectorParentIndex >= 0 && parentIndex >= 0) {\n if (matchesOne(selectors[selectorParentIndex], parentScopes[parentIndex]))\n selectorParentIndex -= 1;\n parentIndex -= 1;\n }\n if (selectorParentIndex === -1)\n return true;\n return false;\n}\nfunction explainThemeScope(themeSettingsSelectors, scope, parentScopes) {\n const result = [];\n for (const { selectors, settings } of themeSettingsSelectors) {\n for (const selectorPieces of selectors) {\n if (matches(selectorPieces, scope, parentScopes)) {\n result.push(settings);\n break;\n }\n }\n }\n return result;\n}\n\nfunction codeToTokensWithThemes(internal, code, options) {\n const themes = Object.entries(options.themes).filter((i) => i[1]).map((i) => ({ color: i[0], theme: i[1] }));\n const themedTokens = themes.map((t) => {\n const tokens2 = codeToTokensBase(internal, code, {\n ...options,\n theme: t.theme\n });\n const state = getLastGrammarStateFromMap(tokens2);\n const theme = typeof t.theme === \"string\" ? t.theme : t.theme.name;\n return {\n tokens: tokens2,\n state,\n theme\n };\n });\n const tokens = syncThemesTokenization(\n ...themedTokens.map((i) => i.tokens)\n );\n const mergedTokens = tokens[0].map(\n (line, lineIdx) => line.map((_token, tokenIdx) => {\n const mergedToken = {\n content: _token.content,\n variants: {},\n offset: _token.offset\n };\n if (\"includeExplanation\" in options && options.includeExplanation) {\n mergedToken.explanation = _token.explanation;\n }\n tokens.forEach((t, themeIdx) => {\n const {\n content: _,\n explanation: __,\n offset: ___,\n ...styles\n } = t[lineIdx][tokenIdx];\n mergedToken.variants[themes[themeIdx].color] = styles;\n });\n return mergedToken;\n })\n );\n const mergedGrammarState = themedTokens[0].state ? new GrammarState(\n Object.fromEntries(themedTokens.map((s) => [s.theme, s.state?.getInternalStack(s.theme)])),\n themedTokens[0].state.lang\n ) : void 0;\n if (mergedGrammarState)\n setLastGrammarStateToMap(mergedTokens, mergedGrammarState);\n return mergedTokens;\n}\nfunction syncThemesTokenization(...themes) {\n const outThemes = themes.map(() => []);\n const count = themes.length;\n for (let i = 0; i < themes[0].length; i++) {\n const lines = themes.map((t) => t[i]);\n const outLines = outThemes.map(() => []);\n outThemes.forEach((t, i2) => t.push(outLines[i2]));\n const indexes = lines.map(() => 0);\n const current = lines.map((l) => l[0]);\n while (current.every((t) => t)) {\n const minLength = Math.min(...current.map((t) => t.content.length));\n for (let n = 0; n < count; n++) {\n const token = current[n];\n if (token.content.length === minLength) {\n outLines[n].push(token);\n indexes[n] += 1;\n current[n] = lines[n][indexes[n]];\n } else {\n outLines[n].push({\n ...token,\n content: token.content.slice(0, minLength)\n });\n current[n] = {\n ...token,\n content: token.content.slice(minLength),\n offset: token.offset + minLength\n };\n }\n }\n }\n }\n return outThemes;\n}\n\nfunction codeToTokens(internal, code, options) {\n let bg;\n let fg;\n let tokens;\n let themeName;\n let rootStyle;\n let grammarState;\n if (\"themes\" in options) {\n const {\n defaultColor = \"light\",\n cssVariablePrefix = \"--shiki-\"\n } = options;\n const themes = Object.entries(options.themes).filter((i) => i[1]).map((i) => ({ color: i[0], theme: i[1] })).sort((a, b) => a.color === defaultColor ? -1 : b.color === defaultColor ? 1 : 0);\n if (themes.length === 0)\n throw new ShikiError$1(\"`themes` option must not be empty\");\n const themeTokens = codeToTokensWithThemes(\n internal,\n code,\n options\n );\n grammarState = getLastGrammarStateFromMap(themeTokens);\n if (defaultColor && !themes.find((t) => t.color === defaultColor))\n throw new ShikiError$1(`\\`themes\\` option must contain the defaultColor key \\`${defaultColor}\\``);\n const themeRegs = themes.map((t) => internal.getTheme(t.theme));\n const themesOrder = themes.map((t) => t.color);\n tokens = themeTokens.map((line) => line.map((token) => mergeToken(token, themesOrder, cssVariablePrefix, defaultColor)));\n if (grammarState)\n setLastGrammarStateToMap(tokens, grammarState);\n const themeColorReplacements = themes.map((t) => resolveColorReplacements(t.theme, options));\n fg = themes.map((t, idx) => (idx === 0 && defaultColor ? \"\" : `${cssVariablePrefix + t.color}:`) + (applyColorReplacements(themeRegs[idx].fg, themeColorReplacements[idx]) || \"inherit\")).join(\";\");\n bg = themes.map((t, idx) => (idx === 0 && defaultColor ? \"\" : `${cssVariablePrefix + t.color}-bg:`) + (applyColorReplacements(themeRegs[idx].bg, themeColorReplacements[idx]) || \"inherit\")).join(\";\");\n themeName = `shiki-themes ${themeRegs.map((t) => t.name).join(\" \")}`;\n rootStyle = defaultColor ? void 0 : [fg, bg].join(\";\");\n } else if (\"theme\" in options) {\n const colorReplacements = resolveColorReplacements(options.theme, options);\n tokens = codeToTokensBase(\n internal,\n code,\n options\n );\n const _theme = internal.getTheme(options.theme);\n bg = applyColorReplacements(_theme.bg, colorReplacements);\n fg = applyColorReplacements(_theme.fg, colorReplacements);\n themeName = _theme.name;\n grammarState = getLastGrammarStateFromMap(tokens);\n } else {\n throw new ShikiError$1(\"Invalid options, either `theme` or `themes` must be provided\");\n }\n return {\n tokens,\n fg,\n bg,\n themeName,\n rootStyle,\n grammarState\n };\n}\nfunction mergeToken(merged, variantsOrder, cssVariablePrefix, defaultColor) {\n const token = {\n content: merged.content,\n explanation: merged.explanation,\n offset: merged.offset\n };\n const styles = variantsOrder.map((t) => getTokenStyleObject(merged.variants[t]));\n const styleKeys = new Set(styles.flatMap((t) => Object.keys(t)));\n const mergedStyles = {};\n styles.forEach((cur, idx) => {\n for (const key of styleKeys) {\n const value = cur[key] || \"inherit\";\n if (idx === 0 && defaultColor) {\n mergedStyles[key] = value;\n } else {\n const keyName = key === \"color\" ? \"\" : key === \"background-color\" ? \"-bg\" : `-${key}`;\n const varKey = cssVariablePrefix + variantsOrder[idx] + (key === \"color\" ? \"\" : keyName);\n mergedStyles[varKey] = value;\n }\n }\n });\n token.htmlStyle = mergedStyles;\n return token;\n}\n\nfunction codeToHast(internal, code, options, transformerContext = {\n meta: {},\n options,\n codeToHast: (_code, _options) => codeToHast(internal, _code, _options),\n codeToTokens: (_code, _options) => codeToTokens(internal, _code, _options)\n}) {\n let input = code;\n for (const transformer of getTransformers(options))\n input = transformer.preprocess?.call(transformerContext, input, options) || input;\n let {\n tokens,\n fg,\n bg,\n themeName,\n rootStyle,\n grammarState\n } = codeToTokens(internal, input, options);\n const {\n mergeWhitespaces = true\n } = options;\n if (mergeWhitespaces === true)\n tokens = mergeWhitespaceTokens(tokens);\n else if (mergeWhitespaces === \"never\")\n tokens = splitWhitespaceTokens(tokens);\n const contextSource = {\n ...transformerContext,\n get source() {\n return input;\n }\n };\n for (const transformer of getTransformers(options))\n tokens = transformer.tokens?.call(contextSource, tokens) || tokens;\n return tokensToHast(\n tokens,\n {\n ...options,\n fg,\n bg,\n themeName,\n rootStyle\n },\n contextSource,\n grammarState\n );\n}\nfunction tokensToHast(tokens, options, transformerContext, grammarState = getLastGrammarStateFromMap(tokens)) {\n const transformers = getTransformers(options);\n const lines = [];\n const root = {\n type: \"root\",\n children: []\n };\n const {\n structure = \"classic\",\n tabindex = \"0\"\n } = options;\n let preNode = {\n type: \"element\",\n tagName: \"pre\",\n properties: {\n class: `shiki ${options.themeName || \"\"}`,\n style: options.rootStyle || `background-color:${options.bg};color:${options.fg}`,\n ...tabindex !== false && tabindex != null ? {\n tabindex: tabindex.toString()\n } : {},\n ...Object.fromEntries(\n Array.from(\n Object.entries(options.meta || {})\n ).filter(([key]) => !key.startsWith(\"_\"))\n )\n },\n children: []\n };\n let codeNode = {\n type: \"element\",\n tagName: \"code\",\n properties: {},\n children: lines\n };\n const lineNodes = [];\n const context = {\n ...transformerContext,\n structure,\n addClassToHast,\n get source() {\n return transformerContext.source;\n },\n get tokens() {\n return tokens;\n },\n get options() {\n return options;\n },\n get root() {\n return root;\n },\n get pre() {\n return preNode;\n },\n get code() {\n return codeNode;\n },\n get lines() {\n return lineNodes;\n }\n };\n tokens.forEach((line, idx) => {\n if (idx) {\n if (structure === \"inline\")\n root.children.push({ type: \"element\", tagName: \"br\", properties: {}, children: [] });\n else if (structure === \"classic\")\n lines.push({ type: \"text\", value: \"\\n\" });\n }\n let lineNode = {\n type: \"element\",\n tagName: \"span\",\n properties: { class: \"line\" },\n children: []\n };\n let col = 0;\n for (const token of line) {\n let tokenNode = {\n type: \"element\",\n tagName: \"span\",\n properties: {\n ...token.htmlAttrs\n },\n children: [{ type: \"text\", value: token.content }]\n };\n if (typeof token.htmlStyle === \"string\")\n warnDeprecated(\"`htmlStyle` as a string is deprecated. Use an object instead.\");\n const style = stringifyTokenStyle(token.htmlStyle || getTokenStyleObject(token));\n if (style)\n tokenNode.properties.style = style;\n for (const transformer of transformers)\n tokenNode = transformer?.span?.call(context, tokenNode, idx + 1, col, lineNode, token) || tokenNode;\n if (structure === \"inline\")\n root.children.push(tokenNode);\n else if (structure === \"classic\")\n lineNode.children.push(tokenNode);\n col += token.content.length;\n }\n if (structure === \"classic\") {\n for (const transformer of transformers)\n lineNode = transformer?.line?.call(context, lineNode, idx + 1) || lineNode;\n lineNodes.push(lineNode);\n lines.push(lineNode);\n }\n });\n if (structure === \"classic\") {\n for (const transformer of transformers)\n codeNode = transformer?.code?.call(context, codeNode) || codeNode;\n preNode.children.push(codeNode);\n for (const transformer of transformers)\n preNode = transformer?.pre?.call(context, preNode) || preNode;\n root.children.push(preNode);\n }\n let result = root;\n for (const transformer of transformers)\n result = transformer?.root?.call(context, result) || result;\n if (grammarState)\n setLastGrammarStateToMap(result, grammarState);\n return result;\n}\nfunction mergeWhitespaceTokens(tokens) {\n return tokens.map((line) => {\n const newLine = [];\n let carryOnContent = \"\";\n let firstOffset = 0;\n line.forEach((token, idx) => {\n const isUnderline = token.fontStyle && token.fontStyle & FontStyle.Underline;\n const couldMerge = !isUnderline;\n if (couldMerge && token.content.match(/^\\s+$/) && line[idx + 1]) {\n if (!firstOffset)\n firstOffset = token.offset;\n carryOnContent += token.content;\n } else {\n if (carryOnContent) {\n if (couldMerge) {\n newLine.push({\n ...token,\n offset: firstOffset,\n content: carryOnContent + token.content\n });\n } else {\n newLine.push(\n {\n content: carryOnContent,\n offset: firstOffset\n },\n token\n );\n }\n firstOffset = 0;\n carryOnContent = \"\";\n } else {\n newLine.push(token);\n }\n }\n });\n return newLine;\n });\n}\nfunction splitWhitespaceTokens(tokens) {\n return tokens.map((line) => {\n return line.flatMap((token) => {\n if (token.content.match(/^\\s+$/))\n return token;\n const match = token.content.match(/^(\\s*)(.*?)(\\s*)$/);\n if (!match)\n return token;\n const [, leading, content, trailing] = match;\n if (!leading && !trailing)\n return token;\n const expanded = [{\n ...token,\n offset: token.offset + leading.length,\n content\n }];\n if (leading) {\n expanded.unshift({\n content: leading,\n offset: token.offset\n });\n }\n if (trailing) {\n expanded.push({\n content: trailing,\n offset: token.offset + leading.length + content.length\n });\n }\n return expanded;\n });\n });\n}\n\nfunction codeToHtml(internal, code, options) {\n const context = {\n meta: {},\n options,\n codeToHast: (_code, _options) => codeToHast(internal, _code, _options),\n codeToTokens: (_code, _options) => codeToTokens(internal, _code, _options)\n };\n let result = toHtml(codeToHast(internal, code, options, context));\n for (const transformer of getTransformers(options))\n result = transformer.postprocess?.call(context, result, options) || result;\n return result;\n}\n\nconst VSCODE_FALLBACK_EDITOR_FG = { light: \"#333333\", dark: \"#bbbbbb\" };\nconst VSCODE_FALLBACK_EDITOR_BG = { light: \"#fffffe\", dark: \"#1e1e1e\" };\nconst RESOLVED_KEY = \"__shiki_resolved\";\nfunction normalizeTheme(rawTheme) {\n if (rawTheme?.[RESOLVED_KEY])\n return rawTheme;\n const theme = {\n ...rawTheme\n };\n if (theme.tokenColors && !theme.settings) {\n theme.settings = theme.tokenColors;\n delete theme.tokenColors;\n }\n theme.type || (theme.type = \"dark\");\n theme.colorReplacements = { ...theme.colorReplacements };\n theme.settings || (theme.settings = []);\n let { bg, fg } = theme;\n if (!bg || !fg) {\n const globalSetting = theme.settings ? theme.settings.find((s) => !s.name && !s.scope) : void 0;\n if (globalSetting?.settings?.foreground)\n fg = globalSetting.settings.foreground;\n if (globalSetting?.settings?.background)\n bg = globalSetting.settings.background;\n if (!fg && theme?.colors?.[\"editor.foreground\"])\n fg = theme.colors[\"editor.foreground\"];\n if (!bg && theme?.colors?.[\"editor.background\"])\n bg = theme.colors[\"editor.background\"];\n if (!fg)\n fg = theme.type === \"light\" ? VSCODE_FALLBACK_EDITOR_FG.light : VSCODE_FALLBACK_EDITOR_FG.dark;\n if (!bg)\n bg = theme.type === \"light\" ? VSCODE_FALLBACK_EDITOR_BG.light : VSCODE_FALLBACK_EDITOR_BG.dark;\n theme.fg = fg;\n theme.bg = bg;\n }\n if (!(theme.settings[0] && theme.settings[0].settings && !theme.settings[0].scope)) {\n theme.settings.unshift({\n settings: {\n foreground: theme.fg,\n background: theme.bg\n }\n });\n }\n let replacementCount = 0;\n const replacementMap = /* @__PURE__ */ new Map();\n function getReplacementColor(value) {\n if (replacementMap.has(value))\n return replacementMap.get(value);\n replacementCount += 1;\n const hex = `#${replacementCount.toString(16).padStart(8, \"0\").toLowerCase()}`;\n if (theme.colorReplacements?.[`#${hex}`])\n return getReplacementColor(value);\n replacementMap.set(value, hex);\n return hex;\n }\n theme.settings = theme.settings.map((setting) => {\n const replaceFg = setting.settings?.foreground && !setting.settings.foreground.startsWith(\"#\");\n const replaceBg = setting.settings?.background && !setting.settings.background.startsWith(\"#\");\n if (!replaceFg && !replaceBg)\n return setting;\n const clone = {\n ...setting,\n settings: {\n ...setting.settings\n }\n };\n if (replaceFg) {\n const replacement = getReplacementColor(setting.settings.foreground);\n theme.colorReplacements[replacement] = setting.settings.foreground;\n clone.settings.foreground = replacement;\n }\n if (replaceBg) {\n const replacement = getReplacementColor(setting.settings.background);\n theme.colorReplacements[replacement] = setting.settings.background;\n clone.settings.background = replacement;\n }\n return clone;\n });\n for (const key of Object.keys(theme.colors || {})) {\n if (key === \"editor.foreground\" || key === \"editor.background\" || key.startsWith(\"terminal.ansi\")) {\n if (!theme.colors[key]?.startsWith(\"#\")) {\n const replacement = getReplacementColor(theme.colors[key]);\n theme.colorReplacements[replacement] = theme.colors[key];\n theme.colors[key] = replacement;\n }\n }\n }\n Object.defineProperty(theme, RESOLVED_KEY, {\n enumerable: false,\n writable: false,\n value: true\n });\n return theme;\n}\n\nasync function resolveLangs(langs) {\n return Array.from(new Set((await Promise.all(\n langs.filter((l) => !isSpecialLang(l)).map(async (lang) => await normalizeGetter(lang).then((r) => Array.isArray(r) ? r : [r]))\n )).flat()));\n}\nasync function resolveThemes(themes) {\n const resolved = await Promise.all(\n themes.map(\n async (theme) => isSpecialTheme(theme) ? null : normalizeTheme(await normalizeGetter(theme))\n )\n );\n return resolved.filter((i) => !!i);\n}\n\nvar __defProp$1 = Object.defineProperty;\nvar __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField$1 = (obj, key, value) => {\n __defNormalProp$1(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nclass Registry extends Registry$1 {\n constructor(_resolver, _themes, _langs, _alias = {}) {\n super(_resolver);\n this._resolver = _resolver;\n this._themes = _themes;\n this._langs = _langs;\n this._alias = _alias;\n __publicField$1(this, \"_resolvedThemes\", /* @__PURE__ */ new Map());\n __publicField$1(this, \"_resolvedGrammars\", /* @__PURE__ */ new Map());\n __publicField$1(this, \"_langMap\", /* @__PURE__ */ new Map());\n __publicField$1(this, \"_langGraph\", /* @__PURE__ */ new Map());\n __publicField$1(this, \"_textmateThemeCache\", /* @__PURE__ */ new WeakMap());\n __publicField$1(this, \"_loadedThemesCache\", null);\n __publicField$1(this, \"_loadedLanguagesCache\", null);\n this._themes.map((t) => this.loadTheme(t));\n this.loadLanguages(this._langs);\n }\n getTheme(theme) {\n if (typeof theme === \"string\")\n return this._resolvedThemes.get(theme);\n else\n return this.loadTheme(theme);\n }\n loadTheme(theme) {\n const _theme = normalizeTheme(theme);\n if (_theme.name) {\n this._resolvedThemes.set(_theme.name, _theme);\n this._loadedThemesCache = null;\n }\n return _theme;\n }\n getLoadedThemes() {\n if (!this._loadedThemesCache)\n this._loadedThemesCache = [...this._resolvedThemes.keys()];\n return this._loadedThemesCache;\n }\n // Override and re-implement this method to cache the textmate themes as `TextMateTheme.createFromRawTheme`\n // is expensive. Themes can switch often especially for dual-theme support.\n //\n // The parent class also accepts `colorMap` as the second parameter, but since we don't use that,\n // we omit here so it's easier to cache the themes.\n setTheme(theme) {\n let textmateTheme = this._textmateThemeCache.get(theme);\n if (!textmateTheme) {\n textmateTheme = Theme.createFromRawTheme(theme);\n this._textmateThemeCache.set(theme, textmateTheme);\n }\n this._syncRegistry.setTheme(textmateTheme);\n }\n getGrammar(name) {\n if (this._alias[name]) {\n const resolved = /* @__PURE__ */ new Set([name]);\n while (this._alias[name]) {\n name = this._alias[name];\n if (resolved.has(name))\n throw new ShikiError(`Circular alias \\`${Array.from(resolved).join(\" -> \")} -> ${name}\\``);\n resolved.add(name);\n }\n }\n return this._resolvedGrammars.get(name);\n }\n loadLanguage(lang) {\n if (this.getGrammar(lang.name))\n return;\n const embeddedLazilyBy = new Set(\n [...this._langMap.values()].filter((i) => i.embeddedLangsLazy?.includes(lang.name))\n );\n this._resolver.addLanguage(lang);\n const grammarConfig = {\n balancedBracketSelectors: lang.balancedBracketSelectors || [\"*\"],\n unbalancedBracketSelectors: lang.unbalancedBracketSelectors || []\n };\n this._syncRegistry._rawGrammars.set(lang.scopeName, lang);\n const g = this.loadGrammarWithConfiguration(lang.scopeName, 1, grammarConfig);\n g.name = lang.name;\n this._resolvedGrammars.set(lang.name, g);\n if (lang.aliases) {\n lang.aliases.forEach((alias) => {\n this._alias[alias] = lang.name;\n });\n }\n this._loadedLanguagesCache = null;\n if (embeddedLazilyBy.size) {\n for (const e of embeddedLazilyBy) {\n this._resolvedGrammars.delete(e.name);\n this._loadedLanguagesCache = null;\n this._syncRegistry?._injectionGrammars?.delete(e.scopeName);\n this._syncRegistry?._grammars?.delete(e.scopeName);\n this.loadLanguage(this._langMap.get(e.name));\n }\n }\n }\n dispose() {\n super.dispose();\n this._resolvedThemes.clear();\n this._resolvedGrammars.clear();\n this._langMap.clear();\n this._langGraph.clear();\n this._loadedThemesCache = null;\n }\n loadLanguages(langs) {\n for (const lang of langs)\n this.resolveEmbeddedLanguages(lang);\n const langsGraphArray = Array.from(this._langGraph.entries());\n const missingLangs = langsGraphArray.filter(([_, lang]) => !lang);\n if (missingLangs.length) {\n const dependents = langsGraphArray.filter(([_, lang]) => lang && lang.embeddedLangs?.some((l) => missingLangs.map(([name]) => name).includes(l))).filter((lang) => !missingLangs.includes(lang));\n throw new ShikiError(`Missing languages ${missingLangs.map(([name]) => `\\`${name}\\``).join(\", \")}, required by ${dependents.map(([name]) => `\\`${name}\\``).join(\", \")}`);\n }\n for (const [_, lang] of langsGraphArray)\n this._resolver.addLanguage(lang);\n for (const [_, lang] of langsGraphArray)\n this.loadLanguage(lang);\n }\n getLoadedLanguages() {\n if (!this._loadedLanguagesCache) {\n this._loadedLanguagesCache = [\n .../* @__PURE__ */ new Set([...this._resolvedGrammars.keys(), ...Object.keys(this._alias)])\n ];\n }\n return this._loadedLanguagesCache;\n }\n resolveEmbeddedLanguages(lang) {\n this._langMap.set(lang.name, lang);\n this._langGraph.set(lang.name, lang);\n if (lang.embeddedLangs) {\n for (const embeddedLang of lang.embeddedLangs)\n this._langGraph.set(embeddedLang, this._langMap.get(embeddedLang));\n }\n }\n}\n\nvar __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => {\n __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\n return value;\n};\nclass Resolver {\n constructor(engine, langs) {\n __publicField(this, \"_langs\", /* @__PURE__ */ new Map());\n __publicField(this, \"_scopeToLang\", /* @__PURE__ */ new Map());\n __publicField(this, \"_injections\", /* @__PURE__ */ new Map());\n __publicField(this, \"_onigLib\");\n this._onigLib = {\n createOnigScanner: (patterns) => engine.createScanner(patterns),\n createOnigString: (s) => engine.createString(s)\n };\n langs.forEach((i) => this.addLanguage(i));\n }\n get onigLib() {\n return this._onigLib;\n }\n getLangRegistration(langIdOrAlias) {\n return this._langs.get(langIdOrAlias);\n }\n loadGrammar(scopeName) {\n return this._scopeToLang.get(scopeName);\n }\n addLanguage(l) {\n this._langs.set(l.name, l);\n if (l.aliases) {\n l.aliases.forEach((a) => {\n this._langs.set(a, l);\n });\n }\n this._scopeToLang.set(l.scopeName, l);\n if (l.injectTo) {\n l.injectTo.forEach((i) => {\n if (!this._injections.get(i))\n this._injections.set(i, []);\n this._injections.get(i).push(l.scopeName);\n });\n }\n }\n getInjections(scopeName) {\n const scopeParts = scopeName.split(\".\");\n let injections = [];\n for (let i = 1; i <= scopeParts.length; i++) {\n const subScopeName = scopeParts.slice(0, i).join(\".\");\n injections = [...injections, ...this._injections.get(subScopeName) || []];\n }\n return injections;\n }\n}\n\nlet instancesCount = 0;\nfunction createShikiInternalSync(options) {\n instancesCount += 1;\n if (options.warnings !== false && instancesCount >= 10 && instancesCount % 10 === 0)\n console.warn(`[Shiki] ${instancesCount} instances have been created. Shiki is supposed to be used as a singleton, consider refactoring your code to cache your highlighter instance; Or call \\`highlighter.dispose()\\` to release unused instances.`);\n let isDisposed = false;\n if (!options.engine)\n throw new ShikiError(\"`engine` option is required for synchronous mode\");\n const langs = (options.langs || []).flat(1);\n const themes = (options.themes || []).flat(1).map(normalizeTheme);\n const resolver = new Resolver(options.engine, langs);\n const _registry = new Registry(resolver, themes, langs, options.langAlias);\n let _lastTheme;\n function getLanguage(name) {\n ensureNotDisposed();\n const _lang = _registry.getGrammar(typeof name === \"string\" ? name : name.name);\n if (!_lang)\n throw new ShikiError(`Language \\`${name}\\` not found, you may need to load it first`);\n return _lang;\n }\n function getTheme(name) {\n if (name === \"none\")\n return { bg: \"\", fg: \"\", name: \"none\", settings: [], type: \"dark\" };\n ensureNotDisposed();\n const _theme = _registry.getTheme(name);\n if (!_theme)\n throw new ShikiError(`Theme \\`${name}\\` not found, you may need to load it first`);\n return _theme;\n }\n function setTheme(name) {\n ensureNotDisposed();\n const theme = getTheme(name);\n if (_lastTheme !== name) {\n _registry.setTheme(theme);\n _lastTheme = name;\n }\n const colorMap = _registry.getColorMap();\n return {\n theme,\n colorMap\n };\n }\n function getLoadedThemes() {\n ensureNotDisposed();\n return _registry.getLoadedThemes();\n }\n function getLoadedLanguages() {\n ensureNotDisposed();\n return _registry.getLoadedLanguages();\n }\n function loadLanguageSync(...langs2) {\n ensureNotDisposed();\n _registry.loadLanguages(langs2.flat(1));\n }\n async function loadLanguage(...langs2) {\n return loadLanguageSync(await resolveLangs(langs2));\n }\n function loadThemeSync(...themes2) {\n ensureNotDisposed();\n for (const theme of themes2.flat(1)) {\n _registry.loadTheme(theme);\n }\n }\n async function loadTheme(...themes2) {\n ensureNotDisposed();\n return loadThemeSync(await resolveThemes(themes2));\n }\n function ensureNotDisposed() {\n if (isDisposed)\n throw new ShikiError(\"Shiki instance has been disposed\");\n }\n function dispose() {\n if (isDisposed)\n return;\n isDisposed = true;\n _registry.dispose();\n instancesCount -= 1;\n }\n return {\n setTheme,\n getTheme,\n getLanguage,\n getLoadedThemes,\n getLoadedLanguages,\n loadLanguage,\n loadLanguageSync,\n loadTheme,\n loadThemeSync,\n dispose,\n [Symbol.dispose]: dispose\n };\n}\n\nasync function createShikiInternal(options = {}) {\n if (options.loadWasm) {\n warnDeprecated(\"`loadWasm` option is deprecated. Use `engine: createOnigurumaEngine(loadWasm)` instead.\");\n }\n const [\n themes,\n langs,\n engine\n ] = await Promise.all([\n resolveThemes(options.themes || []),\n resolveLangs(options.langs || []),\n options.engine || createOnigurumaEngine$1(options.loadWasm || getDefaultWasmLoader())\n ]);\n return createShikiInternalSync({\n ...options,\n loadWasm: void 0,\n themes,\n langs,\n engine\n });\n}\nfunction getShikiInternal(options = {}) {\n warnDeprecated(\"`getShikiInternal` is deprecated. Use `createShikiInternal` instead.\");\n return createShikiInternal(options);\n}\n\nasync function createHighlighterCore(options = {}) {\n const internal = await createShikiInternal(options);\n return {\n getLastGrammarState: (...args) => getLastGrammarState(internal, ...args),\n codeToTokensBase: (code, options2) => codeToTokensBase(internal, code, options2),\n codeToTokensWithThemes: (code, options2) => codeToTokensWithThemes(internal, code, options2),\n codeToTokens: (code, options2) => codeToTokens(internal, code, options2),\n codeToHast: (code, options2) => codeToHast(internal, code, options2),\n codeToHtml: (code, options2) => codeToHtml(internal, code, options2),\n ...internal,\n getInternalContext: () => internal\n };\n}\nfunction createHighlighterCoreSync(options = {}) {\n const internal = createShikiInternalSync(options);\n return {\n getLastGrammarState: (...args) => getLastGrammarState(internal, ...args),\n codeToTokensBase: (code, options2) => codeToTokensBase(internal, code, options2),\n codeToTokensWithThemes: (code, options2) => codeToTokensWithThemes(internal, code, options2),\n codeToTokens: (code, options2) => codeToTokens(internal, code, options2),\n codeToHast: (code, options2) => codeToHast(internal, code, options2),\n codeToHtml: (code, options2) => codeToHtml(internal, code, options2),\n ...internal,\n getInternalContext: () => internal\n };\n}\nfunction makeSingletonHighlighterCore(createHighlighter) {\n let _shiki;\n async function getSingletonHighlighterCore2(options = {}) {\n if (!_shiki) {\n _shiki = createHighlighter({\n ...options,\n themes: options.themes || [],\n langs: options.langs || []\n });\n return _shiki;\n } else {\n const s = await _shiki;\n await Promise.all([\n s.loadTheme(...options.themes || []),\n s.loadLanguage(...options.langs || [])\n ]);\n return s;\n }\n }\n return getSingletonHighlighterCore2;\n}\nconst getSingletonHighlighterCore = /* @__PURE__ */ makeSingletonHighlighterCore(createHighlighterCore);\nfunction getHighlighterCore(options = {}) {\n warnDeprecated(\"`getHighlighterCore` is deprecated. Use `createHighlighterCore` or `getSingletonHighlighterCore` instead.\");\n return createHighlighterCore(options);\n}\n\nfunction createdBundledHighlighter(arg1, arg2, arg3) {\n let bundledLanguages;\n let bundledThemes;\n let engine;\n if (arg2) {\n warnDeprecated(\"`createdBundledHighlighter` signature with `bundledLanguages` and `bundledThemes` is deprecated. Use the options object signature instead.\");\n bundledLanguages = arg1;\n bundledThemes = arg2;\n engine = () => createOnigurumaEngine(arg3);\n } else {\n const options = arg1;\n bundledLanguages = options.langs;\n bundledThemes = options.themes;\n engine = options.engine;\n }\n async function createHighlighter(options) {\n function resolveLang(lang) {\n if (typeof lang === \"string\") {\n if (isSpecialLang(lang))\n return [];\n const bundle = bundledLanguages[lang];\n if (!bundle)\n throw new ShikiError$1(`Language \\`${lang}\\` is not included in this bundle. You may want to load it from external source.`);\n return bundle;\n }\n return lang;\n }\n function resolveTheme(theme) {\n if (isSpecialTheme(theme))\n return \"none\";\n if (typeof theme === \"string\") {\n const bundle = bundledThemes[theme];\n if (!bundle)\n throw new ShikiError$1(`Theme \\`${theme}\\` is not included in this bundle. You may want to load it from external source.`);\n return bundle;\n }\n return theme;\n }\n const _themes = (options.themes ?? []).map((i) => resolveTheme(i));\n const langs = (options.langs ?? []).map((i) => resolveLang(i));\n const core = await createHighlighterCore({\n engine: options.engine ?? engine(),\n ...options,\n themes: _themes,\n langs\n });\n return {\n ...core,\n loadLanguage(...langs2) {\n return core.loadLanguage(...langs2.map(resolveLang));\n },\n loadTheme(...themes) {\n return core.loadTheme(...themes.map(resolveTheme));\n }\n };\n }\n return createHighlighter;\n}\nfunction makeSingletonHighlighter(createHighlighter) {\n let _shiki;\n async function getSingletonHighlighter(options = {}) {\n if (!_shiki) {\n _shiki = createHighlighter({\n ...options,\n themes: options.themes || [],\n langs: options.langs || []\n });\n return _shiki;\n } else {\n const s = await _shiki;\n await Promise.all([\n s.loadTheme(...options.themes || []),\n s.loadLanguage(...options.langs || [])\n ]);\n return s;\n }\n }\n return getSingletonHighlighter;\n}\nfunction createSingletonShorthands(createHighlighter) {\n const getSingletonHighlighter = makeSingletonHighlighter(createHighlighter);\n return {\n getSingletonHighlighter(options) {\n return getSingletonHighlighter(options);\n },\n async codeToHtml(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: \"theme\" in options ? [options.theme] : Object.values(options.themes)\n });\n return shiki.codeToHtml(code, options);\n },\n async codeToHast(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: \"theme\" in options ? [options.theme] : Object.values(options.themes)\n });\n return shiki.codeToHast(code, options);\n },\n async codeToTokens(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: \"theme\" in options ? [options.theme] : Object.values(options.themes)\n });\n return shiki.codeToTokens(code, options);\n },\n async codeToTokensBase(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: [options.theme]\n });\n return shiki.codeToTokensBase(code, options);\n },\n async codeToTokensWithThemes(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: Object.values(options.themes).filter(Boolean)\n });\n return shiki.codeToTokensWithThemes(code, options);\n },\n async getLastGrammarState(code, options) {\n const shiki = await getSingletonHighlighter({\n langs: [options.lang],\n themes: [options.theme]\n });\n return shiki.getLastGrammarState(code, options);\n }\n };\n}\n\nfunction createJavaScriptRegexEngine(options) {\n warnDeprecated(\"import `createJavaScriptRegexEngine` from `@shikijs/engine-javascript` or `shiki/engine/javascript` instead\");\n return createJavaScriptRegexEngine$1(options);\n}\nfunction defaultJavaScriptRegexConstructor(pattern) {\n warnDeprecated(\"import `defaultJavaScriptRegexConstructor` from `@shikijs/engine-javascript` or `shiki/engine/javascript` instead\");\n return defaultJavaScriptRegexConstructor$1(pattern);\n}\n\nfunction createCssVariablesTheme(options = {}) {\n const {\n name = \"css-variables\",\n variablePrefix = \"--shiki-\",\n fontStyle = true\n } = options;\n const variable = (name2) => {\n if (options.variableDefaults?.[name2])\n return `var(${variablePrefix}${name2}, ${options.variableDefaults[name2]})`;\n return `var(${variablePrefix}${name2})`;\n };\n const theme = {\n name,\n type: \"dark\",\n colors: {\n \"editor.foreground\": variable(\"foreground\"),\n \"editor.background\": variable(\"background\"),\n \"terminal.ansiBlack\": variable(\"ansi-black\"),\n \"terminal.ansiRed\": variable(\"ansi-red\"),\n \"terminal.ansiGreen\": variable(\"ansi-green\"),\n \"terminal.ansiYellow\": variable(\"ansi-yellow\"),\n \"terminal.ansiBlue\": variable(\"ansi-blue\"),\n \"terminal.ansiMagenta\": variable(\"ansi-magenta\"),\n \"terminal.ansiCyan\": variable(\"ansi-cyan\"),\n \"terminal.ansiWhite\": variable(\"ansi-white\"),\n \"terminal.ansiBrightBlack\": variable(\"ansi-bright-black\"),\n \"terminal.ansiBrightRed\": variable(\"ansi-bright-red\"),\n \"terminal.ansiBrightGreen\": variable(\"ansi-bright-green\"),\n \"terminal.ansiBrightYellow\": variable(\"ansi-bright-yellow\"),\n \"terminal.ansiBrightBlue\": variable(\"ansi-bright-blue\"),\n \"terminal.ansiBrightMagenta\": variable(\"ansi-bright-magenta\"),\n \"terminal.ansiBrightCyan\": variable(\"ansi-bright-cyan\"),\n \"terminal.ansiBrightWhite\": variable(\"ansi-bright-white\")\n },\n tokenColors: [\n {\n scope: [\n \"keyword.operator.accessor\",\n \"meta.group.braces.round.function.arguments\",\n \"meta.template.expression\",\n \"markup.fenced_code meta.embedded.block\"\n ],\n settings: {\n foreground: variable(\"foreground\")\n }\n },\n {\n scope: \"emphasis\",\n settings: {\n fontStyle: \"italic\"\n }\n },\n {\n scope: [\"strong\", \"markup.heading.markdown\", \"markup.bold.markdown\"],\n settings: {\n fontStyle: \"bold\"\n }\n },\n {\n scope: [\"markup.italic.markdown\"],\n settings: {\n fontStyle: \"italic\"\n }\n },\n {\n scope: \"meta.link.inline.markdown\",\n settings: {\n fontStyle: \"underline\",\n foreground: variable(\"token-link\")\n }\n },\n {\n scope: [\"string\", \"markup.fenced_code\", \"markup.inline\"],\n settings: {\n foreground: variable(\"token-string\")\n }\n },\n {\n scope: [\"comment\", \"string.quoted.docstring.multi\"],\n settings: {\n foreground: variable(\"token-comment\")\n }\n },\n {\n scope: [\n \"constant.numeric\",\n \"constant.language\",\n \"constant.other.placeholder\",\n \"constant.character.format.placeholder\",\n \"variable.language.this\",\n \"variable.other.object\",\n \"variable.other.class\",\n \"variable.other.constant\",\n \"meta.property-name\",\n \"meta.property-value\",\n \"support\"\n ],\n settings: {\n foreground: variable(\"token-constant\")\n }\n },\n {\n scope: [\n \"keyword\",\n \"storage.modifier\",\n \"storage.type\",\n \"storage.control.clojure\",\n \"entity.name.function.clojure\",\n \"entity.name.tag.yaml\",\n \"support.function.node\",\n \"support.type.property-name.json\",\n \"punctuation.separator.key-value\",\n \"punctuation.definition.template-expression\"\n ],\n settings: {\n foreground: variable(\"token-keyword\")\n }\n },\n {\n scope: \"variable.parameter.function\",\n settings: {\n foreground: variable(\"token-parameter\")\n }\n },\n {\n scope: [\n \"support.function\",\n \"entity.name.type\",\n \"entity.other.inherited-class\",\n \"meta.function-call\",\n \"meta.instance.constructor\",\n \"entity.other.attribute-name\",\n \"entity.name.function\",\n \"constant.keyword.clojure\"\n ],\n settings: {\n foreground: variable(\"token-function\")\n }\n },\n {\n scope: [\n \"entity.name.tag\",\n \"string.quoted\",\n \"string.regexp\",\n \"string.interpolated\",\n \"string.template\",\n \"string.unquoted.plain.out.yaml\",\n \"keyword.other.template\"\n ],\n settings: {\n foreground: variable(\"token-string-expression\")\n }\n },\n {\n scope: [\n \"punctuation.definition.arguments\",\n \"punctuation.definition.dict\",\n \"punctuation.separator\",\n \"meta.function-call.arguments\"\n ],\n settings: {\n foreground: variable(\"token-punctuation\")\n }\n },\n {\n // [Custom] Markdown links\n scope: [\n \"markup.underline.link\",\n \"punctuation.definition.metadata.markdown\"\n ],\n settings: {\n foreground: variable(\"token-link\")\n }\n },\n {\n // [Custom] Markdown list\n scope: [\"beginning.punctuation.definition.list.markdown\"],\n settings: {\n foreground: variable(\"token-string\")\n }\n },\n {\n // [Custom] Markdown punctuation definition brackets\n scope: [\n \"punctuation.definition.string.begin.markdown\",\n \"punctuation.definition.string.end.markdown\",\n \"string.other.link.title.markdown\",\n \"string.other.link.description.markdown\"\n ],\n settings: {\n foreground: variable(\"token-keyword\")\n }\n },\n {\n // [Custom] Diff\n scope: [\n \"markup.inserted\",\n \"meta.diff.header.to-file\",\n \"punctuation.definition.inserted\"\n ],\n settings: {\n foreground: variable(\"token-inserted\")\n }\n },\n {\n scope: [\n \"markup.deleted\",\n \"meta.diff.header.from-file\",\n \"punctuation.definition.deleted\"\n ],\n settings: {\n foreground: variable(\"token-deleted\")\n }\n },\n {\n scope: [\n \"markup.changed\",\n \"punctuation.definition.changed\"\n ],\n settings: {\n foreground: variable(\"token-changed\")\n }\n }\n ]\n };\n if (!fontStyle) {\n theme.tokenColors = theme.tokenColors?.map((tokenColor) => {\n if (tokenColor.settings?.fontStyle)\n delete tokenColor.settings.fontStyle;\n return tokenColor;\n });\n }\n return theme;\n}\n\nexport { addClassToHast, applyColorReplacements, codeToHast, codeToHtml, codeToTokens, codeToTokensBase, codeToTokensWithThemes, createCssVariablesTheme, createHighlighterCore, createHighlighterCoreSync, createJavaScriptRegexEngine, createOnigurumaEngine, createPositionConverter, createShikiInternal, createShikiInternalSync, createSingletonShorthands, createWasmOnigEngine, createdBundledHighlighter, defaultJavaScriptRegexConstructor, getHighlighterCore, getShikiInternal, getSingletonHighlighterCore, getTokenStyleObject, isNoneTheme, isPlainLang, isSpecialLang, isSpecialTheme, loadWasm, makeSingletonHighlighter, makeSingletonHighlighterCore, normalizeGetter, normalizeTheme, resolveColorReplacements, splitLines, splitToken, splitTokens, stringifyTokenStyle, toArray, tokenizeAnsiWithTheme, tokenizeWithTheme, tokensToHast, transformerDecorations, warnDeprecated };\n","/* Theme: github-dark-default */\nexport default Object.freeze(JSON.parse(\"{\\\"colors\\\":{\\\"activityBar.activeBorder\\\":\\\"#f78166\\\",\\\"activityBar.background\\\":\\\"#0d1117\\\",\\\"activityBar.border\\\":\\\"#30363d\\\",\\\"activityBar.foreground\\\":\\\"#e6edf3\\\",\\\"activityBar.inactiveForeground\\\":\\\"#7d8590\\\",\\\"activityBarBadge.background\\\":\\\"#1f6feb\\\",\\\"activityBarBadge.foreground\\\":\\\"#ffffff\\\",\\\"badge.background\\\":\\\"#1f6feb\\\",\\\"badge.foreground\\\":\\\"#ffffff\\\",\\\"breadcrumb.activeSelectionForeground\\\":\\\"#7d8590\\\",\\\"breadcrumb.focusForeground\\\":\\\"#e6edf3\\\",\\\"breadcrumb.foreground\\\":\\\"#7d8590\\\",\\\"breadcrumbPicker.background\\\":\\\"#161b22\\\",\\\"button.background\\\":\\\"#238636\\\",\\\"button.foreground\\\":\\\"#ffffff\\\",\\\"button.hoverBackground\\\":\\\"#2ea043\\\",\\\"button.secondaryBackground\\\":\\\"#282e33\\\",\\\"button.secondaryForeground\\\":\\\"#c9d1d9\\\",\\\"button.secondaryHoverBackground\\\":\\\"#30363d\\\",\\\"checkbox.background\\\":\\\"#161b22\\\",\\\"checkbox.border\\\":\\\"#30363d\\\",\\\"debugConsole.errorForeground\\\":\\\"#ffa198\\\",\\\"debugConsole.infoForeground\\\":\\\"#8b949e\\\",\\\"debugConsole.sourceForeground\\\":\\\"#e3b341\\\",\\\"debugConsole.warningForeground\\\":\\\"#d29922\\\",\\\"debugConsoleInputIcon.foreground\\\":\\\"#bc8cff\\\",\\\"debugIcon.breakpointForeground\\\":\\\"#f85149\\\",\\\"debugTokenExpression.boolean\\\":\\\"#56d364\\\",\\\"debugTokenExpression.error\\\":\\\"#ffa198\\\",\\\"debugTokenExpression.name\\\":\\\"#79c0ff\\\",\\\"debugTokenExpression.number\\\":\\\"#56d364\\\",\\\"debugTokenExpression.string\\\":\\\"#a5d6ff\\\",\\\"debugTokenExpression.value\\\":\\\"#a5d6ff\\\",\\\"debugToolBar.background\\\":\\\"#161b22\\\",\\\"descriptionForeground\\\":\\\"#7d8590\\\",\\\"diffEditor.insertedLineBackground\\\":\\\"#23863626\\\",\\\"diffEditor.insertedTextBackground\\\":\\\"#3fb9504d\\\",\\\"diffEditor.removedLineBackground\\\":\\\"#da363326\\\",\\\"diffEditor.removedTextBackground\\\":\\\"#ff7b724d\\\",\\\"dropdown.background\\\":\\\"#161b22\\\",\\\"dropdown.border\\\":\\\"#30363d\\\",\\\"dropdown.foreground\\\":\\\"#e6edf3\\\",\\\"dropdown.listBackground\\\":\\\"#161b22\\\",\\\"editor.background\\\":\\\"#0d1117\\\",\\\"editor.findMatchBackground\\\":\\\"#9e6a03\\\",\\\"editor.findMatchHighlightBackground\\\":\\\"#f2cc6080\\\",\\\"editor.focusedStackFrameHighlightBackground\\\":\\\"#2ea04366\\\",\\\"editor.foldBackground\\\":\\\"#6e76811a\\\",\\\"editor.foreground\\\":\\\"#e6edf3\\\",\\\"editor.lineHighlightBackground\\\":\\\"#6e76811a\\\",\\\"editor.linkedEditingBackground\\\":\\\"#2f81f712\\\",\\\"editor.selectionHighlightBackground\\\":\\\"#3fb95040\\\",\\\"editor.stackFrameHighlightBackground\\\":\\\"#bb800966\\\",\\\"editor.wordHighlightBackground\\\":\\\"#6e768180\\\",\\\"editor.wordHighlightBorder\\\":\\\"#6e768199\\\",\\\"editor.wordHighlightStrongBackground\\\":\\\"#6e76814d\\\",\\\"editor.wordHighlightStrongBorder\\\":\\\"#6e768199\\\",\\\"editorBracketHighlight.foreground1\\\":\\\"#79c0ff\\\",\\\"editorBracketHighlight.foreground2\\\":\\\"#56d364\\\",\\\"editorBracketHighlight.foreground3\\\":\\\"#e3b341\\\",\\\"editorBracketHighlight.foreground4\\\":\\\"#ffa198\\\",\\\"editorBracketHighlight.foreground5\\\":\\\"#ff9bce\\\",\\\"editorBracketHighlight.foreground6\\\":\\\"#d2a8ff\\\",\\\"editorBracketHighlight.unexpectedBracket.foreground\\\":\\\"#7d8590\\\",\\\"editorBracketMatch.background\\\":\\\"#3fb95040\\\",\\\"editorBracketMatch.border\\\":\\\"#3fb95099\\\",\\\"editorCursor.foreground\\\":\\\"#2f81f7\\\",\\\"editorGroup.border\\\":\\\"#30363d\\\",\\\"editorGroupHeader.tabsBackground\\\":\\\"#010409\\\",\\\"editorGroupHeader.tabsBorder\\\":\\\"#30363d\\\",\\\"editorGutter.addedBackground\\\":\\\"#2ea04366\\\",\\\"editorGutter.deletedBackground\\\":\\\"#f8514966\\\",\\\"editorGutter.modifiedBackground\\\":\\\"#bb800966\\\",\\\"editorIndentGuide.activeBackground\\\":\\\"#e6edf33d\\\",\\\"editorIndentGuide.background\\\":\\\"#e6edf31f\\\",\\\"editorInlayHint.background\\\":\\\"#8b949e33\\\",\\\"editorInlayHint.foreground\\\":\\\"#7d8590\\\",\\\"editorInlayHint.paramBackground\\\":\\\"#8b949e33\\\",\\\"editorInlayHint.paramForeground\\\":\\\"#7d8590\\\",\\\"editorInlayHint.typeBackground\\\":\\\"#8b949e33\\\",\\\"editorInlayHint.typeForeground\\\":\\\"#7d8590\\\",\\\"editorLineNumber.activeForeground\\\":\\\"#e6edf3\\\",\\\"editorLineNumber.foreground\\\":\\\"#6e7681\\\",\\\"editorOverviewRuler.border\\\":\\\"#010409\\\",\\\"editorWhitespace.foreground\\\":\\\"#484f58\\\",\\\"editorWidget.background\\\":\\\"#161b22\\\",\\\"errorForeground\\\":\\\"#f85149\\\",\\\"focusBorder\\\":\\\"#1f6feb\\\",\\\"foreground\\\":\\\"#e6edf3\\\",\\\"gitDecoration.addedResourceForeground\\\":\\\"#3fb950\\\",\\\"gitDecoration.conflictingResourceForeground\\\":\\\"#db6d28\\\",\\\"gitDecoration.deletedResourceForeground\\\":\\\"#f85149\\\",\\\"gitDecoration.ignoredResourceForeground\\\":\\\"#6e7681\\\",\\\"gitDecoration.modifiedResourceForeground\\\":\\\"#d29922\\\",\\\"gitDecoration.submoduleResourceForeground\\\":\\\"#7d8590\\\",\\\"gitDecoration.untrackedResourceForeground\\\":\\\"#3fb950\\\",\\\"icon.foreground\\\":\\\"#7d8590\\\",\\\"input.background\\\":\\\"#0d1117\\\",\\\"input.border\\\":\\\"#30363d\\\",\\\"input.foreground\\\":\\\"#e6edf3\\\",\\\"input.placeholderForeground\\\":\\\"#6e7681\\\",\\\"keybindingLabel.foreground\\\":\\\"#e6edf3\\\",\\\"list.activeSelectionBackground\\\":\\\"#6e768166\\\",\\\"list.activeSelectionForeground\\\":\\\"#e6edf3\\\",\\\"list.focusBackground\\\":\\\"#388bfd26\\\",\\\"list.focusForeground\\\":\\\"#e6edf3\\\",\\\"list.highlightForeground\\\":\\\"#2f81f7\\\",\\\"list.hoverBackground\\\":\\\"#6e76811a\\\",\\\"list.hoverForeground\\\":\\\"#e6edf3\\\",\\\"list.inactiveFocusBackground\\\":\\\"#388bfd26\\\",\\\"list.inactiveSelectionBackground\\\":\\\"#6e768166\\\",\\\"list.inactiveSelectionForeground\\\":\\\"#e6edf3\\\",\\\"minimapSlider.activeBackground\\\":\\\"#8b949e47\\\",\\\"minimapSlider.background\\\":\\\"#8b949e33\\\",\\\"minimapSlider.hoverBackground\\\":\\\"#8b949e3d\\\",\\\"notificationCenterHeader.background\\\":\\\"#161b22\\\",\\\"notificationCenterHeader.foreground\\\":\\\"#7d8590\\\",\\\"notifications.background\\\":\\\"#161b22\\\",\\\"notifications.border\\\":\\\"#30363d\\\",\\\"notifications.foreground\\\":\\\"#e6edf3\\\",\\\"notificationsErrorIcon.foreground\\\":\\\"#f85149\\\",\\\"notificationsInfoIcon.foreground\\\":\\\"#2f81f7\\\",\\\"notificationsWarningIcon.foreground\\\":\\\"#d29922\\\",\\\"panel.background\\\":\\\"#010409\\\",\\\"panel.border\\\":\\\"#30363d\\\",\\\"panelInput.border\\\":\\\"#30363d\\\",\\\"panelTitle.activeBorder\\\":\\\"#f78166\\\",\\\"panelTitle.activeForeground\\\":\\\"#e6edf3\\\",\\\"panelTitle.inactiveForeground\\\":\\\"#7d8590\\\",\\\"peekViewEditor.background\\\":\\\"#6e76811a\\\",\\\"peekViewEditor.matchHighlightBackground\\\":\\\"#bb800966\\\",\\\"peekViewResult.background\\\":\\\"#0d1117\\\",\\\"peekViewResult.matchHighlightBackground\\\":\\\"#bb800966\\\",\\\"pickerGroup.border\\\":\\\"#30363d\\\",\\\"pickerGroup.foreground\\\":\\\"#7d8590\\\",\\\"progressBar.background\\\":\\\"#1f6feb\\\",\\\"quickInput.background\\\":\\\"#161b22\\\",\\\"quickInput.foreground\\\":\\\"#e6edf3\\\",\\\"scrollbar.shadow\\\":\\\"#484f5833\\\",\\\"scrollbarSlider.activeBackground\\\":\\\"#8b949e47\\\",\\\"scrollbarSlider.background\\\":\\\"#8b949e33\\\",\\\"scrollbarSlider.hoverBackground\\\":\\\"#8b949e3d\\\",\\\"settings.headerForeground\\\":\\\"#e6edf3\\\",\\\"settings.modifiedItemIndicator\\\":\\\"#bb800966\\\",\\\"sideBar.background\\\":\\\"#010409\\\",\\\"sideBar.border\\\":\\\"#30363d\\\",\\\"sideBar.foreground\\\":\\\"#e6edf3\\\",\\\"sideBarSectionHeader.background\\\":\\\"#010409\\\",\\\"sideBarSectionHeader.border\\\":\\\"#30363d\\\",\\\"sideBarSectionHeader.foreground\\\":\\\"#e6edf3\\\",\\\"sideBarTitle.foreground\\\":\\\"#e6edf3\\\",\\\"statusBar.background\\\":\\\"#0d1117\\\",\\\"statusBar.border\\\":\\\"#30363d\\\",\\\"statusBar.debuggingBackground\\\":\\\"#da3633\\\",\\\"statusBar.debuggingForeground\\\":\\\"#ffffff\\\",\\\"statusBar.focusBorder\\\":\\\"#1f6feb80\\\",\\\"statusBar.foreground\\\":\\\"#7d8590\\\",\\\"statusBar.noFolderBackground\\\":\\\"#0d1117\\\",\\\"statusBarItem.activeBackground\\\":\\\"#e6edf31f\\\",\\\"statusBarItem.focusBorder\\\":\\\"#1f6feb\\\",\\\"statusBarItem.hoverBackground\\\":\\\"#e6edf314\\\",\\\"statusBarItem.prominentBackground\\\":\\\"#6e768166\\\",\\\"statusBarItem.remoteBackground\\\":\\\"#30363d\\\",\\\"statusBarItem.remoteForeground\\\":\\\"#e6edf3\\\",\\\"symbolIcon.arrayForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.booleanForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.classForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.colorForeground\\\":\\\"#79c0ff\\\",\\\"symbolIcon.constantForeground\\\":[\\\"#aff5b4\\\",\\\"#7ee787\\\",\\\"#56d364\\\",\\\"#3fb950\\\",\\\"#2ea043\\\",\\\"#238636\\\",\\\"#196c2e\\\",\\\"#0f5323\\\",\\\"#033a16\\\",\\\"#04260f\\\"],\\\"symbolIcon.constructorForeground\\\":\\\"#d2a8ff\\\",\\\"symbolIcon.enumeratorForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.enumeratorMemberForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.eventForeground\\\":\\\"#6e7681\\\",\\\"symbolIcon.fieldForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.fileForeground\\\":\\\"#d29922\\\",\\\"symbolIcon.folderForeground\\\":\\\"#d29922\\\",\\\"symbolIcon.functionForeground\\\":\\\"#bc8cff\\\",\\\"symbolIcon.interfaceForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.keyForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.keywordForeground\\\":\\\"#ff7b72\\\",\\\"symbolIcon.methodForeground\\\":\\\"#bc8cff\\\",\\\"symbolIcon.moduleForeground\\\":\\\"#ff7b72\\\",\\\"symbolIcon.namespaceForeground\\\":\\\"#ff7b72\\\",\\\"symbolIcon.nullForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.numberForeground\\\":\\\"#3fb950\\\",\\\"symbolIcon.objectForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.operatorForeground\\\":\\\"#79c0ff\\\",\\\"symbolIcon.packageForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.propertyForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.referenceForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.snippetForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.stringForeground\\\":\\\"#79c0ff\\\",\\\"symbolIcon.structForeground\\\":\\\"#f0883e\\\",\\\"symbolIcon.textForeground\\\":\\\"#79c0ff\\\",\\\"symbolIcon.typeParameterForeground\\\":\\\"#79c0ff\\\",\\\"symbolIcon.unitForeground\\\":\\\"#58a6ff\\\",\\\"symbolIcon.variableForeground\\\":\\\"#f0883e\\\",\\\"tab.activeBackground\\\":\\\"#0d1117\\\",\\\"tab.activeBorder\\\":\\\"#0d1117\\\",\\\"tab.activeBorderTop\\\":\\\"#f78166\\\",\\\"tab.activeForeground\\\":\\\"#e6edf3\\\",\\\"tab.border\\\":\\\"#30363d\\\",\\\"tab.hoverBackground\\\":\\\"#0d1117\\\",\\\"tab.inactiveBackground\\\":\\\"#010409\\\",\\\"tab.inactiveForeground\\\":\\\"#7d8590\\\",\\\"tab.unfocusedActiveBorder\\\":\\\"#0d1117\\\",\\\"tab.unfocusedActiveBorderTop\\\":\\\"#30363d\\\",\\\"tab.unfocusedHoverBackground\\\":\\\"#6e76811a\\\",\\\"terminal.ansiBlack\\\":\\\"#484f58\\\",\\\"terminal.ansiBlue\\\":\\\"#58a6ff\\\",\\\"terminal.ansiBrightBlack\\\":\\\"#6e7681\\\",\\\"terminal.ansiBrightBlue\\\":\\\"#79c0ff\\\",\\\"terminal.ansiBrightCyan\\\":\\\"#56d4dd\\\",\\\"terminal.ansiBrightGreen\\\":\\\"#56d364\\\",\\\"terminal.ansiBrightMagenta\\\":\\\"#d2a8ff\\\",\\\"terminal.ansiBrightRed\\\":\\\"#ffa198\\\",\\\"terminal.ansiBrightWhite\\\":\\\"#ffffff\\\",\\\"terminal.ansiBrightYellow\\\":\\\"#e3b341\\\",\\\"terminal.ansiCyan\\\":\\\"#39c5cf\\\",\\\"terminal.ansiGreen\\\":\\\"#3fb950\\\",\\\"terminal.ansiMagenta\\\":\\\"#bc8cff\\\",\\\"terminal.ansiRed\\\":\\\"#ff7b72\\\",\\\"terminal.ansiWhite\\\":\\\"#b1bac4\\\",\\\"terminal.ansiYellow\\\":\\\"#d29922\\\",\\\"terminal.foreground\\\":\\\"#e6edf3\\\",\\\"textBlockQuote.background\\\":\\\"#010409\\\",\\\"textBlockQuote.border\\\":\\\"#30363d\\\",\\\"textCodeBlock.background\\\":\\\"#6e768166\\\",\\\"textLink.activeForeground\\\":\\\"#2f81f7\\\",\\\"textLink.foreground\\\":\\\"#2f81f7\\\",\\\"textPreformat.background\\\":\\\"#6e768166\\\",\\\"textPreformat.foreground\\\":\\\"#7d8590\\\",\\\"textSeparator.foreground\\\":\\\"#21262d\\\",\\\"titleBar.activeBackground\\\":\\\"#0d1117\\\",\\\"titleBar.activeForeground\\\":\\\"#7d8590\\\",\\\"titleBar.border\\\":\\\"#30363d\\\",\\\"titleBar.inactiveBackground\\\":\\\"#010409\\\",\\\"titleBar.inactiveForeground\\\":\\\"#7d8590\\\",\\\"tree.indentGuidesStroke\\\":\\\"#21262d\\\",\\\"welcomePage.buttonBackground\\\":\\\"#21262d\\\",\\\"welcomePage.buttonHoverBackground\\\":\\\"#30363d\\\"},\\\"displayName\\\":\\\"GitHub Dark Default\\\",\\\"name\\\":\\\"github-dark-default\\\",\\\"semanticHighlighting\\\":true,\\\"tokenColors\\\":[{\\\"scope\\\":[\\\"comment\\\",\\\"punctuation.definition.comment\\\",\\\"string.comment\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#8b949e\\\"}},{\\\"scope\\\":[\\\"constant.other.placeholder\\\",\\\"constant.character\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#ff7b72\\\"}},{\\\"scope\\\":[\\\"constant\\\",\\\"entity.name.constant\\\",\\\"variable.other.constant\\\",\\\"variable.other.enummember\\\",\\\"variable.language\\\",\\\"entity\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":[\\\"entity.name\\\",\\\"meta.export.default\\\",\\\"meta.definition.variable\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#ffa657\\\"}},{\\\"scope\\\":[\\\"variable.parameter.function\\\",\\\"meta.jsx.children\\\",\\\"meta.block\\\",\\\"meta.tag.attributes\\\",\\\"entity.name.constant\\\",\\\"meta.object.member\\\",\\\"meta.embedded.expression\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#e6edf3\\\"}},{\\\"scope\\\":\\\"entity.name.function\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#d2a8ff\\\"}},{\\\"scope\\\":[\\\"entity.name.tag\\\",\\\"support.class.component\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#7ee787\\\"}},{\\\"scope\\\":\\\"keyword\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ff7b72\\\"}},{\\\"scope\\\":[\\\"storage\\\",\\\"storage.type\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#ff7b72\\\"}},{\\\"scope\\\":[\\\"storage.modifier.package\\\",\\\"storage.modifier.import\\\",\\\"storage.type.java\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#e6edf3\\\"}},{\\\"scope\\\":[\\\"string\\\",\\\"string punctuation.section.embedded source\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#a5d6ff\\\"}},{\\\"scope\\\":\\\"support\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"meta.property-name\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ffa657\\\"}},{\\\"scope\\\":\\\"variable.other\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#e6edf3\\\"}},{\\\"scope\\\":\\\"invalid.broken\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":\\\"invalid.deprecated\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":\\\"invalid.illegal\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":\\\"invalid.unimplemented\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":\\\"carriage-return\\\",\\\"settings\\\":{\\\"background\\\":\\\"#ff7b72\\\",\\\"content\\\":\\\"^M\\\",\\\"fontStyle\\\":\\\"italic underline\\\",\\\"foreground\\\":\\\"#f0f6fc\\\"}},{\\\"scope\\\":\\\"message.error\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":\\\"string variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":[\\\"source.regexp\\\",\\\"string.regexp\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#a5d6ff\\\"}},{\\\"scope\\\":[\\\"string.regexp.character-class\\\",\\\"string.regexp constant.character.escape\\\",\\\"string.regexp source.ruby.embedded\\\",\\\"string.regexp string.regexp.arbitrary-repitition\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#a5d6ff\\\"}},{\\\"scope\\\":\\\"string.regexp constant.character.escape\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#7ee787\\\"}},{\\\"scope\\\":\\\"support.constant\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"support.variable\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"support.type.property-name.json\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#7ee787\\\"}},{\\\"scope\\\":\\\"meta.module-reference\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"punctuation.definition.list.begin.markdown\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ffa657\\\"}},{\\\"scope\\\":[\\\"markup.heading\\\",\\\"markup.heading entity.name\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"markup.quote\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#7ee787\\\"}},{\\\"scope\\\":\\\"markup.italic\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"italic\\\",\\\"foreground\\\":\\\"#e6edf3\\\"}},{\\\"scope\\\":\\\"markup.bold\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#e6edf3\\\"}},{\\\"scope\\\":[\\\"markup.underline\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"underline\\\"}},{\\\"scope\\\":[\\\"markup.strikethrough\\\"],\\\"settings\\\":{\\\"fontStyle\\\":\\\"strikethrough\\\"}},{\\\"scope\\\":\\\"markup.inline.raw\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":[\\\"markup.deleted\\\",\\\"meta.diff.header.from-file\\\",\\\"punctuation.definition.deleted\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#490202\\\",\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":[\\\"punctuation.section.embedded\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#ff7b72\\\"}},{\\\"scope\\\":[\\\"markup.inserted\\\",\\\"meta.diff.header.to-file\\\",\\\"punctuation.definition.inserted\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#04260f\\\",\\\"foreground\\\":\\\"#7ee787\\\"}},{\\\"scope\\\":[\\\"markup.changed\\\",\\\"punctuation.definition.changed\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#5a1e02\\\",\\\"foreground\\\":\\\"#ffa657\\\"}},{\\\"scope\\\":[\\\"markup.ignored\\\",\\\"markup.untracked\\\"],\\\"settings\\\":{\\\"background\\\":\\\"#79c0ff\\\",\\\"foreground\\\":\\\"#161b22\\\"}},{\\\"scope\\\":\\\"meta.diff.range\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#d2a8ff\\\"}},{\\\"scope\\\":\\\"meta.diff.header\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"meta.separator\\\",\\\"settings\\\":{\\\"fontStyle\\\":\\\"bold\\\",\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":\\\"meta.output\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#79c0ff\\\"}},{\\\"scope\\\":[\\\"brackethighlighter.tag\\\",\\\"brackethighlighter.curly\\\",\\\"brackethighlighter.round\\\",\\\"brackethighlighter.square\\\",\\\"brackethighlighter.angle\\\",\\\"brackethighlighter.quote\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#8b949e\\\"}},{\\\"scope\\\":\\\"brackethighlighter.unmatched\\\",\\\"settings\\\":{\\\"foreground\\\":\\\"#ffa198\\\"}},{\\\"scope\\\":[\\\"constant.other.reference.link\\\",\\\"string.other.link\\\"],\\\"settings\\\":{\\\"foreground\\\":\\\"#a5d6ff\\\"}}],\\\"type\\\":\\\"dark\\\"}\"))\n","// TODO: We should find some other ways to do this.\nconst pre = (markdown: string): string =>\n // IE11 does not support \"u\" flag and Babel could not remove it. We intentionally omitting the \"u\" flag here.\n // eslint-disable-next-line require-unicode-regexp\n markdown.replace(/\\n\\r|\\r\\n/g, carriageReturn => (carriageReturn === '\\n\\r' ? '\\r\\n' : '\\n\\r'));\n\nexport { pre };\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport { InvalidOperationError, ObjectDisposedError } from \"./Error\";\r\nimport { IDetachable } from \"./IDetachable\";\r\nimport { IDisposable } from \"./IDisposable\";\r\nimport { List } from \"./List\";\r\nimport {\r\n Deferred,\r\n} from \"./Promise\";\r\nexport interface IQueue<TItem> extends IDisposable {\r\n enqueue(item: TItem): void;\r\n enqueueFromPromise(promise: Promise<TItem>): void;\r\n dequeue(): Promise<TItem>;\r\n peek(): Promise<TItem>;\r\n length(): number;\r\n}\r\n\r\nenum SubscriberType {\r\n Dequeue,\r\n Peek,\r\n}\r\n\r\nexport class Queue<TItem> implements IQueue<TItem> {\r\n private privPromiseStore: List<Promise<TItem>> = new List<Promise<TItem>>();\r\n private privList: List<TItem>;\r\n private privDetachables: IDetachable[];\r\n private privSubscribers: List<{ type: SubscriberType, deferral: Deferred<TItem> }>;\r\n private privIsDrainInProgress: boolean = false;\r\n private privIsDisposing: boolean = false;\r\n private privDisposeReason: string = null;\r\n\r\n public constructor(list?: List<TItem>) {\r\n this.privList = list ? list : new List<TItem>();\r\n this.privDetachables = [];\r\n this.privSubscribers = new List<{ type: SubscriberType, deferral: Deferred<TItem> }>();\r\n this.privDetachables.push(this.privList.onAdded(this.drain));\r\n }\r\n\r\n public enqueue = (item: TItem): void => {\r\n this.throwIfDispose();\r\n this.enqueueFromPromise(new Promise<TItem>((resolve: (value: TItem) => void, reject: (reason: any) => void) => { resolve(item); }));\r\n }\r\n\r\n public enqueueFromPromise = (promise: Promise<TItem>): void => {\r\n this.throwIfDispose();\r\n promise.then((val: TItem): void => {\r\n this.privList.add(val);\r\n /* tslint:disable:no-empty */\r\n }, (error: string): void => { });\r\n }\r\n\r\n public dequeue = (): Promise<TItem> => {\r\n this.throwIfDispose();\r\n const deferredSubscriber = new Deferred<TItem>();\r\n\r\n if (this.privSubscribers) {\r\n this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Dequeue });\r\n this.drain();\r\n }\r\n\r\n return deferredSubscriber.promise;\r\n }\r\n\r\n public peek = (): Promise<TItem> => {\r\n this.throwIfDispose();\r\n const deferredSubscriber = new Deferred<TItem>();\r\n\r\n const subs = this.privSubscribers;\r\n if (subs) {\r\n this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Peek });\r\n this.drain();\r\n }\r\n\r\n return deferredSubscriber.promise;\r\n }\r\n\r\n public length = (): number => {\r\n this.throwIfDispose();\r\n return this.privList.length();\r\n }\r\n\r\n public isDisposed = (): boolean => {\r\n return this.privSubscribers == null;\r\n }\r\n\r\n public async drainAndDispose(pendingItemProcessor: (pendingItemInQueue: TItem) => void, reason?: string): Promise<void> {\r\n if (!this.isDisposed() && !this.privIsDisposing) {\r\n this.privDisposeReason = reason;\r\n this.privIsDisposing = true;\r\n\r\n const subs = this.privSubscribers;\r\n if (subs) {\r\n while (subs.length() > 0) {\r\n const subscriber = subs.removeFirst();\r\n // TODO: this needs work (Resolve(null) instead?).\r\n subscriber.deferral.resolve(undefined);\r\n // subscriber.deferral.reject(\"Disposed\");\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privSubscribers === subs) {\r\n this.privSubscribers = subs;\r\n }\r\n }\r\n\r\n for (const detachable of this.privDetachables) {\r\n await detachable.detach();\r\n }\r\n\r\n if (this.privPromiseStore.length() > 0 && pendingItemProcessor) {\r\n const promiseArray: Promise<TItem>[] = [];\r\n\r\n this.privPromiseStore.toArray().forEach((wrapper: Promise<TItem>) => {\r\n promiseArray.push(wrapper);\r\n });\r\n return Promise.all(promiseArray).finally(() => {\r\n this.privSubscribers = null;\r\n this.privList.forEach((item: TItem, index: number): void => {\r\n pendingItemProcessor(item);\r\n });\r\n this.privList = null;\r\n return;\r\n }).then<void>();\r\n } else {\r\n this.privSubscribers = null;\r\n this.privList = null;\r\n }\r\n }\r\n }\r\n\r\n public async dispose(reason?: string): Promise<void> {\r\n await this.drainAndDispose(null, reason);\r\n }\r\n\r\n private drain = (): void => {\r\n if (!this.privIsDrainInProgress && !this.privIsDisposing) {\r\n this.privIsDrainInProgress = true;\r\n\r\n const subs = this.privSubscribers;\r\n const lists = this.privList;\r\n if (subs && lists) {\r\n while (lists.length() > 0 && subs.length() > 0 && !this.privIsDisposing) {\r\n const subscriber = subs.removeFirst();\r\n if (subscriber.type === SubscriberType.Peek) {\r\n subscriber.deferral.resolve(lists.first());\r\n } else {\r\n const dequeuedItem = lists.removeFirst();\r\n subscriber.deferral.resolve(dequeuedItem);\r\n }\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privSubscribers === subs) {\r\n this.privSubscribers = subs;\r\n }\r\n\r\n // note: this block assumes cooperative multitasking, i.e.,\r\n // between the if-statement and the assignment there are no\r\n // thread switches.\r\n // Reason is that between the initial const = this.; and this\r\n // point there is the derral.resolve() operation that might have\r\n // caused recursive calls to the Queue, especially, calling\r\n // Dispose() on the queue alredy (which would reset the var\r\n // here to null!).\r\n // That should generally hold true for javascript...\r\n if (this.privList === lists) {\r\n this.privList = lists;\r\n }\r\n }\r\n\r\n this.privIsDrainInProgress = false;\r\n }\r\n }\r\n\r\n private throwIfDispose = (): void => {\r\n if (this.isDisposed()) {\r\n if (this.privDisposeReason) {\r\n throw new InvalidOperationError(this.privDisposeReason);\r\n }\r\n\r\n throw new ObjectDisposedError(\"Queue\");\r\n } else if (this.privIsDisposing) {\r\n throw new InvalidOperationError(\"Queue disposing\");\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport {\r\n createNoDashGuid,\r\n Deferred,\r\n IAudioDestination,\r\n IStreamChunk,\r\n Stream,\r\n} from \"../../common/Exports\";\r\nimport { Contracts } from \"../Contracts\";\r\nimport {\r\n AudioStreamFormat,\r\n PushAudioOutputStreamCallback\r\n} from \"../Exports\";\r\nimport { AudioOutputFormatImpl } from \"./AudioOutputFormat\";\r\n\r\n/**\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @class AudioOutputStream\r\n */\r\nexport abstract class AudioOutputStream {\r\n\r\n /**\r\n * Creates and initializes an instance.\r\n * @constructor\r\n */\r\n protected constructor() { }\r\n\r\n /**\r\n * Sets the format of the AudioOutputStream\r\n * Note: the format is set by the synthesizer before writing. Do not set it before passing it to AudioConfig\r\n * @member AudioOutputStream.prototype.format\r\n */\r\n public abstract set format(format: AudioStreamFormat);\r\n\r\n /**\r\n * Creates a memory backed PullAudioOutputStream with the specified audio format.\r\n * @member AudioOutputStream.createPullStream\r\n * @function\r\n * @public\r\n * @returns {PullAudioOutputStream} The audio output stream being created.\r\n */\r\n public static createPullStream(): PullAudioOutputStream {\r\n return PullAudioOutputStream.create();\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member AudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio output stream used for custom audio output configurations.\r\n * @class PullAudioOutputStream\r\n */\r\nexport abstract class PullAudioOutputStream extends AudioOutputStream {\r\n\r\n /**\r\n * Creates a memory backed PullAudioOutputStream with the specified audio format.\r\n * @member PullAudioOutputStream.create\r\n * @function\r\n * @public\r\n * @returns {PullAudioOutputStream} The push audio output stream being created.\r\n */\r\n public static create(): PullAudioOutputStream {\r\n return new PullAudioOutputStreamImpl();\r\n }\r\n\r\n /**\r\n * Reads audio data from the internal buffer.\r\n * @member PullAudioOutputStream.prototype.read\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - An ArrayBuffer to store the read data.\r\n * @returns {Promise<number>} Audio buffer length has been read.\r\n */\r\n public abstract read(dataBuffer: ArrayBuffer): Promise<number>;\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PullAudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n}\r\n\r\n/**\r\n * Represents memory backed push audio output stream used for custom audio output configurations.\r\n * @private\r\n * @class PullAudioOutputStreamImpl\r\n */\r\nexport class PullAudioOutputStreamImpl extends PullAudioOutputStream implements IAudioDestination {\r\n private privFormat: AudioOutputFormatImpl;\r\n private privId: string;\r\n private privStream: Stream<ArrayBuffer>;\r\n private privLastChunkView: Int8Array;\r\n\r\n /**\r\n * Creates and initializes an instance with the given values.\r\n * @constructor\r\n */\r\n public constructor() {\r\n super();\r\n this.privId = createNoDashGuid();\r\n this.privStream = new Stream<ArrayBuffer>();\r\n }\r\n\r\n /**\r\n * Sets the format information to the stream. For internal use only.\r\n * @param {AudioStreamFormat} format - the format to be set.\r\n */\r\n public set format(format: AudioStreamFormat) {\r\n if (format === undefined || format === null) {\r\n this.privFormat = AudioOutputFormatImpl.getDefaultOutputFormat();\r\n }\r\n this.privFormat = format as AudioOutputFormatImpl;\r\n }\r\n\r\n /**\r\n * Format information for the audio\r\n */\r\n public get format(): AudioStreamFormat {\r\n return this.privFormat;\r\n }\r\n\r\n /**\r\n * Checks if the stream is closed\r\n * @member PullAudioOutputStreamImpl.prototype.isClosed\r\n * @property\r\n * @public\r\n */\r\n public get isClosed(): boolean {\r\n return this.privStream.isClosed;\r\n }\r\n\r\n /**\r\n * Gets the id of the stream\r\n * @member PullAudioOutputStreamImpl.prototype.id\r\n * @property\r\n * @public\r\n */\r\n public id(): string {\r\n return this.privId;\r\n }\r\n\r\n /**\r\n * Reads audio data from the internal buffer.\r\n * @member PullAudioOutputStreamImpl.prototype.read\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - An ArrayBuffer to store the read data.\r\n * @returns {Promise<number>} - Audio buffer length has been read.\r\n */\r\n public async read(dataBuffer: ArrayBuffer): Promise<number> {\r\n const intView: Int8Array = new Int8Array(dataBuffer);\r\n let totalBytes: number = 0;\r\n\r\n if (this.privLastChunkView !== undefined) {\r\n if (this.privLastChunkView.length > dataBuffer.byteLength) {\r\n intView.set(this.privLastChunkView.slice(0, dataBuffer.byteLength));\r\n this.privLastChunkView = this.privLastChunkView.slice(dataBuffer.byteLength);\r\n return Promise.resolve(dataBuffer.byteLength);\r\n }\r\n intView.set(this.privLastChunkView);\r\n totalBytes = this.privLastChunkView.length;\r\n this.privLastChunkView = undefined;\r\n }\r\n\r\n // Until we have the minimum number of bytes to send in a transmission, keep asking for more.\r\n while (totalBytes < dataBuffer.byteLength && !this.privStream.isReadEnded) {\r\n const chunk: IStreamChunk<ArrayBuffer> = await this.privStream.read();\r\n if (chunk !== undefined && !chunk.isEnd) {\r\n let tmpBuffer: ArrayBuffer;\r\n if (chunk.buffer.byteLength > dataBuffer.byteLength - totalBytes) {\r\n tmpBuffer = chunk.buffer.slice(0, dataBuffer.byteLength - totalBytes);\r\n this.privLastChunkView = new Int8Array(chunk.buffer.slice(dataBuffer.byteLength - totalBytes));\r\n } else {\r\n tmpBuffer = chunk.buffer;\r\n }\r\n intView.set(new Int8Array(tmpBuffer), totalBytes);\r\n totalBytes += tmpBuffer.byteLength;\r\n } else {\r\n await this.privStream.readEnded();\r\n }\r\n }\r\n return totalBytes;\r\n }\r\n\r\n /**\r\n * Writes the audio data specified by making an internal copy of the data.\r\n * @member PullAudioOutputStreamImpl.prototype.write\r\n * @function\r\n * @public\r\n * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy.\r\n */\r\n public write(dataBuffer: ArrayBuffer): void {\r\n Contracts.throwIfNullOrUndefined(this.privStream, \"must set format before writing\");\r\n this.privStream.writeStreamChunk({\r\n buffer: dataBuffer,\r\n isEnd: false,\r\n timeReceived: Date.now()\r\n });\r\n }\r\n\r\n /**\r\n * Closes the stream.\r\n * @member PullAudioOutputStreamImpl.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public close(): void {\r\n this.privStream.close();\r\n }\r\n}\r\n\r\n/*\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @class PushAudioOutputStream\r\n */\r\nexport abstract class PushAudioOutputStream extends AudioOutputStream {\r\n /**\r\n * Creates and initializes and instance.\r\n * @constructor\r\n */\r\n protected constructor() { super(); }\r\n\r\n /**\r\n * Creates a PushAudioOutputStream that delegates to the specified callback interface for\r\n * write() and close() methods.\r\n * @member PushAudioOutputStream.create\r\n * @function\r\n * @public\r\n * @param {PushAudioOutputStreamCallback} callback - The custom audio output object,\r\n * derived from PushAudioOutputStreamCallback\r\n * @returns {PushAudioOutputStream} The push audio output stream being created.\r\n */\r\n public static create(callback: PushAudioOutputStreamCallback): PushAudioOutputStream {\r\n return new PushAudioOutputStreamImpl(callback);\r\n }\r\n\r\n /**\r\n * Explicitly frees any external resource attached to the object\r\n * @member PushAudioOutputStream.prototype.close\r\n * @function\r\n * @public\r\n */\r\n public abstract close(): void;\r\n\r\n}\r\n\r\n/**\r\n * Represents audio output stream used for custom audio output configurations.\r\n * @private\r\n * @class PushAudioOutputStreamImpl\r\n */\r\nexport class PushAudioOutputStreamImpl extends PushAudioOutputStream implements IAudioDestination {\r\n private readonly privId: string;\r\n private privCallback: PushAudioOutputStreamCallback;\r\n\r\n /**\r\n * Creates a PushAudioOutputStream that delegates to the specified callback interface for\r\n * read() and close() methods.\r\n * @constructor\r\n * @param {PushAudioOutputStreamCallback} callback - The custom audio output object,\r\n * derived from PushAudioOutputStreamCallback\r\n */\r\n public constructor(callback: PushAudioOutputStreamCallback) {\r\n super();\r\n this.privId = createNoDashGuid();\r\n this.privCallback = callback;\r\n }\r\n\r\n // tslint:disable-next-line:no-empty\r\n public set format(format: AudioStreamFormat) { }\r\n\r\n public write(buffer: ArrayBuffer): void {\r\n if (!!this.privCallback.write) {\r\n this.privCallback.write(buffer);\r\n }\r\n }\r\n\r\n public close(): void {\r\n if (!!this.privCallback.close) {\r\n this.privCallback.close();\r\n }\r\n }\r\n\r\n public id(): string {\r\n return this.privId;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\nimport {\r\n ConnectionMessage,\r\n Deferred,\r\n IStringDictionary,\r\n IWebsocketMessageFormatter,\r\n MessageType,\r\n RawWebsocketMessage,\r\n} from \"../common/Exports\";\r\n\r\nconst CRLF: string = \"\\r\\n\";\r\n\r\nexport class WebsocketMessageFormatter implements IWebsocketMessageFormatter {\r\n\r\n public toConnectionMessage = (message: RawWebsocketMessage): Promise<ConnectionMessage> => {\r\n const deferral = new Deferred<ConnectionMessage>();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const textMessage: string = message.textContent;\r\n let headers: IStringDictionary<string> = {};\r\n let body: string = null;\r\n\r\n if (textMessage) {\r\n const headerBodySplit = textMessage.split(\"\\r\\n\\r\\n\");\r\n if (headerBodySplit && headerBodySplit.length > 0) {\r\n headers = this.parseHeaders(headerBodySplit[0]);\r\n if (headerBodySplit.length > 1) {\r\n body = headerBodySplit[1];\r\n }\r\n }\r\n }\r\n\r\n deferral.resolve(new ConnectionMessage(message.messageType, body, headers, message.id));\r\n } else if (message.messageType === MessageType.Binary) {\r\n const binaryMessage: ArrayBuffer = message.binaryContent;\r\n let headers: IStringDictionary<string> = {};\r\n let body: ArrayBuffer = null;\r\n\r\n if (!binaryMessage || binaryMessage.byteLength < 2) {\r\n throw new Error(\"Invalid binary message format. Header length missing.\");\r\n }\r\n\r\n const dataView = new DataView(binaryMessage);\r\n const headerLength = dataView.getInt16(0);\r\n\r\n if (binaryMessage.byteLength < headerLength + 2) {\r\n throw new Error(\"Invalid binary message format. Header content missing.\");\r\n }\r\n\r\n let headersString = \"\";\r\n for (let i = 0; i < headerLength; i++) {\r\n headersString += String.fromCharCode((dataView).getInt8(i + 2));\r\n }\r\n\r\n headers = this.parseHeaders(headersString);\r\n\r\n if (binaryMessage.byteLength > headerLength + 2) {\r\n body = binaryMessage.slice(2 + headerLength);\r\n }\r\n\r\n deferral.resolve(new ConnectionMessage(message.messageType, body, headers, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. Error: ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n\r\n public fromConnectionMessage = (message: ConnectionMessage): Promise<RawWebsocketMessage> => {\r\n const deferral = new Deferred<RawWebsocketMessage>();\r\n\r\n try {\r\n if (message.messageType === MessageType.Text) {\r\n const payload = `${this.makeHeaders(message)}${CRLF}${message.textBody ? message.textBody : \"\"}`;\r\n\r\n deferral.resolve(new RawWebsocketMessage(MessageType.Text, payload, message.id));\r\n\r\n } else if (message.messageType === MessageType.Binary) {\r\n const headersString = this.makeHeaders(message);\r\n const content = message.binaryBody;\r\n\r\n const headerBuffer = this.stringToArrayBuffer(headersString);\r\n const headerInt8Array = new Int8Array(headerBuffer);\r\n const headerLength = headerInt8Array.byteLength;\r\n\r\n const payloadInt8Array = new Int8Array(2 + headerLength + (content ? content.byteLength : 0));\r\n payloadInt8Array[0] = ((headerLength >> 8) & 0xff);\r\n payloadInt8Array[1] = headerLength & 0xff;\r\n payloadInt8Array.set(headerInt8Array, 2);\r\n\r\n if (content) {\r\n const bodyInt8Array = new Int8Array(content);\r\n payloadInt8Array.set(bodyInt8Array, 2 + headerLength);\r\n }\r\n\r\n const payload: ArrayBuffer = payloadInt8Array.buffer;\r\n\r\n deferral.resolve(new RawWebsocketMessage(MessageType.Binary, payload, message.id));\r\n }\r\n } catch (e) {\r\n deferral.reject(`Error formatting the message. ${e}`);\r\n }\r\n\r\n return deferral.promise;\r\n }\r\n\r\n private makeHeaders = (message: ConnectionMessage): string => {\r\n let headersString: string = \"\";\r\n\r\n if (message.headers) {\r\n for (const header in message.headers) {\r\n if (header) {\r\n headersString += `${header}: ${message.headers[header]}${CRLF}`;\r\n }\r\n }\r\n }\r\n\r\n return headersString;\r\n }\r\n\r\n private parseHeaders = (headersString: string): IStringDictionary<string> => {\r\n const headers: IStringDictionary<string> = {};\r\n\r\n if (headersString) {\r\n const headerMatches = headersString.match(/[^\\r\\n]+/g);\r\n if (headers) {\r\n for (const header of headerMatches) {\r\n if (header) {\r\n const separatorIndex = header.indexOf(\":\");\r\n const headerName = separatorIndex > 0 ? header.substr(0, separatorIndex).trim().toLowerCase() : header;\r\n const headerValue =\r\n separatorIndex > 0 && header.length > (separatorIndex + 1) ?\r\n header.substr(separatorIndex + 1).trim() :\r\n \"\";\r\n\r\n headers[headerName] = headerValue;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return headers;\r\n }\r\n\r\n private stringToArrayBuffer = (str: string): ArrayBuffer => {\r\n const buffer = new ArrayBuffer(str.length);\r\n const view = new DataView(buffer);\r\n for (let i = 0; i < str.length; i++) {\r\n view.setUint8(i, str.charCodeAt(i));\r\n }\r\n return buffer;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT license.\r\n\r\n// tslint:disable:max-classes-per-file\r\n\r\nimport {\r\n AudioSourceErrorEvent,\r\n AudioStreamNodeAttachedEvent,\r\n AudioStreamNodeAttachingEvent,\r\n AudioStreamNodeDetachedEvent,\r\n AudioStreamNodeErrorEvent,\r\n ConnectionEstablishedEvent,\r\n ConnectionEstablishErrorEvent,\r\n ConnectionMessageReceivedEvent,\r\n ConnectionStartEvent,\r\n IEventListener,\r\n IStringDictionary,\r\n PlatformEvent,\r\n} from \"../common/Exports\";\r\nimport { ConnectingToServiceEvent, RecognitionTriggeredEvent } from \"./RecognitionEvents\";\r\n\r\nexport interface ITelemetry {\r\n Metrics: IMetric[];\r\n ReceivedMessages: IStringDictionary<string[]>;\r\n}\r\n\r\nexport interface IMetric {\r\n End?: string;\r\n Error?: string;\r\n Id?: string;\r\n Name?: string;\r\n Start?: string;\r\n PhraseLatencyMs?: number[];\r\n FirstHypothesisLatencyMs?: number[];\r\n}\r\n\r\nexport class ServiceTelemetryListener implements IEventListener<PlatformEvent> {\r\n private privIsDisposed: boolean = false;\r\n\r\n private privRequestId: string;\r\n private privAudioSourceId: string;\r\n private privAudioNodeId: string;\r\n\r\n private privListeningTriggerMetric: IMetric = null;\r\n private privMicMetric: IMetric = null;\r\n private privConnectionEstablishMetric: IMetric = null;\r\n\r\n private privMicStartTime: string;\r\n\r\n private privConnectionId: string;\r\n private privConnectionStartTime: string;\r\n\r\n private privReceivedMessages: IStringDictionary<string[]>;\r\n private privPhraseLatencies: number[];\r\n private privHypothesisLatencies: number[];\r\n\r\n constructor(requestId: string, audioSourceId: string, audioNodeId: string) {\r\n this.privRequestId = requestId;\r\n this.privAudioSourceId = audioSourceId;\r\n this.privAudioNodeId = audioNodeId;\r\n\r\n this.privReceivedMessages = {};\r\n this.privPhraseLatencies = [];\r\n this.privHypothesisLatencies = [];\r\n }\r\n\r\n public phraseReceived(audioReceivedTime: number): void {\r\n if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it.\r\n this.privPhraseLatencies.push(Date.now() - audioReceivedTime);\r\n }\r\n }\r\n\r\n public hypothesisReceived(audioReceivedTime: number): void {\r\n if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it.\r\n this.privHypothesisLatencies.push(Date.now() - audioReceivedTime);\r\n }\r\n }\r\n\r\n public onEvent = (e: PlatformEvent): void => {\r\n if (this.privIsDisposed) {\r\n return;\r\n }\r\n\r\n if (e instanceof RecognitionTriggeredEvent && e.requestId === this.privRequestId) {\r\n this.privListeningTriggerMetric = {\r\n End: e.eventTime,\r\n Name: \"ListeningTrigger\",\r\n Start: e.eventTime,\r\n };\r\n }\r\n\r\n if (e instanceof AudioStreamNodeAttachingEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n this.privMicStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof AudioStreamNodeAttachedEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n this.privMicStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof AudioSourceErrorEvent && e.audioSourceId === this.privAudioSourceId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Error: e.error,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof AudioStreamNodeErrorEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Error: e.error,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof AudioStreamNodeDetachedEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {\r\n if (!this.privMicMetric) {\r\n this.privMicMetric = {\r\n End: e.eventTime,\r\n Name: \"Microphone\",\r\n Start: this.privMicStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectingToServiceEvent && e.requestId === this.privRequestId) {\r\n this.privConnectionId = e.sessionId;\r\n }\r\n\r\n if (e instanceof ConnectionStartEvent && e.connectionId === this.privConnectionId) {\r\n this.privConnectionStartTime = e.eventTime;\r\n }\r\n\r\n if (e instanceof ConnectionEstablishedEvent && e.connectionId === this.privConnectionId) {\r\n if (!this.privConnectionEstablishMetric) {\r\n this.privConnectionEstablishMetric = {\r\n End: e.eventTime,\r\n Id: this.privConnectionId,\r\n Name: \"Connection\",\r\n Start: this.privConnectionStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectionEstablishErrorEvent && e.connectionId === this.privConnectionId) {\r\n if (!this.privConnectionEstablishMetric) {\r\n this.privConnectionEstablishMetric = {\r\n End: e.eventTime,\r\n Error: this.getConnectionError(e.statusCode),\r\n Id: this.privConnectionId,\r\n Name: \"Connection\",\r\n Start: this.privConnectionStartTime,\r\n };\r\n }\r\n }\r\n\r\n if (e instanceof ConnectionMessageReceivedEvent && e.connectionId === this.privConnectionId) {\r\n if (e.message && e.message.headers && e.message.headers.path) {\r\n if (!this.privReceivedMessages[e.message.headers.path]) {\r\n this.privReceivedMessages[e.message.headers.path] = new Array<string>();\r\n }\r\n\r\n this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime);\r\n }\r\n }\r\n }\r\n\r\n public getTelemetry = (): string => {\r\n const metrics = new Array<IMetric>();\r\n\r\n if (this.privListeningTriggerMetric) {\r\n metrics.push(this.privListeningTriggerMetric);\r\n }\r\n\r\n if (this.privMicMetric) {\r\n metrics.push(this.privMicMetric);\r\n }\r\n\r\n if (this.privConnectionEstablishMetric) {\r\n metrics.push(this.privConnectionEstablishMetric);\r\n }\r\n\r\n if (this.privPhraseLatencies.length > 0) {\r\n metrics.push({\r\n PhraseLatencyMs: this.privPhraseLatencies,\r\n });\r\n }\r\n\r\n if (this.privHypothesisLatencies.length > 0) {\r\n metrics.push({\r\n FirstHypothesisLatencyMs: this.privHypothesisLatencies,\r\n });\r\n }\r\n\r\n const telemetry: ITelemetry = {\r\n Metrics: metrics,\r\n ReceivedMessages: this.privReceivedMessages,\r\n };\r\n\r\n const json = JSON.stringify(telemetry);\r\n\r\n // We dont want to send the same telemetry again. So clean those out.\r\n this.privReceivedMessages = {};\r\n this.privListeningTriggerMetric = null;\r\n this.privMicMetric = null;\r\n this.privConnectionEstablishMetric = null;\r\n this.privPhraseLatencies = [];\r\n this.privHypothesisLatencies = [];\r\n return json;\r\n }\r\n\r\n // Determines if there are any telemetry events to send to the service.\r\n public get hasTelemetry(): boolean {\r\n return (Object.keys(this.privReceivedMessages).length !== 0 ||\r\n this.privListeningTriggerMetric !== null ||\r\n this.privMicMetric !== null ||\r\n this.privConnectionEstablishMetric !== null ||\r\n this.privPhraseLatencies.length !== 0 ||\r\n this.privHypothesisLatencies.length !== 0);\r\n }\r\n\r\n public dispose = (): void => {\r\n this.privIsDisposed = true;\r\n }\r\n\r\n private getConnectionError = (statusCode: number): string => {\r\n /*\r\n -- Websocket status codes --\r\n NormalClosure = 1000,\r\n EndpointUnavailable = 1001,\r\n ProtocolError = 1002,\r\n InvalidMessageType = 1003,\r\n Empty = 1005,\r\n InvalidPayloadData = 1007,\r\n PolicyViolation = 1008,\r\n MessageTooBig = 1009,\r\n MandatoryExtension = 1010,\r\n InternalServerError = 1011\r\n */\r\n\r\n switch (statusCode) {\r\n case 400:\r\n case 1002:\r\n case 1003:\r\n case 1005:\r\n case 1007:\r\n case 1008:\r\n case 1009: return \"BadRequest\";\r\n case 401: return \"Unauthorized\";\r\n case 403: return \"Forbidden\";\r\n case 503:\r\n case 1001: return \"ServerUnavailable\";\r\n case 500:\r\n case 1011: return \"ServerError\";\r\n case 408:\r\n case 504: return \"Timeout\";\r\n default: return \"statuscode:\" + statusCode.toString();\r\n }\r\n }\r\n}\r\n","import { type AudioConfig as AudioConfigType } from 'microsoft-cognitiveservices-speech-sdk';\nimport { parse } from 'valibot';\n\nimport resolveFunctionOrReturnValue from './resolveFunctionOrReturnValue';\nimport SpeechSDK from './SpeechSDK';\nimport credentialsSchema, { type Credentials } from './SpeechToText/validation/credentialsSchema';\nimport enableTelemetrySchema, { EnableTelemetry } from './SpeechToText/validation/enableTelemetrySchema';\nimport initialSilenceTimeoutSchema, {\n InitialSilenceTimeout\n} from './SpeechToText/validation/initialSilenceTimeoutSchema';\nimport looseEventsSchema, { LooseEvents } from './SpeechToText/validation/looseEventsSchema';\nimport referenceGrammarsSchema, { ReferenceGrammars } from './SpeechToText/validation/referenceGrammarsSchema';\nimport speechRecognitionEndpointIdSchema, {\n SpeechRecognitionEndpointId\n} from './SpeechToText/validation/speechRecognitionEndpointIdSchema';\nimport textNormalizationSchema, { TextNormalization } from './SpeechToText/validation/textNormalizationSchema';\n\nconst { AudioConfig } = SpeechSDK;\n\nlet shouldWarnOnSubscriptionKey = true;\n\ntype PatchOptionsInit = {\n audioConfig?: AudioConfigType | undefined;\n credentials: (() => Credentials | Promise<Credentials>) | Credentials | Promise<Credentials>;\n enableTelemetry?: boolean | undefined;\n initialSilenceTimeout?: number | undefined;\n looseEvent?: boolean | undefined;\n looseEvents?: boolean | undefined;\n referenceGrammars?: readonly string[] | undefined;\n speechRecognitionEndpointId?: string | undefined;\n textNormalization?: 'display' | 'itn' | 'lexical' | 'maskeditn' | undefined;\n};\n\ntype PatchedOptions = Readonly<{\n audioConfig: AudioConfigType;\n enableTelemetry: EnableTelemetry;\n fetchCredentials: () => Promise<Credentials>;\n initialSilenceTimeout: InitialSilenceTimeout;\n looseEvents: LooseEvents;\n referenceGrammars: ReferenceGrammars;\n speechRecognitionEndpointId: SpeechRecognitionEndpointId;\n textNormalization: TextNormalization;\n}>;\n\nexport default function patchOptions(init: PatchOptionsInit): PatchedOptions {\n const {\n audioConfig,\n credentials,\n enableTelemetry,\n initialSilenceTimeout,\n looseEvent,\n referenceGrammars,\n speechRecognitionEndpointId,\n textNormalization\n } = init;\n\n let { looseEvents } = init;\n\n if (typeof looseEvent !== 'undefined') {\n console.warn('web-speech-cognitive-services: The option \"looseEvent\" should be named as \"looseEvents\".');\n\n looseEvents = looseEvent;\n }\n\n return Object.freeze({\n audioConfig: audioConfig || AudioConfig.fromDefaultMicrophoneInput(),\n // We set telemetry to true to honor the default telemetry settings of Speech SDK\n // https://github.com/Microsoft/cognitive-services-speech-sdk-js#data--telemetry\n enableTelemetry: parse(enableTelemetrySchema, enableTelemetry),\n fetchCredentials: async () => {\n const parsedCredentials = parse(credentialsSchema, await resolveFunctionOrReturnValue<Credentials>(credentials));\n\n if (shouldWarnOnSubscriptionKey && parsedCredentials.subscriptionKey) {\n console.warn(\n 'web-speech-cognitive-services: In production environment, subscription key should not be used, authorization token should be used instead.'\n );\n\n shouldWarnOnSubscriptionKey = false;\n }\n\n return parsedCredentials;\n },\n initialSilenceTimeout: parse(initialSilenceTimeoutSchema, initialSilenceTimeout),\n looseEvents: parse(looseEventsSchema, looseEvents),\n referenceGrammars: parse(referenceGrammarsSchema, referenceGrammars),\n speechRecognitionEndpointId: parse(speechRecognitionEndpointIdSchema, speechRecognitionEndpointId),\n textNormalization: parse(textNormalizationSchema, textNormalization)\n });\n}\n\nexport type { Credentials, PatchedOptions, PatchOptionsInit };\n","/* eslint no-magic-numbers: [\"error\", { \"ignore\": [0, 1, 100] }] */\n\n// Cognitive Services does not support unsigned percentage\n// It must be converted into +/- first.\nfunction relativePercentage(value) {\n let relative = Math.round((value - 1) * 100);\n\n if (relative >= 0) {\n relative = '+' + relative;\n }\n\n return relative + '%';\n}\n\nexport default function buildSSML({ lang, pitch = 1, rate = 1, text, voice, volume }) {\n return `<speak version=\"1.0\" xml:lang=\"${lang}\">\n <voice xml:lang=\"${lang}\" name=\"${voice}\">\n <prosody pitch=\"${relativePercentage(pitch)}\" rate=\"${relativePercentage(rate)}\" volume=\"${relativePercentage(\n volume\n )}\">\n ${text}\n </prosody>\n </voice>\n</speak>`;\n}\n","import { WebSpeechPonyfillFactory } from 'botframework-webchat-api';\nimport { AudioConfig } from 'microsoft-cognitiveservices-speech-sdk';\nimport { createSpeechServicesPonyfill } from 'web-speech-cognitive-services';\n\nimport createMicrophoneAudioConfigAndAudioContext from './speech/createMicrophoneAudioConfigAndAudioContext';\nimport CognitiveServicesAudioOutputFormat from './types/CognitiveServicesAudioOutputFormat';\nimport CognitiveServicesCredentials from './types/CognitiveServicesCredentials';\nimport CognitiveServicesTextNormalization from './types/CognitiveServicesTextNormalization';\n\nexport default function createCognitiveServicesSpeechServicesPonyfillFactory({\n audioConfig,\n audioContext,\n audioInputDeviceId,\n credentials,\n enableTelemetry,\n initialSilenceTimeout,\n speechRecognitionEndpointId,\n speechSynthesisDeploymentId,\n speechSynthesisOutputFormat,\n textNormalization\n}: {\n audioConfig?: AudioConfig;\n audioContext?: AudioContext;\n audioInputDeviceId?: string;\n credentials: CognitiveServicesCredentials;\n enableTelemetry?: true;\n initialSilenceTimeout?: number | undefined;\n speechRecognitionEndpointId?: string;\n speechSynthesisDeploymentId?: string;\n speechSynthesisOutputFormat?: CognitiveServicesAudioOutputFormat;\n textNormalization?: CognitiveServicesTextNormalization;\n}): WebSpeechPonyfillFactory {\n if (!window.navigator.mediaDevices && !audioConfig) {\n console.warn(\n 'botframework-webchat: Your browser does not support Web Audio or the page is not loaded via HTTPS or localhost. Cognitive Services Speech Services is disabled. However, you may pass a custom AudioConfig to enable speech in this environment.'\n );\n\n return () => ({});\n }\n\n if (audioConfig) {\n audioInputDeviceId &&\n console.warn(\n 'botframework-webchat: \"audioConfig\" and \"audioInputDeviceId\" cannot be set at the same time; ignoring \"audioInputDeviceId\".'\n );\n\n audioContext &&\n console.warn(\n 'botframework-webchat: \"audioConfig\" and \"audioContext\" cannot be set at the same time; ignoring \"audioContext\" for speech recognition.'\n );\n } else {\n ({ audioConfig, audioContext } = createMicrophoneAudioConfigAndAudioContext({\n audioContext,\n audioInputDeviceId,\n enableTelemetry\n }));\n }\n\n return ({ referenceGrammarID } = {}) => {\n const { SpeechGrammarList, SpeechRecognition, speechSynthesis, SpeechSynthesisUtterance } =\n createSpeechServicesPonyfill({\n audioConfig,\n audioContext,\n credentials,\n enableTelemetry,\n initialSilenceTimeout,\n referenceGrammars: referenceGrammarID ? [`luis/${referenceGrammarID}-PRODUCTION`] : [],\n speechRecognitionEndpointId,\n speechSynthesisDeploymentId,\n speechSynthesisOutputFormat,\n textNormalization\n });\n\n return {\n resumeAudioContext: () => audioContext && audioContext.state === 'suspended' && audioContext.resume(),\n SpeechGrammarList,\n SpeechRecognition,\n speechSynthesis,\n SpeechSynthesisUtterance\n };\n };\n}\n"]}
|