1 (function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3 typeof define === 'function' && define.amd ? define(['exports'], factory) :
4 (global = global || self, factory(global.doc = {}));
5 }(this, (function (exports) { 'use strict';
13 function concat(parts) {
14 // access the internals of a document directly.
15 // if(parts.length === 1) {
16 // // If it's a single document, no need to concat it.
27 * @param {Doc} contents
32 function indent(contents) {
41 * @param {Doc} contents
46 function align(n, contents) {
55 * @param {Doc} contents
56 * @param {object} [opts] - TBD ???
61 function group(contents, opts) {
68 break: !!opts.shouldBreak,
69 expandedStates: opts.expandedStates
73 * @param {Doc} contents
78 function dedentToRoot(contents) {
79 return align(-Infinity, contents);
82 * @param {Doc} contents
87 function markAsRoot(contents) {
88 // @ts-ignore - TBD ???:
94 * @param {Doc} contents
99 function dedent(contents) {
100 return align(-1, contents);
103 * @param {Doc[]} states
104 * @param {object} [opts] - TBD ???
109 function conditionalGroup(states, opts) {
110 return group(states[0], Object.assign({}, opts, {
111 expandedStates: states
115 * @param {Doc[]} parts
120 function fill(parts) {
128 * @param {Doc} [breakContents]
129 * @param {Doc} [flatContents]
130 * @param {object} [opts] - TBD ???
135 function ifBreak(breakContents, flatContents, opts) {
142 groupId: opts.groupId
146 * @param {Doc} contents
151 function lineSuffix(contents) {
159 const lineSuffixBoundary = {
160 type: "line-suffix-boundary"
162 const breakParent = {
175 const hardline = concat([{
179 const literalline = concat([{
186 placeholder: Symbol("cursor")
194 function join(sep, arr) {
197 for (let i = 0; i < arr.length; i++) {
209 * @param {number} size
210 * @param {number} tabWidth
214 function addAlignmentToDoc(doc, size, tabWidth) {
218 // Use indent to add tabs for all the levels of tabs we need
219 for (let i = 0; i < Math.floor(size / tabWidth); ++i) {
220 aligned = indent(aligned);
221 } // Use align for all the spaces that are needed
224 aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current
225 // indentation, so we use -Infinity to reset the indentation to 0
227 aligned = align(-Infinity, aligned);
260 const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
261 return new RegExp(pattern, onlyFirst ? undefined : 'g');
264 var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
266 /* eslint-disable yoda */
268 const isFullwidthCodePoint = codePoint => {
269 if (Number.isNaN(codePoint)) {
271 } // Code points are derived from:
272 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
275 if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo
276 codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
277 codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
278 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
279 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
280 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals
281 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A
282 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables
283 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs
284 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms
285 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants
286 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms
287 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement
288 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement
289 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
290 0x20000 <= codePoint && codePoint <= 0x3FFFD)) {
297 var isFullwidthCodePoint_1 = isFullwidthCodePoint;
298 var default_1 = isFullwidthCodePoint;
299 isFullwidthCodePoint_1.default = default_1;
301 var emojiRegex = function emojiRegex() {
302 // https://mths.be/emoji
303 return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
306 const stringWidth = string => {
307 string = string.replace(emojiRegex(), ' ');
309 if (typeof string !== 'string' || string.length === 0) {
313 string = stripAnsi(string);
316 for (let i = 0; i < string.length; i++) {
317 const code = string.codePointAt(i); // Ignore control characters
319 if (code <= 0x1F || code >= 0x7F && code <= 0x9F) {
321 } // Ignore combining characters
324 if (code >= 0x300 && code <= 0x36F) {
333 width += isFullwidthCodePoint_1(code) ? 2 : 1;
339 var stringWidth_1 = stringWidth; // TODO: remove this in the next major version
341 var default_1$1 = stringWidth;
342 stringWidth_1.default = default_1$1;
344 const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
346 var escapeStringRegexp = string => {
347 if (typeof string !== 'string') {
348 throw new TypeError('Expected a string');
351 return string.replace(matchOperatorsRegex, '\\$&');
354 var getLast = arr => arr[arr.length - 1];
356 const notAsciiRegex = /[^\x20-\x7F]/;
358 function getPenultimate(arr) {
359 if (arr.length > 1) {
360 return arr[arr.length - 2];
366 * @typedef {{backwards?: boolean}} SkipOptions
370 * @param {string | RegExp} chars
371 * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false}
375 function skip(chars) {
376 return (text, index, opts) => {
377 const backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having
378 // to check for failures (did someone say monads?).
380 if (index === false) {
389 while (cursor >= 0 && cursor < length) {
390 const c = text.charAt(cursor);
392 if (chars instanceof RegExp) {
393 if (!chars.test(c)) {
396 } else if (!chars.includes(c)) {
400 backwards ? cursor-- : cursor++;
403 if (cursor === -1 || cursor === length) {
404 // If we reached the beginning or end of the file, return the
405 // out-of-bounds cursor. It's up to the caller to handle this
406 // correctly. We don't want to indicate `false` though if it
407 // actually skipped valid characters.
415 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
419 const skipWhitespace = skip(/\s/);
421 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
424 const skipSpaces = skip(" \t");
426 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
429 const skipToLineEnd = skip(",; \t");
431 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
434 const skipEverythingButNewLine = skip(/[^\r\n]/);
436 * @param {string} text
437 * @param {number | false} index
438 * @returns {number | false}
441 function skipInlineComment(text, index) {
442 if (index === false) {
446 if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") {
447 for (let i = index + 2; i < text.length; ++i) {
448 if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") {
457 * @param {string} text
458 * @param {number | false} index
459 * @returns {number | false}
463 function skipTrailingComment(text, index) {
464 if (index === false) {
468 if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") {
469 return skipEverythingButNewLine(text, index);
473 } // This one doesn't use the above helper function because it wants to
474 // test \r\n in order and `skip` doesn't support ordering and we only
475 // want to skip one newline. It's simple to implement.
478 * @param {string} text
479 * @param {number | false} index
480 * @param {SkipOptions=} opts
481 * @returns {number | false}
485 function skipNewline(text, index, opts) {
486 const backwards = opts && opts.backwards;
488 if (index === false) {
492 const atIndex = text.charAt(index);
495 if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
499 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
503 if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
507 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
515 * @param {string} text
516 * @param {number} index
517 * @param {SkipOptions=} opts
522 function hasNewline(text, index, opts) {
524 const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
525 const idx2 = skipNewline(text, idx, opts);
529 * @param {string} text
530 * @param {number} start
531 * @param {number} end
536 function hasNewlineInRange(text, start, end) {
537 for (let i = start; i < end; ++i) {
538 if (text.charAt(i) === "\n") {
544 } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty
548 * @param {string} text
550 * @param {(node: N) => number} locStart
554 function isPreviousLineEmpty(text, node, locStart) {
555 /** @type {number | false} */
556 let idx = locStart(node) - 1;
557 idx = skipSpaces(text, idx, {
560 idx = skipNewline(text, idx, {
563 idx = skipSpaces(text, idx, {
566 const idx2 = skipNewline(text, idx, {
572 * @param {string} text
573 * @param {number} index
578 function isNextLineEmptyAfterIndex(text, index) {
579 /** @type {number | false} */
581 /** @type {number | false} */
585 while (idx !== oldIdx) {
586 // We need to skip all the potential trailing inline comments
588 idx = skipToLineEnd(text, idx);
589 idx = skipInlineComment(text, idx);
590 idx = skipSpaces(text, idx);
593 idx = skipTrailingComment(text, idx);
594 idx = skipNewline(text, idx);
595 return idx !== false && hasNewline(text, idx);
599 * @param {string} text
601 * @param {(node: N) => number} locEnd
606 function isNextLineEmpty(text, node, locEnd) {
607 return isNextLineEmptyAfterIndex(text, locEnd(node));
610 * @param {string} text
611 * @param {number} idx
612 * @returns {number | false}
616 function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
617 /** @type {number | false} */
619 /** @type {number | false} */
623 while (nextIdx !== oldIdx) {
625 nextIdx = skipSpaces(text, nextIdx);
626 nextIdx = skipInlineComment(text, nextIdx);
627 nextIdx = skipTrailingComment(text, nextIdx);
628 nextIdx = skipNewline(text, nextIdx);
635 * @param {string} text
637 * @param {(node: N) => number} locEnd
638 * @returns {number | false}
642 function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
643 return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
647 * @param {string} text
649 * @param {(node: N) => number} locEnd
654 function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
655 return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback?
656 getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
659 * @param {string} text
660 * @param {number} index
661 * @param {SkipOptions=} opts
666 function hasSpaces(text, index, opts) {
668 const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
669 return idx !== index;
672 * @param {{range?: [number, number], start?: number}} node
673 * @param {number} index
677 function setLocStart(node, index) {
679 node.range[0] = index;
685 * @param {{range?: [number, number], end?: number}} node
686 * @param {number} index
690 function setLocEnd(node, index) {
692 node.range[1] = index;
698 const PRECEDENCE = {};
699 [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach((tier, i) => {
705 function getPrecedence(op) {
706 return PRECEDENCE[op];
709 const equalityOperators = {
715 const multiplicativeOperators = {
720 const bitshiftOperators = {
726 function shouldFlatten(parentOp, nodeOp) {
727 if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) {
729 } // ** is right-associative
730 // x ** y ** z --> x ** (y ** z)
733 if (parentOp === "**") {
735 } // x == y == z --> (x == y) == z
738 if (equalityOperators[parentOp] && equalityOperators[nodeOp]) {
740 } // x * y % z --> (x * y) % z
743 if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) {
745 } // x * y / z --> (x * y) / z
746 // x / y * z --> (x / y) * z
749 if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) {
751 } // x << y << z --> (x << y) << z
754 if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) {
761 function isBitwiseOperator(operator) {
762 return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&";
763 } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr
764 // holds) `function`, `class`, or `do {}`. Will be overzealous if there's
765 // already necessary grouping parentheses.
768 function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) {
769 node = getLeftMost(node);
772 case "FunctionExpression":
773 case "ClassExpression":
775 return forbidFunctionClassAndDoExpr;
777 case "ObjectExpression":
780 case "MemberExpression":
781 case "OptionalMemberExpression":
782 return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
784 case "TaggedTemplateExpression":
785 if (node.tag.type === "FunctionExpression") {
786 // IIFEs are always already parenthesized
790 return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr);
792 case "CallExpression":
793 case "OptionalCallExpression":
794 if (node.callee.type === "FunctionExpression") {
795 // IIFEs are always already parenthesized
799 return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr);
801 case "ConditionalExpression":
802 return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr);
804 case "UpdateExpression":
805 return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr);
807 case "BindExpression":
808 return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
810 case "SequenceExpression":
811 return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr);
813 case "TSAsExpression":
814 return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr);
821 function getLeftMost(node) {
823 return getLeftMost(node.left);
829 * @param {string} value
830 * @param {number} tabWidth
831 * @param {number=} startIndex
836 function getAlignmentSize(value, tabWidth, startIndex) {
837 startIndex = startIndex || 0;
840 for (let i = startIndex; i < value.length; ++i) {
841 if (value[i] === "\t") {
842 // Tabs behave in a way that they are aligned to the nearest
843 // multiple of tabWidth:
844 // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
845 // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
846 size = size + tabWidth - size % tabWidth;
855 * @param {string} value
856 * @param {number} tabWidth
861 function getIndentSize(value, tabWidth) {
862 const lastNewlineIndex = value.lastIndexOf("\n");
864 if (lastNewlineIndex === -1) {
868 return getAlignmentSize( // All the leading whitespaces
869 value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth);
872 * @typedef {'"' | "'"} Quote
877 * @param {string} raw
878 * @param {Quote} preferredQuote
883 function getPreferredQuote(raw, preferredQuote) {
884 // `rawContent` is the string exactly like it appeared in the input source
885 // code, without its enclosing quotes.
886 const rawContent = raw.slice(1, -1);
887 /** @type {{ quote: '"', regex: RegExp }} */
893 /** @type {{ quote: "'", regex: RegExp }} */
899 const preferred = preferredQuote === "'" ? single : double;
900 const alternate = preferred === single ? double : single;
901 let result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing
902 // the string, we might want to enclose with the alternate quote instead, to
903 // minimize the number of escaped quotes.
905 if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) {
906 const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
907 const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
908 result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote;
914 function printString(raw, options, isDirectiveLiteral) {
915 // `rawContent` is the string exactly like it appeared in the input source
916 // code, without its enclosing quotes.
917 const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
918 // the quotes on a DirectiveLiteral.
920 const canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'");
923 const enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't
924 // change the escape sequences they use.
925 // See https://github.com/prettier/prettier/issues/1555
926 // and https://tc39.github.io/ecma262/#directive-prologue
928 if (isDirectiveLiteral) {
929 if (canChangeDirectiveQuotes) {
930 return enclosingQuote + rawContent + enclosingQuote;
934 } // It might sound unnecessary to use `makeString` even if the string already
935 // is enclosed with `enclosingQuote`, but it isn't. The string could contain
936 // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
937 // sure that we consistently output the minimum amount of escaped quotes.
940 return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml));
943 * @param {string} rawContent
944 * @param {Quote} enclosingQuote
945 * @param {boolean=} unescapeUnnecessaryEscapes
950 function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) {
951 const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double).
953 const regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to
954 // enclose `rawContent` with `enclosingQuote`.
956 const newContent = rawContent.replace(regex, (match, escaped, quote) => {
957 // If we matched an escape, and the escaped character is a quote of the
958 // other type than we intend to enclose the string with, there's no need for
959 // it to be escaped, so return it _without_ the backslash.
960 if (escaped === otherQuote) {
962 } // If we matched an unescaped quote and it is of the _same_ type as we
963 // intend to enclose the string with, it must be escaped, so return it with
967 if (quote === enclosingQuote) {
973 } // Unescape any unnecessarily escaped character.
974 // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27
977 return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped;
979 return enclosingQuote + newContent + enclosingQuote;
982 function printNumber(rawNumber) {
983 return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation.
984 .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0).
985 .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit.
986 .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes.
987 .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot.
988 .replace(/\.(?=e|$)/, "");
991 * @param {string} str
992 * @param {string} target
997 function getMaxContinuousCount(str, target) {
998 const results = str.match(new RegExp("(".concat(escapeStringRegexp(target), ")+"), "g"));
1000 if (results === null) {
1004 return results.reduce((maxCount, result) => Math.max(maxCount, result.length / target.length), 0);
1007 function getMinNotPresentContinuousCount(str, target) {
1008 const matches = str.match(new RegExp("(".concat(escapeStringRegexp(target), ")+"), "g"));
1010 if (matches === null) {
1014 const countPresent = new Map();
1017 for (const match of matches) {
1018 const count = match.length / target.length;
1019 countPresent.set(count, true);
1026 for (let i = 1; i < max; i++) {
1027 if (!countPresent.get(i)) {
1035 * @param {string} text
1040 function getStringWidth(text) {
1043 } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
1046 if (!notAsciiRegex.test(text)) {
1050 return stringWidth_1(text);
1053 function hasIgnoreComment(path) {
1054 const node = path.getValue();
1055 return hasNodeIgnoreComment(node);
1058 function hasNodeIgnoreComment(node) {
1059 return node && (node.comments && node.comments.length > 0 && node.comments.some(comment => isNodeIgnoreComment(comment) && !comment.unignore) || node.prettierIgnore);
1062 function isNodeIgnoreComment(comment) {
1063 return comment.value.trim() === "prettier-ignore";
1066 function addCommentHelper(node, comment) {
1067 const comments = node.comments || (node.comments = []);
1068 comments.push(comment);
1069 comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment
1070 // We already "print" it via the raw text, we don't need to re-print it as a
1073 if (node.type === "JSXText") {
1074 comment.printed = true;
1078 function addLeadingComment(node, comment) {
1079 comment.leading = true;
1080 comment.trailing = false;
1081 addCommentHelper(node, comment);
1084 function addDanglingComment(node, comment) {
1085 comment.leading = false;
1086 comment.trailing = false;
1087 addCommentHelper(node, comment);
1090 function addTrailingComment(node, comment) {
1091 comment.leading = false;
1092 comment.trailing = true;
1093 addCommentHelper(node, comment);
1096 function isWithinParentArrayProperty(path, propertyName) {
1097 const node = path.getValue();
1098 const parent = path.getParentNode();
1100 if (parent == null) {
1104 if (!Array.isArray(parent[propertyName])) {
1108 const key = path.getName();
1109 return parent[propertyName][key] === node;
1112 function replaceEndOfLineWith(text, replacement) {
1115 for (const part of text.split("\n")) {
1116 if (parts.length !== 0) {
1117 parts.push(replacement);
1127 replaceEndOfLineWith,
1129 getMaxContinuousCount,
1130 getMinNotPresentContinuousCount,
1136 getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
1137 getNextNonSpaceNonCommentCharacterIndex,
1138 getNextNonSpaceNonCommentCharacter,
1143 skipEverythingButNewLine,
1145 skipTrailingComment,
1147 isNextLineEmptyAfterIndex,
1149 isPreviousLineEmpty,
1155 startsWithNoLookaheadToken,
1162 hasNodeIgnoreComment,
1163 isNodeIgnoreComment,
1168 isWithinParentArrayProperty
1171 function guessEndOfLine(text) {
1172 const index = text.indexOf("\r");
1175 return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
1181 function convertEndOfLineToChars(value) {
1196 convertEndOfLineToChars
1200 getStringWidth: getStringWidth$1
1203 convertEndOfLineToChars: convertEndOfLineToChars$1
1210 /** @type {Record<symbol, typeof MODE_BREAK | typeof MODE_FLAT>} */
1213 const MODE_BREAK = 1;
1214 const MODE_FLAT = 2;
1216 function rootIndent() {
1224 function makeIndent(ind, options) {
1225 return generateInd(ind, {
1230 function makeAlign(ind, n, options) {
1231 return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, {
1233 }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, {
1235 }) : typeof n === "string" ? generateInd(ind, {
1236 type: "stringAlign",
1238 }, options) : generateInd(ind, {
1239 type: "numberAlign",
1244 function generateInd(ind, newPart, options) {
1245 const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart);
1251 for (const part of queue) {
1252 switch (part.type) {
1256 if (options.useTabs) {
1259 addSpaces(options.tabWidth);
1267 length += part.n.length;
1272 lastSpaces += part.n;
1275 /* istanbul ignore next */
1278 throw new Error("Unexpected type '".concat(part.type, "'"));
1283 return Object.assign({}, ind, {
1289 function addTabs(count) {
1290 value += "\t".repeat(count);
1291 length += options.tabWidth * count;
1294 function addSpaces(count) {
1295 value += " ".repeat(count);
1300 if (options.useTabs) {
1307 function flushTabs() {
1315 function flushSpaces() {
1316 if (lastSpaces > 0) {
1317 addSpaces(lastSpaces);
1323 function resetLast() {
1329 function trim$1(out) {
1330 if (out.length === 0) {
1334 let trimCount = 0; // Trim whitespace at the end of line
1336 while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) {
1337 trimCount += out.pop().length;
1340 if (out.length && typeof out[out.length - 1] === "string") {
1341 const trimmed = out[out.length - 1].replace(/[ \t]*$/, "");
1342 trimCount += out[out.length - 1].length - trimmed.length;
1343 out[out.length - 1] = trimmed;
1349 function fits(next, restCommands, width, options, mustBeFlat) {
1350 let restIdx = restCommands.length;
1351 const cmds = [next]; // `out` is only used for width counting because `trim` requires to look
1352 // backwards for space characters.
1356 while (width >= 0) {
1357 if (cmds.length === 0) {
1358 if (restIdx === 0) {
1362 cmds.push(restCommands[restIdx - 1]);
1367 const [ind, mode, doc] = cmds.pop();
1369 if (typeof doc === "string") {
1371 width -= getStringWidth$1(doc);
1375 for (let i = doc.parts.length - 1; i >= 0; i--) {
1376 cmds.push([ind, mode, doc.parts[i]]);
1382 cmds.push([makeIndent(ind, options), mode, doc.contents]);
1386 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
1390 width += trim$1(out);
1394 if (mustBeFlat && doc.break) {
1398 cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
1401 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
1407 for (let i = doc.parts.length - 1; i >= 0; i--) {
1408 cmds.push([ind, mode, doc.parts[i]]);
1415 const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
1417 if (groupMode === MODE_BREAK) {
1418 if (doc.breakContents) {
1419 cmds.push([ind, mode, doc.breakContents]);
1423 if (groupMode === MODE_FLAT) {
1424 if (doc.flatContents) {
1425 cmds.push([ind, mode, doc.flatContents]);
1459 function printDocToString(doc, options) {
1461 const width = options.printWidth;
1462 const newLine = convertEndOfLineToChars$1(options.endOfLine);
1463 let pos = 0; // cmds is basically a stack. We've turned a recursive call into a
1464 // while loop which is much faster. The while loop below adds new
1465 // cmds to the array instead of recursively calling `print`.
1467 const cmds = [[rootIndent(), MODE_BREAK, doc]];
1469 let shouldRemeasure = false;
1470 let lineSuffix = [];
1472 while (cmds.length !== 0) {
1473 const [ind, mode, doc] = cmds.pop();
1475 if (typeof doc === "string") {
1476 const formatted = newLine !== "\n" && doc.includes("\n") ? doc.replace(/\n/g, newLine) : doc;
1477 out.push(formatted);
1478 pos += getStringWidth$1(formatted);
1482 out.push(cursor$1.placeholder);
1486 for (let i = doc.parts.length - 1; i >= 0; i--) {
1487 cmds.push([ind, mode, doc.parts[i]]);
1493 cmds.push([makeIndent(ind, options), mode, doc.contents]);
1497 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
1507 if (!shouldRemeasure) {
1508 cmds.push([ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents]);
1516 shouldRemeasure = false;
1517 const next = [ind, MODE_FLAT, doc.contents];
1518 const rem = width - pos;
1520 if (!doc.break && fits(next, cmds, rem, options)) {
1523 // Expanded states are a rare case where a document
1524 // can manually provide multiple representations of
1525 // itself. It provides an array of documents
1526 // going from the least expanded (most flattened)
1527 // representation first to the most expanded. If a
1528 // group has these, we need to manually go through
1529 // these states and find the first one that fits.
1530 if (doc.expandedStates) {
1531 const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1];
1534 cmds.push([ind, MODE_BREAK, mostExpanded]);
1537 for (let i = 1; i < doc.expandedStates.length + 1; i++) {
1538 if (i >= doc.expandedStates.length) {
1539 cmds.push([ind, MODE_BREAK, mostExpanded]);
1542 const state = doc.expandedStates[i];
1543 const cmd = [ind, MODE_FLAT, state];
1545 if (fits(cmd, cmds, rem, options)) {
1553 cmds.push([ind, MODE_BREAK, doc.contents]);
1562 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
1566 // Fills each line with as much code as possible before moving to a new
1567 // line with the same indentation.
1569 // Expects doc.parts to be an array of alternating content and
1570 // whitespace. The whitespace contains the linebreaks.
1573 // ["I", line, "love", line, "monkeys"]
1575 // [{ type: group, ... }, softline, { type: group, ... }]
1577 // It uses this parts structure to handle three main layout cases:
1578 // * The first two content items fit on the same line without
1580 // -> output the first content item and the whitespace "flat".
1581 // * Only the first content item fits on the line without breaking
1582 // -> output the first content item "flat" and the whitespace with
1584 // * Neither content item fits on the line without breaking
1585 // -> output the first content item and the whitespace with "break".
1589 const rem = width - pos;
1594 if (parts.length === 0) {
1598 const [content, whitespace] = parts;
1599 const contentFlatCmd = [ind, MODE_FLAT, content];
1600 const contentBreakCmd = [ind, MODE_BREAK, content];
1601 const contentFits = fits(contentFlatCmd, [], rem, options, true);
1603 if (parts.length === 1) {
1605 cmds.push(contentFlatCmd);
1607 cmds.push(contentBreakCmd);
1613 const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace];
1614 const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace];
1616 if (parts.length === 2) {
1618 cmds.push(whitespaceFlatCmd);
1619 cmds.push(contentFlatCmd);
1621 cmds.push(whitespaceBreakCmd);
1622 cmds.push(contentBreakCmd);
1626 } // At this point we've handled the first pair (context, separator)
1627 // and will create a new fill doc for the rest of the content.
1628 // Ideally we wouldn't mutate the array here but copying all the
1629 // elements to a new array would make this algorithm quadratic,
1630 // which is unusable for large arrays (e.g. large texts in JSX).
1634 const remainingCmd = [ind, mode, fill$1(parts)];
1635 const secondContent = parts[0];
1636 const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])];
1637 const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, true);
1639 if (firstAndSecondContentFits) {
1640 cmds.push(remainingCmd);
1641 cmds.push(whitespaceFlatCmd);
1642 cmds.push(contentFlatCmd);
1643 } else if (contentFits) {
1644 cmds.push(remainingCmd);
1645 cmds.push(whitespaceBreakCmd);
1646 cmds.push(contentFlatCmd);
1648 cmds.push(remainingCmd);
1649 cmds.push(whitespaceBreakCmd);
1650 cmds.push(contentBreakCmd);
1658 const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
1660 if (groupMode === MODE_BREAK) {
1661 if (doc.breakContents) {
1662 cmds.push([ind, mode, doc.breakContents]);
1666 if (groupMode === MODE_FLAT) {
1667 if (doc.flatContents) {
1668 cmds.push([ind, mode, doc.flatContents]);
1676 lineSuffix.push([ind, mode, doc.contents]);
1679 case "line-suffix-boundary":
1680 if (lineSuffix.length > 0) {
1681 cmds.push([ind, mode, {
1700 // This line was forced into the output even if we
1701 // were in flattened mode, so we need to tell the next
1702 // group that no matter what, it needs to remeasure
1703 // because the previous measurement didn't accurately
1704 // capture the entire expression (this is necessary
1705 // for nested groups)
1706 shouldRemeasure = true;
1712 if (lineSuffix.length) {
1713 cmds.push([ind, mode, doc]);
1714 cmds.push(...lineSuffix.reverse());
1721 out.push(newLine, ind.root.value);
1722 pos = ind.root.length;
1729 out.push(newLine + ind.value);
1741 const cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder);
1743 if (cursorPlaceholderIndex !== -1) {
1744 const otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1);
1745 const beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
1746 const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join("");
1747 const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
1749 formatted: beforeCursor + aroundCursor + afterCursor,
1750 cursorNodeStart: beforeCursor.length,
1751 cursorNodeText: aroundCursor
1756 formatted: out.join("")
1764 const traverseDocOnExitStackMarker = {};
1766 function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
1767 const docsStack = [doc];
1769 while (docsStack.length !== 0) {
1770 const doc = docsStack.pop();
1772 if (doc === traverseDocOnExitStackMarker) {
1773 onExit(docsStack.pop());
1777 let shouldRecurse = true;
1780 if (onEnter(doc) === false) {
1781 shouldRecurse = false;
1786 docsStack.push(doc);
1787 docsStack.push(traverseDocOnExitStackMarker);
1790 if (shouldRecurse) {
1791 // When there are multiple parts to process,
1792 // the parts need to be pushed onto the stack in reverse order,
1793 // so that they are processed in the original order
1794 // when the stack is popped.
1795 if (doc.type === "concat" || doc.type === "fill") {
1796 for (let ic = doc.parts.length, i = ic - 1; i >= 0; --i) {
1797 docsStack.push(doc.parts[i]);
1799 } else if (doc.type === "if-break") {
1800 if (doc.flatContents) {
1801 docsStack.push(doc.flatContents);
1804 if (doc.breakContents) {
1805 docsStack.push(doc.breakContents);
1807 } else if (doc.type === "group" && doc.expandedStates) {
1808 if (shouldTraverseConditionalGroups) {
1809 for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) {
1810 docsStack.push(doc.expandedStates[i]);
1813 docsStack.push(doc.contents);
1815 } else if (doc.contents) {
1816 docsStack.push(doc.contents);
1822 function mapDoc(doc, cb) {
1823 if (doc.type === "concat" || doc.type === "fill") {
1824 const parts = doc.parts.map(part => mapDoc(part, cb));
1825 return cb(Object.assign({}, doc, {
1828 } else if (doc.type === "if-break") {
1829 const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb);
1830 const flatContents = doc.flatContents && mapDoc(doc.flatContents, cb);
1831 return cb(Object.assign({}, doc, {
1835 } else if (doc.contents) {
1836 const contents = mapDoc(doc.contents, cb);
1837 return cb(Object.assign({}, doc, {
1845 function findInDoc(doc, fn, defaultValue) {
1846 let result = defaultValue;
1847 let hasStopped = false;
1849 function findInDocOnEnterFn(doc) {
1850 const maybeResult = fn(doc);
1852 if (maybeResult !== undefined) {
1854 result = maybeResult;
1862 traverseDoc(doc, findInDocOnEnterFn);
1866 function isEmpty(n) {
1867 return typeof n === "string" && n.length === 0;
1870 function isLineNextFn(doc) {
1871 if (typeof doc === "string") {
1875 if (doc.type === "line") {
1880 function isLineNext(doc) {
1881 return findInDoc(doc, isLineNextFn, false);
1884 function willBreakFn(doc) {
1885 if (doc.type === "group" && doc.break) {
1889 if (doc.type === "line" && doc.hard) {
1893 if (doc.type === "break-parent") {
1898 function willBreak(doc) {
1899 return findInDoc(doc, willBreakFn, false);
1902 function breakParentGroup(groupStack) {
1903 if (groupStack.length > 0) {
1904 const parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because
1905 // the user is expected to manually handle what breaks.
1907 if (!parentGroup.expandedStates) {
1908 parentGroup.break = true;
1915 function propagateBreaks(doc) {
1916 const alreadyVisitedSet = new Set();
1917 const groupStack = [];
1919 function propagateBreaksOnEnterFn(doc) {
1920 if (doc.type === "break-parent") {
1921 breakParentGroup(groupStack);
1924 if (doc.type === "group") {
1925 groupStack.push(doc);
1927 if (alreadyVisitedSet.has(doc)) {
1931 alreadyVisitedSet.add(doc);
1935 function propagateBreaksOnExitFn(doc) {
1936 if (doc.type === "group") {
1937 const group = groupStack.pop();
1940 breakParentGroup(groupStack);
1945 traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn,
1946 /* shouldTraverseConditionalGroups */
1950 function removeLinesFn(doc) {
1951 // Force this doc into flat mode by statically converting all
1952 // lines into spaces (or soft lines into nothing). Hard lines
1953 // should still output because there's too great of a chance
1954 // of breaking existing assumptions otherwise.
1955 if (doc.type === "line" && !doc.hard) {
1956 return doc.soft ? "" : " ";
1957 } else if (doc.type === "if-break") {
1958 return doc.flatContents || "";
1964 function removeLines(doc) {
1965 return mapDoc(doc, removeLinesFn);
1968 function stripTrailingHardline(doc) {
1969 // HACK remove ending hardline, original PR: #1984
1970 if (doc.type === "concat" && doc.parts.length !== 0) {
1971 const lastPart = doc.parts[doc.parts.length - 1];
1973 if (lastPart.type === "concat") {
1974 if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") {
1977 parts: doc.parts.slice(0, -1)
1983 parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart))
2000 stripTrailingHardline
2003 function flattenDoc(doc) {
2004 if (doc.type === "concat") {
2007 for (let i = 0; i < doc.parts.length; ++i) {
2008 const doc2 = doc.parts[i];
2010 if (typeof doc2 !== "string" && doc2.type === "concat") {
2011 res.push(...flattenDoc(doc2).parts);
2013 const flattened = flattenDoc(doc2);
2015 if (flattened !== "") {
2016 res.push(flattened);
2021 return Object.assign({}, doc, {
2024 } else if (doc.type === "if-break") {
2025 return Object.assign({}, doc, {
2026 breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
2027 flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
2029 } else if (doc.type === "group") {
2030 return Object.assign({}, doc, {
2031 contents: flattenDoc(doc.contents),
2032 expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates
2034 } else if (doc.contents) {
2035 return Object.assign({}, doc, {
2036 contents: flattenDoc(doc.contents)
2043 function printDoc(doc) {
2044 if (typeof doc === "string") {
2045 return JSON.stringify(doc);
2048 if (doc.type === "line") {
2050 return "literalline";
2064 if (doc.type === "break-parent") {
2065 return "breakParent";
2068 if (doc.type === "trim") {
2072 if (doc.type === "concat") {
2073 return "[" + doc.parts.map(printDoc).join(", ") + "]";
2076 if (doc.type === "indent") {
2077 return "indent(" + printDoc(doc.contents) + ")";
2080 if (doc.type === "align") {
2081 return doc.n === -Infinity ? "dedentToRoot(" + printDoc(doc.contents) + ")" : doc.n < 0 ? "dedent(" + printDoc(doc.contents) + ")" : doc.n.type === "root" ? "markAsRoot(" + printDoc(doc.contents) + ")" : "align(" + JSON.stringify(doc.n) + ", " + printDoc(doc.contents) + ")";
2084 if (doc.type === "if-break") {
2085 return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")";
2088 if (doc.type === "group") {
2089 if (doc.expandedStates) {
2090 return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])";
2093 return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")";
2096 if (doc.type === "fill") {
2097 return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")";
2100 if (doc.type === "line-suffix") {
2101 return "lineSuffix(" + printDoc(doc.contents) + ")";
2104 if (doc.type === "line-suffix-boundary") {
2105 return "lineSuffixBoundary";
2108 throw new Error("Unknown doc type " + doc.type);
2112 printDocToDebug(doc) {
2113 return printDoc(flattenDoc(doc));
2119 builders: docBuilders,
2120 printer: docPrinter,
2124 var document_1 = document.builders;
2125 var document_2 = document.printer;
2126 var document_3 = document.utils;
2127 var document_4 = document.debug;
2129 exports.builders = document_1;
2130 exports.debug = document_4;
2131 exports.default = document;
2132 exports.printer = document_2;
2133 exports.utils = document_3;
2135 Object.defineProperty(exports, '__esModule', { value: true });