cc-viewer 1.6.183 → 1.6.192

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.
Files changed (135) hide show
  1. package/dist/assets/App-DuGHwadX.js +31 -0
  2. package/dist/assets/{AppHeader-Dc7WvorH.css → AppHeader-D8MCV07q.css} +3 -3
  3. package/dist/assets/AppHeader.module-CozRDKfP.js +573 -0
  4. package/dist/assets/Mobile-Bab634xx.js +10 -0
  5. package/dist/assets/_baseUniq-DJPPdHyT.js +1 -0
  6. package/dist/assets/arc-DZ3Bjq-l.js +1 -0
  7. package/dist/assets/architectureDiagram-Q4EWVU46-xy0J2lr0.js +36 -0
  8. package/dist/assets/blockDiagram-DXYQGD6D-CoUm8UC5.js +132 -0
  9. package/dist/assets/c4Diagram-AHTNJAMY-CFHX4Dfx.js +10 -0
  10. package/dist/assets/channel-G3S1FOvm.js +1 -0
  11. package/dist/assets/chunk-4BX2VUAB-CiktxOyY.js +1 -0
  12. package/dist/assets/chunk-4TB4RGXK-DHl7ZlQV.js +206 -0
  13. package/dist/assets/chunk-55IACEB6-DcgWxDD5.js +1 -0
  14. package/dist/assets/chunk-EDXVE4YY-DeUzWpQx.js +1 -0
  15. package/dist/assets/{chunk-FMBD7UC4-Bb0LARSp.js → chunk-FMBD7UC4-BCaKpugk.js} +2 -2
  16. package/dist/assets/chunk-OYMX7WX6-DKMEMbG9.js +231 -0
  17. package/dist/assets/chunk-QZHKN3VN-BREApeQ-.js +1 -0
  18. package/dist/assets/chunk-YZCP3GAM-BYW1PNda.js +1 -0
  19. package/dist/assets/classDiagram-6PBFFD2Q-B0-7EUsz.js +1 -0
  20. package/dist/assets/classDiagram-v2-HSJHXN6E-B0-7EUsz.js +1 -0
  21. package/dist/assets/clone-CX_D5SrR.js +1 -0
  22. package/dist/assets/cose-bilkent-S5V4N54A-DpwiMCiq.js +1 -0
  23. package/dist/assets/cytoscape.esm-BMgRe88L.js +331 -0
  24. package/dist/assets/dagre-KV5264BT-Dc7qbya2.js +4 -0
  25. package/dist/assets/defaultLocale-CcTwRAjA.js +1 -0
  26. package/dist/assets/diagram-5BDNPKRD-v7FsHeLQ.js +10 -0
  27. package/dist/assets/diagram-G4DWMVQ6-BhKNBlcE.js +24 -0
  28. package/dist/assets/diagram-MMDJMWI5-C-3cRdzG.js +43 -0
  29. package/dist/assets/diagram-TYMM5635-HfNcJIfT.js +24 -0
  30. package/dist/assets/erDiagram-SMLLAGMA-Ckj0dkk7.js +85 -0
  31. package/dist/assets/flowDiagram-DWJPFMVM-yf315tJr.js +162 -0
  32. package/dist/assets/ganttDiagram-T4ZO3ILL-Ch2bINVC.js +292 -0
  33. package/dist/assets/gitGraphDiagram-UUTBAWPF-CesdgsJi.js +106 -0
  34. package/dist/assets/graph-CRpmapJV.js +1 -0
  35. package/dist/assets/html2canvas.esm-B8c0f9Wq.js +22 -0
  36. package/dist/assets/index-DJ0iGKLy.js +2 -0
  37. package/dist/assets/infoDiagram-42DDH7IO-CuD16P9Y.js +2 -0
  38. package/dist/assets/init-C7FSzFHJ.js +1 -0
  39. package/dist/assets/ishikawaDiagram-UXIWVN3A-4y8aG54G.js +70 -0
  40. package/dist/assets/journeyDiagram-VCZTEJTY-B6TtR2Zk.js +139 -0
  41. package/dist/assets/kanban-definition-6JOO6SKY-DTcNHYUS.js +89 -0
  42. package/dist/assets/katex-CJRKSY_b.js +257 -0
  43. package/dist/assets/layout-CX5hpkD2.js +1 -0
  44. package/dist/assets/linear-tWlC-NXc.js +1 -0
  45. package/dist/assets/mermaid.core-DNvsWVDx.js +308 -0
  46. package/dist/assets/min-CDExe3RN.js +1 -0
  47. package/dist/assets/mindmap-definition-QFDTVHPH-CW0yNQcb.js +96 -0
  48. package/dist/assets/ordinal-aRyHI6gl.js +1 -0
  49. package/dist/assets/pieDiagram-DEJITSTG-DNrnOqmz.js +30 -0
  50. package/dist/assets/quadrantDiagram-34T5L4WZ-Cl176vnh.js +7 -0
  51. package/dist/assets/requirementDiagram-MS252O5E-DKp3A5f_.js +84 -0
  52. package/dist/assets/sankeyDiagram-XADWPNL6-BMV0lAz8.js +10 -0
  53. package/dist/assets/sequenceDiagram-FGHM5R23-CQ4preep.js +157 -0
  54. package/dist/assets/stateDiagram-FHFEXIEX-BKqYYN8H.js +1 -0
  55. package/dist/assets/stateDiagram-v2-QKLJ7IA2-C1W1ECmZ.js +1 -0
  56. package/dist/assets/timeline-definition-GMOUNBTQ-4kgeuumv.js +120 -0
  57. package/dist/assets/vendor-antd-Dk5s46Ag.js +406 -0
  58. package/dist/assets/vendor-codemirror-DxvDOrio.js +46 -0
  59. package/dist/assets/vendor-highlight-DVwgAdJY.js +3 -0
  60. package/dist/assets/vendor-markdown-DO-Ppp4f.js +60 -0
  61. package/dist/assets/vendor-qrcode-hI5wlAgK.js +9 -0
  62. package/dist/assets/vendor-virtuoso-HW77kTCh.js +1 -0
  63. package/dist/assets/vendor-xterm-D2cUrYEx.js +140 -0
  64. package/dist/assets/vennDiagram-DHZGUBPP-CqBcUIdK.js +34 -0
  65. package/dist/assets/wardley-RL74JXVD-CbEnkKx8.js +162 -0
  66. package/dist/assets/wardleyDiagram-NUSXRM2D-BJrjkZMg.js +20 -0
  67. package/dist/assets/xychartDiagram-5P7HB3ND-D8aBEz8e.js +7 -0
  68. package/dist/index.html +3 -3
  69. package/package.json +1 -1
  70. package/server.js +13 -4
  71. package/dist/assets/App-BHfyP8-J.js +0 -31
  72. package/dist/assets/AppHeader.module-W_78JZt9.js +0 -573
  73. package/dist/assets/Mobile-ca5EOMpN.js +0 -10
  74. package/dist/assets/_baseUniq-DYSZB4Xx.js +0 -1
  75. package/dist/assets/arc-BChSP8hM.js +0 -1
  76. package/dist/assets/architectureDiagram-Q4EWVU46-vlr5Q6DQ.js +0 -36
  77. package/dist/assets/blockDiagram-DXYQGD6D-4C3Amh2i.js +0 -132
  78. package/dist/assets/c4Diagram-AHTNJAMY-wI0efLSs.js +0 -10
  79. package/dist/assets/channel-d8DITadq.js +0 -1
  80. package/dist/assets/chunk-4BX2VUAB-BX9brpDB.js +0 -1
  81. package/dist/assets/chunk-4TB4RGXK-DvFQ-X9V.js +0 -206
  82. package/dist/assets/chunk-55IACEB6-BNmYjPNf.js +0 -1
  83. package/dist/assets/chunk-EDXVE4YY-BNvDPqBE.js +0 -1
  84. package/dist/assets/chunk-OYMX7WX6-BwlvIpeD.js +0 -231
  85. package/dist/assets/chunk-QZHKN3VN-BS6RK8_X.js +0 -1
  86. package/dist/assets/chunk-YZCP3GAM-oOqmydQz.js +0 -1
  87. package/dist/assets/classDiagram-6PBFFD2Q-B1oRrMCc.js +0 -1
  88. package/dist/assets/classDiagram-v2-HSJHXN6E-B1oRrMCc.js +0 -1
  89. package/dist/assets/clone-BrNOd7Lq.js +0 -1
  90. package/dist/assets/cose-bilkent-S5V4N54A-CamsIqkY.js +0 -1
  91. package/dist/assets/cytoscape.esm-DxGcaOPV.js +0 -331
  92. package/dist/assets/dagre-KV5264BT-CPAWWiBh.js +0 -4
  93. package/dist/assets/defaultLocale-DX6XiGOO.js +0 -1
  94. package/dist/assets/diagram-5BDNPKRD-D6TmzGhl.js +0 -10
  95. package/dist/assets/diagram-G4DWMVQ6-DDuJnMCL.js +0 -24
  96. package/dist/assets/diagram-MMDJMWI5-CQWhvrpz.js +0 -43
  97. package/dist/assets/diagram-TYMM5635-CEDj3w_h.js +0 -24
  98. package/dist/assets/erDiagram-SMLLAGMA-B_eQqha6.js +0 -85
  99. package/dist/assets/flowDiagram-DWJPFMVM-B985i3uQ.js +0 -162
  100. package/dist/assets/ganttDiagram-T4ZO3ILL-DKp62vr3.js +0 -292
  101. package/dist/assets/gitGraphDiagram-UUTBAWPF-Cc1gyz1Q.js +0 -106
  102. package/dist/assets/graph-C-1-3bsA.js +0 -1
  103. package/dist/assets/html2canvas.esm-QH1iLAAe.js +0 -22
  104. package/dist/assets/index-LH2WLu05.js +0 -2
  105. package/dist/assets/infoDiagram-42DDH7IO-DqXaAHZz.js +0 -2
  106. package/dist/assets/init-Gi6I4Gst.js +0 -1
  107. package/dist/assets/ishikawaDiagram-UXIWVN3A-zdUdDJX2.js +0 -70
  108. package/dist/assets/journeyDiagram-VCZTEJTY-ip5SzODy.js +0 -139
  109. package/dist/assets/kanban-definition-6JOO6SKY-D5EYh6AP.js +0 -89
  110. package/dist/assets/katex-DkKDou_j.js +0 -257
  111. package/dist/assets/layout-Cjq8AL8G.js +0 -1
  112. package/dist/assets/linear-U0KsEJ2u.js +0 -1
  113. package/dist/assets/mermaid.core-CT-5crLN.js +0 -308
  114. package/dist/assets/min-C7G6pq26.js +0 -1
  115. package/dist/assets/mindmap-definition-QFDTVHPH-CIzhFOw1.js +0 -96
  116. package/dist/assets/ordinal-Cboi1Yqb.js +0 -1
  117. package/dist/assets/pieDiagram-DEJITSTG-Cp1Zd1MQ.js +0 -30
  118. package/dist/assets/quadrantDiagram-34T5L4WZ-Cp31xM90.js +0 -7
  119. package/dist/assets/requirementDiagram-MS252O5E-Dbg_eQqB.js +0 -84
  120. package/dist/assets/sankeyDiagram-XADWPNL6-CMrzwpwC.js +0 -10
  121. package/dist/assets/sequenceDiagram-FGHM5R23-KJegoBnN.js +0 -157
  122. package/dist/assets/stateDiagram-FHFEXIEX-BDWprYzE.js +0 -1
  123. package/dist/assets/stateDiagram-v2-QKLJ7IA2-CCUmB0qI.js +0 -1
  124. package/dist/assets/timeline-definition-GMOUNBTQ-BOWeG5LY.js +0 -120
  125. package/dist/assets/vendor-antd-CtdKd5xs.js +0 -406
  126. package/dist/assets/vendor-codemirror-CdXaVX4e.js +0 -46
  127. package/dist/assets/vendor-highlight-D4ATuRwX.js +0 -3
  128. package/dist/assets/vendor-markdown-CO-jRjTB.js +0 -60
  129. package/dist/assets/vendor-qrcode-D05RfzwB.js +0 -9
  130. package/dist/assets/vendor-virtuoso-BhnFrbmh.js +0 -1
  131. package/dist/assets/vendor-xterm-DWMOrwSy.js +0 -140
  132. package/dist/assets/vennDiagram-DHZGUBPP-B6mLodPk.js +0 -34
  133. package/dist/assets/wardley-RL74JXVD-CovHs24Z.js +0 -162
  134. package/dist/assets/wardleyDiagram-NUSXRM2D-CBg_VXF7.js +0 -20
  135. package/dist/assets/xychartDiagram-5P7HB3ND-BRxgk_oX.js +0 -7
@@ -0,0 +1,162 @@
1
+ var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);import{_ as __vitePreload}from"./index-DJ0iGKLy.js";import{m as map,f as flatten,d as min}from"./min-CDExe3RN.js";import{b as baseFlatten,l as baseUniq,c as baseIteratee,m as filter,r as reduce,n as forEach}from"./_baseUniq-DJPPdHyT.js";import{b9 as isEmpty}from"./mermaid.core-DNvsWVDx.js";import{a5 as getAugmentedNamespace}from"./vendor-antd-Dk5s46Ag.js";function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee))}function uniqBy(array,iteratee){return array&&array.length?baseUniq(array,baseIteratee(iteratee)):[]}function isAstNode(obj){return typeof obj=="object"&&obj!==null&&typeof obj.$type=="string"}function isReference(obj){return typeof obj=="object"&&obj!==null&&typeof obj.$refText=="string"&&"ref"in obj}function isMultiReference(obj){return typeof obj=="object"&&obj!==null&&typeof obj.$refText=="string"&&"items"in obj}function isAstNodeDescription(obj){return typeof obj=="object"&&obj!==null&&typeof obj.name=="string"&&typeof obj.type=="string"&&typeof obj.path=="string"}function isLinkingError(obj){return typeof obj=="object"&&obj!==null&&typeof obj.info=="object"&&typeof obj.message=="string"}class AbstractAstReflection{constructor(){this.subtypes={},this.allSubtypes={}}getAllTypes(){return Object.keys(this.types)}getReferenceType(refInfo){var _a21;const metaData=this.types[refInfo.container.$type];if(!metaData)throw new Error(`Type ${refInfo.container.$type||"undefined"} not found.`);const referenceType=(_a21=metaData.properties[refInfo.property])==null?void 0:_a21.referenceType;if(!referenceType)throw new Error(`Property ${refInfo.property||"undefined"} of type ${refInfo.container.$type} is not a reference.`);return referenceType}getTypeMetaData(type){const result=this.types[type];return result||{name:type,properties:{},superTypes:[]}}isInstance(node,type){return isAstNode(node)&&this.isSubtype(node.$type,type)}isSubtype(subtype,supertype){if(subtype===supertype)return!0;let nested=this.subtypes[subtype];nested||(nested=this.subtypes[subtype]={});const existing=nested[supertype];if(existing!==void 0)return existing;{const metaData=this.types[subtype],result=metaData?metaData.superTypes.some(s=>this.isSubtype(s,supertype)):!1;return nested[supertype]=result,result}}getAllSubTypes(type){const existing=this.allSubtypes[type];if(existing)return existing;{const allTypes=this.getAllTypes(),types=[];for(const possibleSubType of allTypes)this.isSubtype(possibleSubType,type)&&types.push(possibleSubType);return this.allSubtypes[type]=types,types}}}function isCompositeCstNode(node){return typeof node=="object"&&node!==null&&Array.isArray(node.content)}function isLeafCstNode(node){return typeof node=="object"&&node!==null&&typeof node.tokenType=="object"}function isRootCstNode(node){return isCompositeCstNode(node)&&typeof node.fullText=="string"}class StreamImpl{constructor(startFn,nextFn){this.startFn=startFn,this.nextFn=nextFn}iterator(){const iterator={state:this.startFn(),next:()=>this.nextFn(iterator.state),[Symbol.iterator]:()=>iterator};return iterator}[Symbol.iterator](){return this.iterator()}isEmpty(){return!!this.iterator().next().done}count(){const iterator=this.iterator();let count=0,next=iterator.next();for(;!next.done;)count++,next=iterator.next();return count}toArray(){const result=[],iterator=this.iterator();let next;do next=iterator.next(),next.value!==void 0&&result.push(next.value);while(!next.done);return result}toSet(){return new Set(this)}toMap(keyFn,valueFn){const entryStream=this.map(element=>[keyFn?keyFn(element):element,valueFn?valueFn(element):element]);return new Map(entryStream)}toString(){return this.join()}concat(other){return new StreamImpl(()=>({first:this.startFn(),firstDone:!1,iterator:other[Symbol.iterator]()}),state=>{let result;if(!state.firstDone){do if(result=this.nextFn(state.first),!result.done)return result;while(!result.done);state.firstDone=!0}do if(result=state.iterator.next(),!result.done)return result;while(!result.done);return DONE_RESULT})}join(separator=","){const iterator=this.iterator();let value="",result,addSeparator=!1;do result=iterator.next(),result.done||(addSeparator&&(value+=separator),value+=toString(result.value)),addSeparator=!0;while(!result.done);return value}indexOf(searchElement,fromIndex=0){const iterator=this.iterator();let index=0,next=iterator.next();for(;!next.done;){if(index>=fromIndex&&next.value===searchElement)return index;next=iterator.next(),index++}return-1}every(predicate){const iterator=this.iterator();let next=iterator.next();for(;!next.done;){if(!predicate(next.value))return!1;next=iterator.next()}return!0}some(predicate){const iterator=this.iterator();let next=iterator.next();for(;!next.done;){if(predicate(next.value))return!0;next=iterator.next()}return!1}forEach(callbackfn){const iterator=this.iterator();let index=0,next=iterator.next();for(;!next.done;)callbackfn(next.value,index),next=iterator.next(),index++}map(callbackfn){return new StreamImpl(this.startFn,state=>{const{done,value}=this.nextFn(state);return done?DONE_RESULT:{done:!1,value:callbackfn(value)}})}filter(predicate){return new StreamImpl(this.startFn,state=>{let result;do if(result=this.nextFn(state),!result.done&&predicate(result.value))return result;while(!result.done);return DONE_RESULT})}nonNullable(){return this.filter(e=>e!=null)}reduce(callbackfn,initialValue){const iterator=this.iterator();let previousValue=initialValue,next=iterator.next();for(;!next.done;)previousValue===void 0?previousValue=next.value:previousValue=callbackfn(previousValue,next.value),next=iterator.next();return previousValue}reduceRight(callbackfn,initialValue){return this.recursiveReduce(this.iterator(),callbackfn,initialValue)}recursiveReduce(iterator,callbackfn,initialValue){const next=iterator.next();if(next.done)return initialValue;const previousValue=this.recursiveReduce(iterator,callbackfn,initialValue);return previousValue===void 0?next.value:callbackfn(previousValue,next.value)}find(predicate){const iterator=this.iterator();let next=iterator.next();for(;!next.done;){if(predicate(next.value))return next.value;next=iterator.next()}}findIndex(predicate){const iterator=this.iterator();let index=0,next=iterator.next();for(;!next.done;){if(predicate(next.value))return index;next=iterator.next(),index++}return-1}includes(searchElement){const iterator=this.iterator();let next=iterator.next();for(;!next.done;){if(next.value===searchElement)return!0;next=iterator.next()}return!1}flatMap(callbackfn){return new StreamImpl(()=>({this:this.startFn()}),state=>{do{if(state.iterator){const next=state.iterator.next();if(next.done)state.iterator=void 0;else return next}const{done,value}=this.nextFn(state.this);if(!done){const mapped=callbackfn(value);if(isIterable(mapped))state.iterator=mapped[Symbol.iterator]();else return{done:!1,value:mapped}}}while(state.iterator);return DONE_RESULT})}flat(depth){if(depth===void 0&&(depth=1),depth<=0)return this;const stream2=depth>1?this.flat(depth-1):this;return new StreamImpl(()=>({this:stream2.startFn()}),state=>{do{if(state.iterator){const next=state.iterator.next();if(next.done)state.iterator=void 0;else return next}const{done,value}=stream2.nextFn(state.this);if(!done)if(isIterable(value))state.iterator=value[Symbol.iterator]();else return{done:!1,value}}while(state.iterator);return DONE_RESULT})}head(){const result=this.iterator().next();if(!result.done)return result.value}tail(skipCount=1){return new StreamImpl(()=>{const state=this.startFn();for(let i=0;i<skipCount;i++)if(this.nextFn(state).done)return state;return state},this.nextFn)}limit(maxSize){return new StreamImpl(()=>({size:0,state:this.startFn()}),state=>(state.size++,state.size>maxSize?DONE_RESULT:this.nextFn(state.state)))}distinct(by){return new StreamImpl(()=>({set:new Set,internalState:this.startFn()}),state=>{let result;do if(result=this.nextFn(state.internalState),!result.done){const value=by?by(result.value):result.value;if(!state.set.has(value))return state.set.add(value),result}while(!result.done);return DONE_RESULT})}exclude(other,key){const otherKeySet=new Set;for(const item of other){const value=key?key(item):item;otherKeySet.add(value)}return this.filter(e=>{const ownKey=key?key(e):e;return!otherKeySet.has(ownKey)})}}function toString(item){return typeof item=="string"?item:typeof item>"u"?"undefined":typeof item.toString=="function"?item.toString():Object.prototype.toString.call(item)}function isIterable(obj){return!!obj&&typeof obj[Symbol.iterator]=="function"}const EMPTY_STREAM=new StreamImpl(()=>{},()=>DONE_RESULT),DONE_RESULT=Object.freeze({done:!0,value:void 0});function stream(...collections){if(collections.length===1){const collection=collections[0];if(collection instanceof StreamImpl)return collection;if(isIterable(collection))return new StreamImpl(()=>collection[Symbol.iterator](),iterator=>iterator.next());if(typeof collection.length=="number")return new StreamImpl(()=>({index:0}),state=>state.index<collection.length?{done:!1,value:collection[state.index++]}:DONE_RESULT)}return collections.length>1?new StreamImpl(()=>({collIndex:0,arrIndex:0}),state=>{do{if(state.iterator){const next=state.iterator.next();if(!next.done)return next;state.iterator=void 0}if(state.array){if(state.arrIndex<state.array.length)return{done:!1,value:state.array[state.arrIndex++]};state.array=void 0,state.arrIndex=0}if(state.collIndex<collections.length){const collection=collections[state.collIndex++];isIterable(collection)?state.iterator=collection[Symbol.iterator]():collection&&typeof collection.length=="number"&&(state.array=collection)}}while(state.iterator||state.array||state.collIndex<collections.length);return DONE_RESULT}):EMPTY_STREAM}class TreeStreamImpl extends StreamImpl{constructor(root,children,options){super(()=>({iterators:options!=null&&options.includeRoot?[[root][Symbol.iterator]()]:[children(root)[Symbol.iterator]()],pruned:!1}),state=>{for(state.pruned&&(state.iterators.pop(),state.pruned=!1);state.iterators.length>0;){const next=state.iterators[state.iterators.length-1].next();if(next.done)state.iterators.pop();else return state.iterators.push(children(next.value)[Symbol.iterator]()),next}return DONE_RESULT})}iterator(){const iterator={state:this.startFn(),next:()=>this.nextFn(iterator.state),prune:()=>{iterator.state.pruned=!0},[Symbol.iterator]:()=>iterator};return iterator}}var Reduction;(function(Reduction2){function sum(stream2){return stream2.reduce((a,b)=>a+b,0)}Reduction2.sum=sum;function product(stream2){return stream2.reduce((a,b)=>a*b,0)}Reduction2.product=product;function min2(stream2){return stream2.reduce((a,b)=>Math.min(a,b))}Reduction2.min=min2;function max(stream2){return stream2.reduce((a,b)=>Math.max(a,b))}Reduction2.max=max})(Reduction||(Reduction={}));function linkContentToContainer(node,options={}){for(const[name,value]of Object.entries(node))name.startsWith("$")||(Array.isArray(value)?value.forEach((item,index)=>{isAstNode(item)&&(item.$container=node,item.$containerProperty=name,item.$containerIndex=index,options.deep&&linkContentToContainer(item,options))}):isAstNode(value)&&(value.$container=node,value.$containerProperty=name,options.deep&&linkContentToContainer(value,options)))}function getContainerOfType(node,typePredicate){let item=node;for(;item;){if(typePredicate(item))return item;item=item.$container}}function getDocument(node){const result=findRootNode(node).$document;if(!result)throw new Error("AST node has no document.");return result}function findRootNode(node){for(;node.$container;)node=node.$container;return node}function getReferenceNodes(reference){return isReference(reference)?reference.ref?[reference.ref]:[]:isMultiReference(reference)?reference.items.map(item=>item.ref):[]}function streamContents(node,options){if(!node)throw new Error("Node must be an AstNode.");const range=options==null?void 0:options.range;return new StreamImpl(()=>({keys:Object.keys(node),keyIndex:0,arrayIndex:0}),state=>{for(;state.keyIndex<state.keys.length;){const property=state.keys[state.keyIndex];if(!property.startsWith("$")){const value=node[property];if(isAstNode(value)){if(state.keyIndex++,isAstNodeInRange(value,range))return{done:!1,value}}else if(Array.isArray(value)){for(;state.arrayIndex<value.length;){const index=state.arrayIndex++,element=value[index];if(isAstNode(element)&&isAstNodeInRange(element,range))return{done:!1,value:element}}state.arrayIndex=0}}state.keyIndex++}return DONE_RESULT})}function streamAllContents(root,options){if(!root)throw new Error("Root node must be an AstNode.");return new TreeStreamImpl(root,node=>streamContents(node,options))}function streamAst(root,options){if(!root)throw new Error("Root node must be an AstNode.");return new TreeStreamImpl(root,node=>streamContents(node,options),{includeRoot:!0})}function isAstNodeInRange(astNode,range){var _a21;if(!range)return!0;const nodeRange=(_a21=astNode.$cstNode)==null?void 0:_a21.range;return nodeRange?inRange(nodeRange,range):!1}function streamReferences(node){return new StreamImpl(()=>({keys:Object.keys(node),keyIndex:0,arrayIndex:0}),state=>{for(;state.keyIndex<state.keys.length;){const property=state.keys[state.keyIndex];if(!property.startsWith("$")){const value=node[property];if(isReference(value)||isMultiReference(value))return state.keyIndex++,{done:!1,value:{reference:value,container:node,property}};if(Array.isArray(value)){for(;state.arrayIndex<value.length;){const index=state.arrayIndex++,element=value[index];if(isReference(element)||isMultiReference(value))return{done:!1,value:{reference:element,container:node,property,index}}}state.arrayIndex=0}}state.keyIndex++}return DONE_RESULT})}function assignMandatoryProperties(reflection2,node){const typeMetaData=reflection2.getTypeMetaData(node.$type),genericNode=node;for(const property of Object.values(typeMetaData.properties))property.defaultValue!==void 0&&genericNode[property.name]===void 0&&(genericNode[property.name]=copyDefaultValue(property.defaultValue))}function copyDefaultValue(propertyType){return Array.isArray(propertyType)?[...propertyType.map(copyDefaultValue)]:propertyType}const AbstractElement={$type:"AbstractElement",cardinality:"cardinality"};function isAbstractElement(item){return reflection$1.isInstance(item,AbstractElement.$type)}const AbstractParserRule={$type:"AbstractParserRule"};function isAbstractParserRule(item){return reflection$1.isInstance(item,AbstractParserRule.$type)}const AbstractRule={$type:"AbstractRule"},AbstractType={$type:"AbstractType"},Action={$type:"Action",cardinality:"cardinality",feature:"feature",inferredType:"inferredType",operator:"operator",type:"type"};function isAction(item){return reflection$1.isInstance(item,Action.$type)}const Alternatives={$type:"Alternatives",cardinality:"cardinality",elements:"elements"};function isAlternatives(item){return reflection$1.isInstance(item,Alternatives.$type)}const ArrayLiteral={$type:"ArrayLiteral",elements:"elements"},ArrayType={$type:"ArrayType",elementType:"elementType"},Assignment={$type:"Assignment",cardinality:"cardinality",feature:"feature",operator:"operator",predicate:"predicate",terminal:"terminal"};function isAssignment(item){return reflection$1.isInstance(item,Assignment.$type)}const BooleanLiteral={$type:"BooleanLiteral",true:"true"};function isBooleanLiteral(item){return reflection$1.isInstance(item,BooleanLiteral.$type)}const CharacterRange={$type:"CharacterRange",cardinality:"cardinality",left:"left",lookahead:"lookahead",parenthesized:"parenthesized",right:"right"};function isCharacterRange(item){return reflection$1.isInstance(item,CharacterRange.$type)}const Condition={$type:"Condition"},Conjunction={$type:"Conjunction",left:"left",right:"right"};function isConjunction(item){return reflection$1.isInstance(item,Conjunction.$type)}const CrossReference={$type:"CrossReference",cardinality:"cardinality",deprecatedSyntax:"deprecatedSyntax",isMulti:"isMulti",terminal:"terminal",type:"type"};function isCrossReference(item){return reflection$1.isInstance(item,CrossReference.$type)}const Disjunction={$type:"Disjunction",left:"left",right:"right"};function isDisjunction(item){return reflection$1.isInstance(item,Disjunction.$type)}const EndOfFile={$type:"EndOfFile",cardinality:"cardinality"};function isEndOfFile(item){return reflection$1.isInstance(item,EndOfFile.$type)}const Grammar={$type:"Grammar",imports:"imports",interfaces:"interfaces",isDeclared:"isDeclared",name:"name",rules:"rules",types:"types"},GrammarImport={$type:"GrammarImport",path:"path"},Group$1={$type:"Group",cardinality:"cardinality",elements:"elements",guardCondition:"guardCondition",predicate:"predicate"};function isGroup(item){return reflection$1.isInstance(item,Group$1.$type)}const InferredType={$type:"InferredType",name:"name"};function isInferredType(item){return reflection$1.isInstance(item,InferredType.$type)}const InfixRule={$type:"InfixRule",call:"call",dataType:"dataType",inferredType:"inferredType",name:"name",operators:"operators",parameters:"parameters",returnType:"returnType"};function isInfixRule(item){return reflection$1.isInstance(item,InfixRule.$type)}const InfixRuleOperatorList={$type:"InfixRuleOperatorList",associativity:"associativity",operators:"operators"},InfixRuleOperators={$type:"InfixRuleOperators",precedences:"precedences"},Interface={$type:"Interface",attributes:"attributes",name:"name",superTypes:"superTypes"};function isInterface(item){return reflection$1.isInstance(item,Interface.$type)}const Keyword={$type:"Keyword",cardinality:"cardinality",predicate:"predicate",value:"value"};function isKeyword(item){return reflection$1.isInstance(item,Keyword.$type)}const NamedArgument={$type:"NamedArgument",calledByName:"calledByName",parameter:"parameter",value:"value"},NegatedToken={$type:"NegatedToken",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized",terminal:"terminal"};function isNegatedToken(item){return reflection$1.isInstance(item,NegatedToken.$type)}const Negation={$type:"Negation",value:"value"};function isNegation(item){return reflection$1.isInstance(item,Negation.$type)}const NumberLiteral={$type:"NumberLiteral",value:"value"},Parameter={$type:"Parameter",name:"name"},ParameterReference={$type:"ParameterReference",parameter:"parameter"};function isParameterReference(item){return reflection$1.isInstance(item,ParameterReference.$type)}const ParserRule={$type:"ParserRule",dataType:"dataType",definition:"definition",entry:"entry",fragment:"fragment",inferredType:"inferredType",name:"name",parameters:"parameters",returnType:"returnType"};function isParserRule(item){return reflection$1.isInstance(item,ParserRule.$type)}const ReferenceType={$type:"ReferenceType",isMulti:"isMulti",referenceType:"referenceType"},RegexToken={$type:"RegexToken",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized",regex:"regex"};function isRegexToken(item){return reflection$1.isInstance(item,RegexToken.$type)}const ReturnType={$type:"ReturnType",name:"name"};function isReturnType(item){return reflection$1.isInstance(item,ReturnType.$type)}const RuleCall={$type:"RuleCall",arguments:"arguments",cardinality:"cardinality",predicate:"predicate",rule:"rule"};function isRuleCall(item){return reflection$1.isInstance(item,RuleCall.$type)}const SimpleType={$type:"SimpleType",primitiveType:"primitiveType",stringType:"stringType",typeRef:"typeRef"};function isSimpleType(item){return reflection$1.isInstance(item,SimpleType.$type)}const StringLiteral={$type:"StringLiteral",value:"value"},TerminalAlternatives={$type:"TerminalAlternatives",cardinality:"cardinality",elements:"elements",lookahead:"lookahead",parenthesized:"parenthesized"};function isTerminalAlternatives(item){return reflection$1.isInstance(item,TerminalAlternatives.$type)}const TerminalElement={$type:"TerminalElement",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized"},TerminalGroup={$type:"TerminalGroup",cardinality:"cardinality",elements:"elements",lookahead:"lookahead",parenthesized:"parenthesized"};function isTerminalGroup(item){return reflection$1.isInstance(item,TerminalGroup.$type)}const TerminalRule={$type:"TerminalRule",definition:"definition",fragment:"fragment",hidden:"hidden",name:"name",type:"type"};function isTerminalRule(item){return reflection$1.isInstance(item,TerminalRule.$type)}const TerminalRuleCall={$type:"TerminalRuleCall",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized",rule:"rule"};function isTerminalRuleCall(item){return reflection$1.isInstance(item,TerminalRuleCall.$type)}const Type={$type:"Type",name:"name",type:"type"};function isType(item){return reflection$1.isInstance(item,Type.$type)}const TypeAttribute={$type:"TypeAttribute",defaultValue:"defaultValue",isOptional:"isOptional",name:"name",type:"type"},TypeDefinition={$type:"TypeDefinition"},UnionType={$type:"UnionType",types:"types"},UnorderedGroup={$type:"UnorderedGroup",cardinality:"cardinality",elements:"elements"};function isUnorderedGroup(item){return reflection$1.isInstance(item,UnorderedGroup.$type)}const UntilToken={$type:"UntilToken",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized",terminal:"terminal"};function isUntilToken(item){return reflection$1.isInstance(item,UntilToken.$type)}const ValueLiteral={$type:"ValueLiteral"},Wildcard={$type:"Wildcard",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized"};function isWildcard(item){return reflection$1.isInstance(item,Wildcard.$type)}class LangiumGrammarAstReflection extends AbstractAstReflection{constructor(){super(...arguments),this.types={AbstractElement:{name:AbstractElement.$type,properties:{cardinality:{name:AbstractElement.cardinality}},superTypes:[]},AbstractParserRule:{name:AbstractParserRule.$type,properties:{},superTypes:[AbstractRule.$type,AbstractType.$type]},AbstractRule:{name:AbstractRule.$type,properties:{},superTypes:[]},AbstractType:{name:AbstractType.$type,properties:{},superTypes:[]},Action:{name:Action.$type,properties:{cardinality:{name:Action.cardinality},feature:{name:Action.feature},inferredType:{name:Action.inferredType},operator:{name:Action.operator},type:{name:Action.type,referenceType:AbstractType.$type}},superTypes:[AbstractElement.$type]},Alternatives:{name:Alternatives.$type,properties:{cardinality:{name:Alternatives.cardinality},elements:{name:Alternatives.elements,defaultValue:[]}},superTypes:[AbstractElement.$type]},ArrayLiteral:{name:ArrayLiteral.$type,properties:{elements:{name:ArrayLiteral.elements,defaultValue:[]}},superTypes:[ValueLiteral.$type]},ArrayType:{name:ArrayType.$type,properties:{elementType:{name:ArrayType.elementType}},superTypes:[TypeDefinition.$type]},Assignment:{name:Assignment.$type,properties:{cardinality:{name:Assignment.cardinality},feature:{name:Assignment.feature},operator:{name:Assignment.operator},predicate:{name:Assignment.predicate},terminal:{name:Assignment.terminal}},superTypes:[AbstractElement.$type]},BooleanLiteral:{name:BooleanLiteral.$type,properties:{true:{name:BooleanLiteral.true,defaultValue:!1}},superTypes:[Condition.$type,ValueLiteral.$type]},CharacterRange:{name:CharacterRange.$type,properties:{cardinality:{name:CharacterRange.cardinality},left:{name:CharacterRange.left},lookahead:{name:CharacterRange.lookahead},parenthesized:{name:CharacterRange.parenthesized,defaultValue:!1},right:{name:CharacterRange.right}},superTypes:[TerminalElement.$type]},Condition:{name:Condition.$type,properties:{},superTypes:[]},Conjunction:{name:Conjunction.$type,properties:{left:{name:Conjunction.left},right:{name:Conjunction.right}},superTypes:[Condition.$type]},CrossReference:{name:CrossReference.$type,properties:{cardinality:{name:CrossReference.cardinality},deprecatedSyntax:{name:CrossReference.deprecatedSyntax,defaultValue:!1},isMulti:{name:CrossReference.isMulti,defaultValue:!1},terminal:{name:CrossReference.terminal},type:{name:CrossReference.type,referenceType:AbstractType.$type}},superTypes:[AbstractElement.$type]},Disjunction:{name:Disjunction.$type,properties:{left:{name:Disjunction.left},right:{name:Disjunction.right}},superTypes:[Condition.$type]},EndOfFile:{name:EndOfFile.$type,properties:{cardinality:{name:EndOfFile.cardinality}},superTypes:[AbstractElement.$type]},Grammar:{name:Grammar.$type,properties:{imports:{name:Grammar.imports,defaultValue:[]},interfaces:{name:Grammar.interfaces,defaultValue:[]},isDeclared:{name:Grammar.isDeclared,defaultValue:!1},name:{name:Grammar.name},rules:{name:Grammar.rules,defaultValue:[]},types:{name:Grammar.types,defaultValue:[]}},superTypes:[]},GrammarImport:{name:GrammarImport.$type,properties:{path:{name:GrammarImport.path}},superTypes:[]},Group:{name:Group$1.$type,properties:{cardinality:{name:Group$1.cardinality},elements:{name:Group$1.elements,defaultValue:[]},guardCondition:{name:Group$1.guardCondition},predicate:{name:Group$1.predicate}},superTypes:[AbstractElement.$type]},InferredType:{name:InferredType.$type,properties:{name:{name:InferredType.name}},superTypes:[AbstractType.$type]},InfixRule:{name:InfixRule.$type,properties:{call:{name:InfixRule.call},dataType:{name:InfixRule.dataType},inferredType:{name:InfixRule.inferredType},name:{name:InfixRule.name},operators:{name:InfixRule.operators},parameters:{name:InfixRule.parameters,defaultValue:[]},returnType:{name:InfixRule.returnType,referenceType:AbstractType.$type}},superTypes:[AbstractParserRule.$type]},InfixRuleOperatorList:{name:InfixRuleOperatorList.$type,properties:{associativity:{name:InfixRuleOperatorList.associativity},operators:{name:InfixRuleOperatorList.operators,defaultValue:[]}},superTypes:[]},InfixRuleOperators:{name:InfixRuleOperators.$type,properties:{precedences:{name:InfixRuleOperators.precedences,defaultValue:[]}},superTypes:[]},Interface:{name:Interface.$type,properties:{attributes:{name:Interface.attributes,defaultValue:[]},name:{name:Interface.name},superTypes:{name:Interface.superTypes,defaultValue:[],referenceType:AbstractType.$type}},superTypes:[AbstractType.$type]},Keyword:{name:Keyword.$type,properties:{cardinality:{name:Keyword.cardinality},predicate:{name:Keyword.predicate},value:{name:Keyword.value}},superTypes:[AbstractElement.$type]},NamedArgument:{name:NamedArgument.$type,properties:{calledByName:{name:NamedArgument.calledByName,defaultValue:!1},parameter:{name:NamedArgument.parameter,referenceType:Parameter.$type},value:{name:NamedArgument.value}},superTypes:[]},NegatedToken:{name:NegatedToken.$type,properties:{cardinality:{name:NegatedToken.cardinality},lookahead:{name:NegatedToken.lookahead},parenthesized:{name:NegatedToken.parenthesized,defaultValue:!1},terminal:{name:NegatedToken.terminal}},superTypes:[TerminalElement.$type]},Negation:{name:Negation.$type,properties:{value:{name:Negation.value}},superTypes:[Condition.$type]},NumberLiteral:{name:NumberLiteral.$type,properties:{value:{name:NumberLiteral.value}},superTypes:[ValueLiteral.$type]},Parameter:{name:Parameter.$type,properties:{name:{name:Parameter.name}},superTypes:[]},ParameterReference:{name:ParameterReference.$type,properties:{parameter:{name:ParameterReference.parameter,referenceType:Parameter.$type}},superTypes:[Condition.$type]},ParserRule:{name:ParserRule.$type,properties:{dataType:{name:ParserRule.dataType},definition:{name:ParserRule.definition},entry:{name:ParserRule.entry,defaultValue:!1},fragment:{name:ParserRule.fragment,defaultValue:!1},inferredType:{name:ParserRule.inferredType},name:{name:ParserRule.name},parameters:{name:ParserRule.parameters,defaultValue:[]},returnType:{name:ParserRule.returnType,referenceType:AbstractType.$type}},superTypes:[AbstractParserRule.$type]},ReferenceType:{name:ReferenceType.$type,properties:{isMulti:{name:ReferenceType.isMulti,defaultValue:!1},referenceType:{name:ReferenceType.referenceType}},superTypes:[TypeDefinition.$type]},RegexToken:{name:RegexToken.$type,properties:{cardinality:{name:RegexToken.cardinality},lookahead:{name:RegexToken.lookahead},parenthesized:{name:RegexToken.parenthesized,defaultValue:!1},regex:{name:RegexToken.regex}},superTypes:[TerminalElement.$type]},ReturnType:{name:ReturnType.$type,properties:{name:{name:ReturnType.name}},superTypes:[]},RuleCall:{name:RuleCall.$type,properties:{arguments:{name:RuleCall.arguments,defaultValue:[]},cardinality:{name:RuleCall.cardinality},predicate:{name:RuleCall.predicate},rule:{name:RuleCall.rule,referenceType:AbstractRule.$type}},superTypes:[AbstractElement.$type]},SimpleType:{name:SimpleType.$type,properties:{primitiveType:{name:SimpleType.primitiveType},stringType:{name:SimpleType.stringType},typeRef:{name:SimpleType.typeRef,referenceType:AbstractType.$type}},superTypes:[TypeDefinition.$type]},StringLiteral:{name:StringLiteral.$type,properties:{value:{name:StringLiteral.value}},superTypes:[ValueLiteral.$type]},TerminalAlternatives:{name:TerminalAlternatives.$type,properties:{cardinality:{name:TerminalAlternatives.cardinality},elements:{name:TerminalAlternatives.elements,defaultValue:[]},lookahead:{name:TerminalAlternatives.lookahead},parenthesized:{name:TerminalAlternatives.parenthesized,defaultValue:!1}},superTypes:[TerminalElement.$type]},TerminalElement:{name:TerminalElement.$type,properties:{cardinality:{name:TerminalElement.cardinality},lookahead:{name:TerminalElement.lookahead},parenthesized:{name:TerminalElement.parenthesized,defaultValue:!1}},superTypes:[AbstractElement.$type]},TerminalGroup:{name:TerminalGroup.$type,properties:{cardinality:{name:TerminalGroup.cardinality},elements:{name:TerminalGroup.elements,defaultValue:[]},lookahead:{name:TerminalGroup.lookahead},parenthesized:{name:TerminalGroup.parenthesized,defaultValue:!1}},superTypes:[TerminalElement.$type]},TerminalRule:{name:TerminalRule.$type,properties:{definition:{name:TerminalRule.definition},fragment:{name:TerminalRule.fragment,defaultValue:!1},hidden:{name:TerminalRule.hidden,defaultValue:!1},name:{name:TerminalRule.name},type:{name:TerminalRule.type}},superTypes:[AbstractRule.$type]},TerminalRuleCall:{name:TerminalRuleCall.$type,properties:{cardinality:{name:TerminalRuleCall.cardinality},lookahead:{name:TerminalRuleCall.lookahead},parenthesized:{name:TerminalRuleCall.parenthesized,defaultValue:!1},rule:{name:TerminalRuleCall.rule,referenceType:TerminalRule.$type}},superTypes:[TerminalElement.$type]},Type:{name:Type.$type,properties:{name:{name:Type.name},type:{name:Type.type}},superTypes:[AbstractType.$type]},TypeAttribute:{name:TypeAttribute.$type,properties:{defaultValue:{name:TypeAttribute.defaultValue},isOptional:{name:TypeAttribute.isOptional,defaultValue:!1},name:{name:TypeAttribute.name},type:{name:TypeAttribute.type}},superTypes:[]},TypeDefinition:{name:TypeDefinition.$type,properties:{},superTypes:[]},UnionType:{name:UnionType.$type,properties:{types:{name:UnionType.types,defaultValue:[]}},superTypes:[TypeDefinition.$type]},UnorderedGroup:{name:UnorderedGroup.$type,properties:{cardinality:{name:UnorderedGroup.cardinality},elements:{name:UnorderedGroup.elements,defaultValue:[]}},superTypes:[AbstractElement.$type]},UntilToken:{name:UntilToken.$type,properties:{cardinality:{name:UntilToken.cardinality},lookahead:{name:UntilToken.lookahead},parenthesized:{name:UntilToken.parenthesized,defaultValue:!1},terminal:{name:UntilToken.terminal}},superTypes:[TerminalElement.$type]},ValueLiteral:{name:ValueLiteral.$type,properties:{},superTypes:[]},Wildcard:{name:Wildcard.$type,properties:{cardinality:{name:Wildcard.cardinality},lookahead:{name:Wildcard.lookahead},parenthesized:{name:Wildcard.parenthesized,defaultValue:!1}},superTypes:[TerminalElement.$type]}}}}const reflection$1=new LangiumGrammarAstReflection;function streamCst(node){return new TreeStreamImpl(node,element=>isCompositeCstNode(element)?element.content:[],{includeRoot:!0})}function isChildNode(child,parent){for(;child.container;)if(child=child.container,child===parent)return!0;return!1}function tokenToRange(token){return{start:{character:token.startColumn-1,line:token.startLine-1},end:{character:token.endColumn,line:token.endLine-1}}}function toDocumentSegment(node){if(!node)return;const{offset,end,range}=node;return{range,offset,end,length:end-offset}}var RangeComparison;(function(RangeComparison2){RangeComparison2[RangeComparison2.Before=0]="Before",RangeComparison2[RangeComparison2.After=1]="After",RangeComparison2[RangeComparison2.OverlapFront=2]="OverlapFront",RangeComparison2[RangeComparison2.OverlapBack=3]="OverlapBack",RangeComparison2[RangeComparison2.Inside=4]="Inside",RangeComparison2[RangeComparison2.Outside=5]="Outside"})(RangeComparison||(RangeComparison={}));function compareRange(range,to){if(range.end.line<to.start.line||range.end.line===to.start.line&&range.end.character<=to.start.character)return RangeComparison.Before;if(range.start.line>to.end.line||range.start.line===to.end.line&&range.start.character>=to.end.character)return RangeComparison.After;const startInside=range.start.line>to.start.line||range.start.line===to.start.line&&range.start.character>=to.start.character,endInside=range.end.line<to.end.line||range.end.line===to.end.line&&range.end.character<=to.end.character;return startInside&&endInside?RangeComparison.Inside:startInside?RangeComparison.OverlapBack:endInside?RangeComparison.OverlapFront:RangeComparison.Outside}function inRange(range,to){return compareRange(range,to)>RangeComparison.After}const DefaultNameRegexp=/^[\w\p{L}]$/u;function findCommentNode(cstNode,commentNames){if(cstNode){const previous=getPreviousNode(cstNode,!0);if(previous&&isCommentNode(previous,commentNames))return previous;if(isRootCstNode(cstNode)){const endIndex=cstNode.content.findIndex(e=>!e.hidden);for(let i=endIndex-1;i>=0;i--){const child=cstNode.content[i];if(isCommentNode(child,commentNames))return child}}}}function isCommentNode(cstNode,commentNames){return isLeafCstNode(cstNode)&&commentNames.includes(cstNode.tokenType.name)}function getPreviousNode(node,hidden=!0){for(;node.container;){const parent=node.container;let index=parent.content.indexOf(node);for(;index>0;){index--;const previous=parent.content[index];if(hidden||!previous.hidden)return previous}node=parent}}class ErrorWithLocation extends Error{constructor(node,message){super(node?`${message} at ${node.range.start.line}:${node.range.start.character}`:message)}}function assertUnreachable(_,message="Error: Got unexpected value."){throw new Error(message)}function cc(char){return char.charCodeAt(0)}function insertToSet(item,set){Array.isArray(item)?item.forEach(function(subItem){set.push(subItem)}):set.push(item)}function addFlag(flagObj,flagKey){if(flagObj[flagKey]===!0)throw"duplicate flag "+flagKey;flagObj[flagKey],flagObj[flagKey]=!0}function ASSERT_EXISTS(obj){if(obj===void 0)throw Error("Internal Error - Should never get here!");return!0}function ASSERT_NEVER_REACH_HERE(){throw Error("Internal Error - Should never get here!")}function isCharacter(obj){return obj.type==="Character"}const digitsCharCodes=[];for(let i=cc("0");i<=cc("9");i++)digitsCharCodes.push(i);const wordCharCodes=[cc("_")].concat(digitsCharCodes);for(let i=cc("a");i<=cc("z");i++)wordCharCodes.push(i);for(let i=cc("A");i<=cc("Z");i++)wordCharCodes.push(i);const whitespaceCodes=[cc(" "),cc("\f"),cc(`
2
+ `),cc("\r"),cc(" "),cc("\v"),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc(" "),cc("\u2028"),cc("\u2029"),cc(" "),cc(" "),cc(" "),cc("\uFEFF")],hexDigitPattern=/[0-9a-fA-F]/,decimalPattern=/[0-9]/,decimalPatternNoZero=/[1-9]/;class RegExpParser{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(newState2){this.idx=newState2.idx,this.input=newState2.input,this.groupIdx=newState2.groupIdx}pattern(input){this.idx=0,this.input=input,this.groupIdx=0,this.consumeChar("/");const value=this.disjunction();this.consumeChar("/");const flags={type:"Flags",loc:{begin:this.idx,end:input.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":addFlag(flags,"global");break;case"i":addFlag(flags,"ignoreCase");break;case"m":addFlag(flags,"multiLine");break;case"u":addFlag(flags,"unicode");break;case"y":addFlag(flags,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags,value,loc:this.loc(0)}}disjunction(){const alts=[],begin=this.idx;for(alts.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),alts.push(this.alternative());return{type:"Disjunction",value:alts,loc:this.loc(begin)}}alternative(){const terms=[],begin=this.idx;for(;this.isTerm();)terms.push(this.term());return{type:"Alternative",value:terms,loc:this.loc(begin)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){const begin=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(begin)};case"$":return{type:"EndAnchor",loc:this.loc(begin)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(begin)};case"B":return{type:"NonWordBoundary",loc:this.loc(begin)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let type;switch(this.popChar()){case"=":type="Lookahead";break;case"!":type="NegativeLookahead";break;case"<":{switch(this.popChar()){case"=":type="Lookbehind";break;case"!":type="NegativeLookbehind"}break}}ASSERT_EXISTS(type);const disjunction=this.disjunction();return this.consumeChar(")"),{type,value:disjunction,loc:this.loc(begin)}}return ASSERT_NEVER_REACH_HERE()}quantifier(isBacktracking=!1){let range;const begin=this.idx;switch(this.popChar()){case"*":range={atLeast:0,atMost:1/0};break;case"+":range={atLeast:1,atMost:1/0};break;case"?":range={atLeast:0,atMost:1};break;case"{":const atLeast=this.integerIncludingZero();switch(this.popChar()){case"}":range={atLeast,atMost:atLeast};break;case",":let atMost;this.isDigit()?(atMost=this.integerIncludingZero(),range={atLeast,atMost}):range={atLeast,atMost:1/0},this.consumeChar("}");break}if(isBacktracking===!0&&range===void 0)return;ASSERT_EXISTS(range);break}if(!(isBacktracking===!0&&range===void 0)&&ASSERT_EXISTS(range))return this.peekChar(0)==="?"?(this.consumeChar("?"),range.greedy=!1):range.greedy=!0,range.type="Quantifier",range.loc=this.loc(begin),range}atom(){let atom2;const begin=this.idx;switch(this.peekChar()){case".":atom2=this.dotAll();break;case"\\":atom2=this.atomEscape();break;case"[":atom2=this.characterClass();break;case"(":atom2=this.group();break}if(atom2===void 0&&this.isPatternCharacter()&&(atom2=this.patternCharacter()),ASSERT_EXISTS(atom2))return atom2.loc=this.loc(begin),this.isQuantifier()&&(atom2.quantifier=this.quantifier()),atom2}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[cc(`
3
+ `),cc("\r"),cc("\u2028"),cc("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:"GroupBackReference",value:this.positiveInteger()}}characterClassEscape(){let set,complement=!1;switch(this.popChar()){case"d":set=digitsCharCodes;break;case"D":set=digitsCharCodes,complement=!0;break;case"s":set=whitespaceCodes;break;case"S":set=whitespaceCodes,complement=!0;break;case"w":set=wordCharCodes;break;case"W":set=wordCharCodes,complement=!0;break}if(ASSERT_EXISTS(set))return{type:"Set",value:set,complement}}controlEscapeAtom(){let escapeCode;switch(this.popChar()){case"f":escapeCode=cc("\f");break;case"n":escapeCode=cc(`
4
+ `);break;case"r":escapeCode=cc("\r");break;case"t":escapeCode=cc(" ");break;case"v":escapeCode=cc("\v");break}if(ASSERT_EXISTS(escapeCode))return{type:"Character",value:escapeCode}}controlLetterEscapeAtom(){this.consumeChar("c");const letter=this.popChar();if(/[a-zA-Z]/.test(letter)===!1)throw Error("Invalid ");return{type:"Character",value:letter.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:cc("\0")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){const escapedChar=this.popChar();return{type:"Character",value:cc(escapedChar)}}classPatternCharacterAtom(){switch(this.peekChar()){case`
5
+ `:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:const nextChar=this.popChar();return{type:"Character",value:cc(nextChar)}}}characterClass(){const set=[];let complement=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),complement=!0);this.isClassAtom();){const from=this.classAtom();if(from.type,isCharacter(from)&&this.isRangeDash()){this.consumeChar("-");const to=this.classAtom();if(to.type,isCharacter(to)){if(to.value<from.value)throw Error("Range out of order in character class");set.push({from:from.value,to:to.value})}else insertToSet(from.value,set),set.push(cc("-")),insertToSet(to.value,set)}else insertToSet(from.value,set)}return this.consumeChar("]"),{type:"Set",complement,value:set}}classAtom(){switch(this.peekChar()){case"]":case`
6
+ `:case"\r":case"\u2028":case"\u2029":throw Error("TBD");case"\\":return this.classEscape();default:return this.classPatternCharacterAtom()}}classEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"b":return this.consumeChar("b"),{type:"Character",value:cc("\b")};case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}group(){let capturing=!0;switch(this.consumeChar("("),this.peekChar(0)){case"?":this.consumeChar("?"),this.consumeChar(":"),capturing=!1;break;default:this.groupIdx++;break}const value=this.disjunction();this.consumeChar(")");const groupAst={type:"Group",capturing,value};return capturing&&(groupAst.idx=this.groupIdx),groupAst}positiveInteger(){let number=this.popChar();if(decimalPatternNoZero.test(number)===!1)throw Error("Expecting a positive integer");for(;decimalPattern.test(this.peekChar(0));)number+=this.popChar();return parseInt(number,10)}integerIncludingZero(){let number=this.popChar();if(decimalPattern.test(number)===!1)throw Error("Expecting an integer");for(;decimalPattern.test(this.peekChar(0));)number+=this.popChar();return parseInt(number,10)}patternCharacter(){const nextChar=this.popChar();switch(nextChar){case`
7
+ `:case"\r":case"\u2028":case"\u2029":case"^":case"$":case"\\":case".":case"*":case"+":case"?":case"(":case")":case"[":case"|":throw Error("TBD");default:return{type:"Character",value:cc(nextChar)}}}isRegExpFlag(){switch(this.peekChar(0)){case"g":case"i":case"m":case"u":case"y":return!0;default:return!1}}isRangeDash(){return this.peekChar()==="-"&&this.isClassAtom(1)}isDigit(){return decimalPattern.test(this.peekChar(0))}isClassAtom(howMuch=0){switch(this.peekChar(howMuch)){case"]":case`
8
+ `:case"\r":case"\u2028":case"\u2029":return!1;default:return!0}}isTerm(){return this.isAtom()||this.isAssertion()}isAtom(){if(this.isPatternCharacter())return!0;switch(this.peekChar(0)){case".":case"\\":case"[":case"(":return!0;default:return!1}}isAssertion(){switch(this.peekChar(0)){case"^":case"$":return!0;case"\\":switch(this.peekChar(1)){case"b":case"B":return!0;default:return!1}case"(":return this.peekChar(1)==="?"&&(this.peekChar(2)==="="||this.peekChar(2)==="!"||this.peekChar(2)==="<"&&(this.peekChar(3)==="="||this.peekChar(3)==="!"));default:return!1}}isQuantifier(){const prevState=this.saveState();try{return this.quantifier(!0)!==void 0}catch{return!1}finally{this.restoreState(prevState)}}isPatternCharacter(){switch(this.peekChar()){case"^":case"$":case"\\":case".":case"*":case"+":case"?":case"(":case")":case"[":case"|":case"/":case`
9
+ `:case"\r":case"\u2028":case"\u2029":return!1;default:return!0}}parseHexDigits(howMany){let hexString="";for(let i=0;i<howMany;i++){const hexChar=this.popChar();if(hexDigitPattern.test(hexChar)===!1)throw Error("Expecting a HexDecimal digits");hexString+=hexChar}return{type:"Character",value:parseInt(hexString,16)}}peekChar(howMuch=0){return this.input[this.idx+howMuch]}popChar(){const nextChar=this.peekChar(0);return this.consumeChar(void 0),nextChar}consumeChar(char){if(char!==void 0&&this.input[this.idx]!==char)throw Error("Expected: '"+char+"' but found: '"+this.input[this.idx]+"' at offset: "+this.idx);if(this.idx>=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(begin){return{begin,end:this.idx}}}class BaseRegExpVisitor{visitChildren(node){for(const key in node){const child=node[key];node.hasOwnProperty(key)&&(child.type!==void 0?this.visit(child):Array.isArray(child)&&child.forEach(subChild=>{this.visit(subChild)},this))}}visit(node){switch(node.type){case"Pattern":this.visitPattern(node);break;case"Flags":this.visitFlags(node);break;case"Disjunction":this.visitDisjunction(node);break;case"Alternative":this.visitAlternative(node);break;case"StartAnchor":this.visitStartAnchor(node);break;case"EndAnchor":this.visitEndAnchor(node);break;case"WordBoundary":this.visitWordBoundary(node);break;case"NonWordBoundary":this.visitNonWordBoundary(node);break;case"Lookahead":this.visitLookahead(node);break;case"NegativeLookahead":this.visitNegativeLookahead(node);break;case"Lookbehind":this.visitLookbehind(node);break;case"NegativeLookbehind":this.visitNegativeLookbehind(node);break;case"Character":this.visitCharacter(node);break;case"Set":this.visitSet(node);break;case"Group":this.visitGroup(node);break;case"GroupBackReference":this.visitGroupBackReference(node);break;case"Quantifier":this.visitQuantifier(node);break}this.visitChildren(node)}visitPattern(node){}visitFlags(node){}visitDisjunction(node){}visitAlternative(node){}visitStartAnchor(node){}visitEndAnchor(node){}visitWordBoundary(node){}visitNonWordBoundary(node){}visitLookahead(node){}visitNegativeLookahead(node){}visitLookbehind(node){}visitNegativeLookbehind(node){}visitCharacter(node){}visitSet(node){}visitGroup(node){}visitGroupBackReference(node){}visitQuantifier(node){}}const NEWLINE_REGEXP=/\r?\n/gm,regexpParser=new RegExpParser;class TerminalRegExpVisitor extends BaseRegExpVisitor{constructor(){super(...arguments),this.isStarting=!0,this.endRegexpStack=[],this.multiline=!1}get endRegex(){return this.endRegexpStack.join("")}reset(regex){this.multiline=!1,this.regex=regex,this.startRegexp="",this.isStarting=!0,this.endRegexpStack=[]}visitGroup(node){node.quantifier&&(this.isStarting=!1,this.endRegexpStack=[])}visitCharacter(node){const char=String.fromCharCode(node.value);if(!this.multiline&&char===`
10
+ `&&(this.multiline=!0),node.quantifier)this.isStarting=!1,this.endRegexpStack=[];else{const escapedChar=escapeRegExp(char);this.endRegexpStack.push(escapedChar),this.isStarting&&(this.startRegexp+=escapedChar)}}visitSet(node){if(!this.multiline){const set=this.regex.substring(node.loc.begin,node.loc.end),regex=new RegExp(set);this.multiline=!!`
11
+ `.match(regex)}if(node.quantifier)this.isStarting=!1,this.endRegexpStack=[];else{const set=this.regex.substring(node.loc.begin,node.loc.end);this.endRegexpStack.push(set),this.isStarting&&(this.startRegexp+=set)}}visitChildren(node){node.type==="Group"&&node.quantifier||super.visitChildren(node)}}const visitor=new TerminalRegExpVisitor;function isMultilineComment(regexp){try{return typeof regexp=="string"&&(regexp=new RegExp(regexp)),regexp=regexp.toString(),visitor.reset(regexp),visitor.visit(regexpParser.pattern(regexp)),visitor.multiline}catch{return!1}}const whitespaceCharacters=`\f
12
+ \r \v              \u2028\u2029   \uFEFF`.split("");function isWhitespace(value){const regexp=typeof value=="string"?new RegExp(value):value;return whitespaceCharacters.some(ws=>regexp.test(ws))}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function partialMatches(regex,input){const partial=partialRegExp(regex),match=input.match(partial);return!!match&&match[0].length>0}function partialRegExp(regex){typeof regex=="string"&&(regex=new RegExp(regex));const re=regex,source=regex.source;let i=0;function process2(){let result="",tmp;function appendRaw(nbChars){result+=source.substr(i,nbChars),i+=nbChars}function appendOptional(nbChars){result+="(?:"+source.substr(i,nbChars)+"|$)",i+=nbChars}for(;i<source.length;)switch(source[i]){case"\\":switch(source[i+1]){case"c":appendOptional(3);break;case"x":appendOptional(4);break;case"u":re.unicode?source[i+2]==="{"?appendOptional(source.indexOf("}",i)-i+1):appendOptional(6):appendOptional(2);break;case"p":case"P":re.unicode?appendOptional(source.indexOf("}",i)-i+1):appendOptional(2);break;case"k":appendOptional(source.indexOf(">",i)-i+1);break;default:appendOptional(2);break}break;case"[":tmp=/\[(?:\\.|.)*?\]/g,tmp.lastIndex=i,tmp=tmp.exec(source)||[],appendOptional(tmp[0].length);break;case"|":case"^":case"$":case"*":case"+":case"?":appendRaw(1);break;case"{":tmp=/\{\d+,?\d*\}/g,tmp.lastIndex=i,tmp=tmp.exec(source),tmp?appendRaw(tmp[0].length):appendOptional(1);break;case"(":if(source[i+1]==="?")switch(source[i+2]){case":":result+="(?:",i+=3,result+=process2()+"|$)";break;case"=":result+="(?=",i+=3,result+=process2()+")";break;case"!":tmp=i,i+=3,process2(),result+=source.substr(tmp,i-tmp);break;case"<":switch(source[i+3]){case"=":case"!":tmp=i,i+=4,process2(),result+=source.substr(tmp,i-tmp);break;default:appendRaw(source.indexOf(">",i)-i+1),result+=process2()+"|$)";break}break}else appendRaw(1),result+=process2()+"|$)";break;case")":return++i,result;default:appendOptional(1);break}return result}return new RegExp(process2(),regex.flags)}function getEntryRule(grammar){return grammar.rules.find(e=>isParserRule(e)&&e.entry)}function getHiddenRules(grammar){return grammar.rules.filter(e=>isTerminalRule(e)&&e.hidden)}function getAllReachableRules(grammar,allTerminals){const ruleNames=new Set,entryRule=getEntryRule(grammar);if(!entryRule)return new Set(grammar.rules);const topMostRules=[entryRule].concat(getHiddenRules(grammar));for(const rule of topMostRules)ruleDfs(rule,ruleNames,allTerminals);const rules=new Set;for(const rule of grammar.rules)(ruleNames.has(rule.name)||isTerminalRule(rule)&&rule.hidden)&&rules.add(rule);return rules}function ruleDfs(rule,visitedSet,allTerminals){visitedSet.add(rule.name),streamAllContents(rule).forEach(node=>{if(isRuleCall(node)||allTerminals){const refRule=node.rule.ref;refRule&&!visitedSet.has(refRule.name)&&ruleDfs(refRule,visitedSet,allTerminals)}})}function getCrossReferenceTerminal(crossRef){if(crossRef.terminal)return crossRef.terminal;if(crossRef.type.ref){const nameAssigment=findNameAssignment(crossRef.type.ref);return nameAssigment==null?void 0:nameAssigment.terminal}}function isCommentTerminal(terminalRule){return terminalRule.hidden&&!isWhitespace(terminalRegex(terminalRule))}function findNodesForProperty(node,property){return!node||!property?[]:findNodesForPropertyInternal(node,property,node.astNode,!0)}function findNodeForProperty(node,property,index){if(!node||!property)return;const nodes=findNodesForPropertyInternal(node,property,node.astNode,!0);if(nodes.length!==0)return index!==void 0?index=Math.max(0,Math.min(index,nodes.length-1)):index=0,nodes[index]}function findNodesForPropertyInternal(node,property,element,first2){if(!first2){const nodeFeature=getContainerOfType(node.grammarSource,isAssignment);if(nodeFeature&&nodeFeature.feature===property)return[node]}return isCompositeCstNode(node)&&node.astNode===element?node.content.flatMap(e=>findNodesForPropertyInternal(e,property,element,!1)):[]}function findNodeForKeyword(node,keyword,index){if(!node)return;const nodes=findNodesForKeywordInternal(node,keyword,node==null?void 0:node.astNode);if(nodes.length!==0)return index!==void 0?index=Math.max(0,Math.min(index,nodes.length-1)):index=0,nodes[index]}function findNodesForKeywordInternal(node,keyword,element){if(node.astNode!==element)return[];if(isKeyword(node.grammarSource)&&node.grammarSource.value===keyword)return[node];const treeIterator=streamCst(node).iterator();let result;const keywordNodes=[];do if(result=treeIterator.next(),!result.done){const childNode=result.value;childNode.astNode===element?isKeyword(childNode.grammarSource)&&childNode.grammarSource.value===keyword&&keywordNodes.push(childNode):treeIterator.prune()}while(!result.done);return keywordNodes}function findAssignment(cstNode){var _a21;const astNode=cstNode.astNode;for(;astNode===((_a21=cstNode.container)==null?void 0:_a21.astNode);){const assignment=getContainerOfType(cstNode.grammarSource,isAssignment);if(assignment)return assignment;cstNode=cstNode.container}}function findNameAssignment(type){let startNode=type;return isInferredType(startNode)&&(isAction(startNode.$container)?startNode=startNode.$container.$container:isAbstractParserRule(startNode.$container)?startNode=startNode.$container:assertUnreachable(startNode.$container)),findNameAssignmentInternal(type,startNode,new Map)}function findNameAssignmentInternal(type,startNode,cache){var _a21;function go(node,refType){let childAssignment;return getContainerOfType(node,isAssignment)||(childAssignment=findNameAssignmentInternal(refType,refType,cache)),cache.set(type,childAssignment),childAssignment}if(cache.has(type))return cache.get(type);cache.set(type,void 0);for(const node of streamAllContents(startNode)){if(isAssignment(node)&&node.feature.toLowerCase()==="name")return cache.set(type,node),node;if(isRuleCall(node)&&isParserRule(node.rule.ref))return go(node,node.rule.ref);if(isSimpleType(node)&&((_a21=node.typeRef)!=null&&_a21.ref))return go(node,node.typeRef.ref)}}function isDataTypeRule(rule){return isDataTypeRuleInternal(rule,new Set)}function isDataTypeRuleInternal(rule,visited){if(visited.has(rule))return!0;visited.add(rule);for(const node of streamAllContents(rule))if(isRuleCall(node)){if(!node.rule.ref||isParserRule(node.rule.ref)&&!isDataTypeRuleInternal(node.rule.ref,visited)||isInfixRule(node.rule.ref))return!1}else{if(isAssignment(node))return!1;if(isAction(node))return!1}return!!rule.definition}function getExplicitRuleType(rule){if(!isTerminalRule(rule)){if(rule.inferredType)return rule.inferredType.name;if(rule.dataType)return rule.dataType;if(rule.returnType){const refType=rule.returnType.ref;if(refType)return refType.name}}}function getTypeName(type){if(isAbstractParserRule(type))return isParserRule(type)&&isDataTypeRule(type)?type.name:getExplicitRuleType(type)??type.name;if(isInterface(type)||isType(type)||isReturnType(type))return type.name;if(isAction(type)){const actionType=getActionType(type);if(actionType)return actionType}else if(isInferredType(type))return type.name;throw new Error("Cannot get name of Unknown Type")}function getActionType(action){var _a21;if(action.inferredType)return action.inferredType.name;if((_a21=action.type)!=null&&_a21.ref)return getTypeName(action.type.ref)}function getRuleType(rule){var _a21;return isTerminalRule(rule)?((_a21=rule.type)==null?void 0:_a21.name)??"string":getExplicitRuleType(rule)??rule.name}function terminalRegex(terminalRule){const flags={s:!1,i:!1,u:!1},source=abstractElementToRegex(terminalRule.definition,flags),flagText=Object.entries(flags).filter(([,value])=>value).map(([name])=>name).join("");return new RegExp(source,flagText)}const WILDCARD=/[\s\S]/.source;function abstractElementToRegex(element,flags){var _a21;if(isTerminalAlternatives(element))return terminalAlternativesToRegex(element);if(isTerminalGroup(element))return terminalGroupToRegex(element);if(isCharacterRange(element))return characterRangeToRegex(element);if(isTerminalRuleCall(element)){const rule=element.rule.ref;if(!rule)throw new Error("Missing rule reference.");return withCardinality(abstractElementToRegex(rule.definition),{cardinality:element.cardinality,lookahead:element.lookahead,parenthesized:element.parenthesized})}else{if(isNegatedToken(element))return negateTokenToRegex(element);if(isUntilToken(element))return untilTokenToRegex(element);if(isRegexToken(element)){const lastSlash=element.regex.lastIndexOf("/"),source=element.regex.substring(1,lastSlash),regexFlags=element.regex.substring(lastSlash+1);return flags&&(flags.i=regexFlags.includes("i"),flags.s=regexFlags.includes("s"),flags.u=regexFlags.includes("u")),withCardinality(source,{cardinality:element.cardinality,lookahead:element.lookahead,parenthesized:element.parenthesized,wrap:!1})}else{if(isWildcard(element))return withCardinality(WILDCARD,{cardinality:element.cardinality,lookahead:element.lookahead,parenthesized:element.parenthesized});throw new Error(`Invalid terminal element: ${element==null?void 0:element.$type}, ${(_a21=element==null?void 0:element.$cstNode)==null?void 0:_a21.text}`)}}}function terminalAlternativesToRegex(alternatives){return withCardinality(alternatives.elements.map(e=>abstractElementToRegex(e)).join("|"),{cardinality:alternatives.cardinality,lookahead:alternatives.lookahead,parenthesized:alternatives.parenthesized,wrap:!1})}function terminalGroupToRegex(group){return withCardinality(group.elements.map(e=>abstractElementToRegex(e)).join(""),{cardinality:group.cardinality,lookahead:group.lookahead,parenthesized:group.parenthesized,wrap:!1})}function untilTokenToRegex(until){return withCardinality(`${WILDCARD}*?${abstractElementToRegex(until.terminal)}`,{cardinality:until.cardinality,lookahead:until.lookahead,parenthesized:until.parenthesized})}function negateTokenToRegex(negate){return withCardinality(`(?!${abstractElementToRegex(negate.terminal)})${WILDCARD}*?`,{cardinality:negate.cardinality,lookahead:negate.lookahead,parenthesized:negate.parenthesized})}function characterRangeToRegex(range){return range.right?withCardinality(`[${keywordToRegex(range.left)}-${keywordToRegex(range.right)}]`,{cardinality:range.cardinality,lookahead:range.lookahead,parenthesized:range.parenthesized,wrap:!1}):withCardinality(keywordToRegex(range.left),{cardinality:range.cardinality,lookahead:range.lookahead,parenthesized:range.parenthesized,wrap:!1})}function keywordToRegex(keyword){return escapeRegExp(keyword.value)}function withCardinality(regex,options){return(options.parenthesized||options.lookahead||options.wrap!==!1)&&(regex=`(${options.lookahead??(options.parenthesized?"":"?:")}${regex})`),options.cardinality?`${regex}${options.cardinality}`:regex}function createGrammarConfig(services){const rules=[],grammar=services.Grammar;for(const rule of grammar.rules)isTerminalRule(rule)&&isCommentTerminal(rule)&&isMultilineComment(terminalRegex(rule))&&rules.push(rule.name);return{multilineCommentRules:rules,nameRegexp:DefaultNameRegexp}}function PRINT_ERROR(msg){console&&console.error&&console.error(`Error: ${msg}`)}function PRINT_WARNING(msg){console&&console.warn&&console.warn(`Warning: ${msg}`)}function timer(func){const start=new Date().getTime(),val=func();return{time:new Date().getTime()-start,value:val}}function toFastProperties(toBecomeFast){function FakeConstructor(){}FakeConstructor.prototype=toBecomeFast;const fakeInstance=new FakeConstructor;function fakeAccess(){return typeof fakeInstance.bar}return fakeAccess(),fakeAccess(),toBecomeFast}function tokenLabel$1(tokType){return hasTokenLabel$1(tokType)?tokType.LABEL:tokType.name}function hasTokenLabel$1(obj){return typeof obj.LABEL=="string"&&obj.LABEL!==""}class AbstractProduction{get definition(){return this._definition}set definition(value){this._definition=value}constructor(_definition){this._definition=_definition}accept(visitor2){visitor2.visit(this),this.definition.forEach(prod=>{prod.accept(visitor2)})}}class NonTerminal extends AbstractProduction{constructor(options){super([]),this.idx=1,Object.assign(this,pickOnlyDefined(options))}set definition(definition){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(visitor2){visitor2.visit(this)}}class Rule extends AbstractProduction{constructor(options){super(options.definition),this.orgText="",Object.assign(this,pickOnlyDefined(options))}}class Alternative extends AbstractProduction{constructor(options){super(options.definition),this.ignoreAmbiguities=!1,Object.assign(this,pickOnlyDefined(options))}}let Option$1=class extends AbstractProduction{constructor(options){super(options.definition),this.idx=1,Object.assign(this,pickOnlyDefined(options))}};class RepetitionMandatory extends AbstractProduction{constructor(options){super(options.definition),this.idx=1,Object.assign(this,pickOnlyDefined(options))}}class RepetitionMandatoryWithSeparator extends AbstractProduction{constructor(options){super(options.definition),this.idx=1,Object.assign(this,pickOnlyDefined(options))}}class Repetition extends AbstractProduction{constructor(options){super(options.definition),this.idx=1,Object.assign(this,pickOnlyDefined(options))}}class RepetitionWithSeparator extends AbstractProduction{constructor(options){super(options.definition),this.idx=1,Object.assign(this,pickOnlyDefined(options))}}class Alternation extends AbstractProduction{get definition(){return this._definition}set definition(value){this._definition=value}constructor(options){super(options.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,Object.assign(this,pickOnlyDefined(options))}}class Terminal{constructor(options){this.idx=1,Object.assign(this,pickOnlyDefined(options))}accept(visitor2){visitor2.visit(this)}}function serializeGrammar(topRules){return topRules.map(serializeProduction)}function serializeProduction(node){function convertDefinition(definition){return definition.map(serializeProduction)}if(node instanceof NonTerminal){const serializedNonTerminal={type:"NonTerminal",name:node.nonTerminalName,idx:node.idx};return typeof node.label=="string"&&(serializedNonTerminal.label=node.label),serializedNonTerminal}else{if(node instanceof Alternative)return{type:"Alternative",definition:convertDefinition(node.definition)};if(node instanceof Option$1)return{type:"Option",idx:node.idx,definition:convertDefinition(node.definition)};if(node instanceof RepetitionMandatory)return{type:"RepetitionMandatory",idx:node.idx,definition:convertDefinition(node.definition)};if(node instanceof RepetitionMandatoryWithSeparator)return{type:"RepetitionMandatoryWithSeparator",idx:node.idx,separator:serializeProduction(new Terminal({terminalType:node.separator})),definition:convertDefinition(node.definition)};if(node instanceof RepetitionWithSeparator)return{type:"RepetitionWithSeparator",idx:node.idx,separator:serializeProduction(new Terminal({terminalType:node.separator})),definition:convertDefinition(node.definition)};if(node instanceof Repetition)return{type:"Repetition",idx:node.idx,definition:convertDefinition(node.definition)};if(node instanceof Alternation)return{type:"Alternation",idx:node.idx,definition:convertDefinition(node.definition)};if(node instanceof Terminal){const serializedTerminal={type:"Terminal",name:node.terminalType.name,label:tokenLabel$1(node.terminalType),idx:node.idx};typeof node.label=="string"&&(serializedTerminal.terminalLabel=node.label);const pattern=node.terminalType.PATTERN;return node.terminalType.PATTERN&&(serializedTerminal.pattern=pattern instanceof RegExp?pattern.source:pattern),serializedTerminal}else{if(node instanceof Rule)return{type:"Rule",name:node.name,orgText:node.orgText,definition:convertDefinition(node.definition)};throw Error("non exhaustive match")}}}function pickOnlyDefined(obj){return Object.fromEntries(Object.entries(obj).filter(([,v])=>v!==void 0))}class GAstVisitor{visit(node){const nodeAny=node;switch(nodeAny.constructor){case NonTerminal:return this.visitNonTerminal(nodeAny);case Alternative:return this.visitAlternative(nodeAny);case Option$1:return this.visitOption(nodeAny);case RepetitionMandatory:return this.visitRepetitionMandatory(nodeAny);case RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(nodeAny);case RepetitionWithSeparator:return this.visitRepetitionWithSeparator(nodeAny);case Repetition:return this.visitRepetition(nodeAny);case Alternation:return this.visitAlternation(nodeAny);case Terminal:return this.visitTerminal(nodeAny);case Rule:return this.visitRule(nodeAny);default:throw Error("non exhaustive match")}}visitNonTerminal(node){}visitAlternative(node){}visitOption(node){}visitRepetition(node){}visitRepetitionMandatory(node){}visitRepetitionMandatoryWithSeparator(node){}visitRepetitionWithSeparator(node){}visitAlternation(node){}visitTerminal(node){}visitRule(node){}}function isSequenceProd(prod){return prod instanceof Alternative||prod instanceof Option$1||prod instanceof Repetition||prod instanceof RepetitionMandatory||prod instanceof RepetitionMandatoryWithSeparator||prod instanceof RepetitionWithSeparator||prod instanceof Terminal||prod instanceof Rule}function isOptionalProd(prod,alreadyVisited=[]){return prod instanceof Option$1||prod instanceof Repetition||prod instanceof RepetitionWithSeparator?!0:prod instanceof Alternation?prod.definition.some(subProd=>isOptionalProd(subProd,alreadyVisited)):prod instanceof NonTerminal&&alreadyVisited.includes(prod)?!1:prod instanceof AbstractProduction?(prod instanceof NonTerminal&&alreadyVisited.push(prod),prod.definition.every(subProd=>isOptionalProd(subProd,alreadyVisited))):!1}function isBranchingProd(prod){return prod instanceof Alternation}function getProductionDslName$1(prod){if(prod instanceof NonTerminal)return"SUBRULE";if(prod instanceof Option$1)return"OPTION";if(prod instanceof Alternation)return"OR";if(prod instanceof RepetitionMandatory)return"AT_LEAST_ONE";if(prod instanceof RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(prod instanceof RepetitionWithSeparator)return"MANY_SEP";if(prod instanceof Repetition)return"MANY";if(prod instanceof Terminal)return"CONSUME";throw Error("non exhaustive match")}class RestWalker{walk(prod,prevRest=[]){prod.definition.forEach((subProd,index)=>{const currRest=prod.definition.slice(index+1);if(subProd instanceof NonTerminal)this.walkProdRef(subProd,currRest,prevRest);else if(subProd instanceof Terminal)this.walkTerminal(subProd,currRest,prevRest);else if(subProd instanceof Alternative)this.walkFlat(subProd,currRest,prevRest);else if(subProd instanceof Option$1)this.walkOption(subProd,currRest,prevRest);else if(subProd instanceof RepetitionMandatory)this.walkAtLeastOne(subProd,currRest,prevRest);else if(subProd instanceof RepetitionMandatoryWithSeparator)this.walkAtLeastOneSep(subProd,currRest,prevRest);else if(subProd instanceof RepetitionWithSeparator)this.walkManySep(subProd,currRest,prevRest);else if(subProd instanceof Repetition)this.walkMany(subProd,currRest,prevRest);else if(subProd instanceof Alternation)this.walkOr(subProd,currRest,prevRest);else throw Error("non exhaustive match")})}walkTerminal(terminal,currRest,prevRest){}walkProdRef(refProd,currRest,prevRest){}walkFlat(flatProd,currRest,prevRest){const fullOrRest=currRest.concat(prevRest);this.walk(flatProd,fullOrRest)}walkOption(optionProd,currRest,prevRest){const fullOrRest=currRest.concat(prevRest);this.walk(optionProd,fullOrRest)}walkAtLeastOne(atLeastOneProd,currRest,prevRest){const fullAtLeastOneRest=[new Option$1({definition:atLeastOneProd.definition})].concat(currRest,prevRest);this.walk(atLeastOneProd,fullAtLeastOneRest)}walkAtLeastOneSep(atLeastOneSepProd,currRest,prevRest){const fullAtLeastOneSepRest=restForRepetitionWithSeparator(atLeastOneSepProd,currRest,prevRest);this.walk(atLeastOneSepProd,fullAtLeastOneSepRest)}walkMany(manyProd,currRest,prevRest){const fullManyRest=[new Option$1({definition:manyProd.definition})].concat(currRest,prevRest);this.walk(manyProd,fullManyRest)}walkManySep(manySepProd,currRest,prevRest){const fullManySepRest=restForRepetitionWithSeparator(manySepProd,currRest,prevRest);this.walk(manySepProd,fullManySepRest)}walkOr(orProd,currRest,prevRest){const fullOrRest=currRest.concat(prevRest);orProd.definition.forEach(alt=>{const prodWrapper=new Alternative({definition:[alt]});this.walk(prodWrapper,fullOrRest)})}}function restForRepetitionWithSeparator(repSepProd,currRest,prevRest){return[new Option$1({definition:[new Terminal({terminalType:repSepProd.separator})].concat(repSepProd.definition)})].concat(currRest,prevRest)}function first(prod){if(prod instanceof NonTerminal)return first(prod.referencedRule);if(prod instanceof Terminal)return firstForTerminal(prod);if(isSequenceProd(prod))return firstForSequence(prod);if(isBranchingProd(prod))return firstForBranching(prod);throw Error("non exhaustive match")}function firstForSequence(prod){let firstSet=[];const seq=prod.definition;let nextSubProdIdx=0,hasInnerProdsRemaining=seq.length>nextSubProdIdx,currSubProd,isLastInnerProdOptional=!0;for(;hasInnerProdsRemaining&&isLastInnerProdOptional;)currSubProd=seq[nextSubProdIdx],isLastInnerProdOptional=isOptionalProd(currSubProd),firstSet=firstSet.concat(first(currSubProd)),nextSubProdIdx=nextSubProdIdx+1,hasInnerProdsRemaining=seq.length>nextSubProdIdx;return[...new Set(firstSet)]}function firstForBranching(prod){const allAlternativesFirsts=prod.definition.map(innerProd=>first(innerProd));return[...new Set(allAlternativesFirsts.flat())]}function firstForTerminal(terminal){return[terminal.terminalType]}const IN="_~IN~_";class ResyncFollowsWalker extends RestWalker{constructor(topProd){super(),this.topProd=topProd,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(terminal,currRest,prevRest){}walkProdRef(refProd,currRest,prevRest){const followName=buildBetweenProdsFollowPrefix(refProd.referencedRule,refProd.idx)+this.topProd.name,fullRest=currRest.concat(prevRest),restProd=new Alternative({definition:fullRest}),t_in_topProd_follows=first(restProd);this.follows[followName]=t_in_topProd_follows}}function computeAllProdsFollows(topProductions){const reSyncFollows={};return topProductions.forEach(topProd=>{const currRefsFollow=new ResyncFollowsWalker(topProd).startWalking();Object.assign(reSyncFollows,currRefsFollow)}),reSyncFollows}function buildBetweenProdsFollowPrefix(inner,occurenceInParent){return inner.name+occurenceInParent+IN}let regExpAstCache={};const regExpParser=new RegExpParser;function getRegExpAst(regExp){const regExpStr=regExp.toString();if(regExpAstCache.hasOwnProperty(regExpStr))return regExpAstCache[regExpStr];{const regExpAst=regExpParser.pattern(regExpStr);return regExpAstCache[regExpStr]=regExpAst,regExpAst}}function clearRegExpParserCache(){regExpAstCache={}}const complementErrorMessage="Complement Sets are not supported for first char optimization",failedOptimizationPrefixMsg=`Unable to use "first char" lexer optimizations:
13
+ `;function getOptimizedStartCodesIndices(regExp,ensureOptimizations=!1){try{const ast=getRegExpAst(regExp);return firstCharOptimizedIndices(ast.value,{},ast.flags.ignoreCase)}catch(e){if(e.message===complementErrorMessage)ensureOptimizations&&PRINT_WARNING(`${failedOptimizationPrefixMsg} Unable to optimize: < ${regExp.toString()} >
14
+ Complement Sets cannot be automatically optimized.
15
+ This will disable the lexer's first char optimizations.
16
+ See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let msgSuffix="";ensureOptimizations&&(msgSuffix=`
17
+ This will disable the lexer's first char optimizations.
18
+ See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),PRINT_ERROR(`${failedOptimizationPrefixMsg}
19
+ Failed parsing: < ${regExp.toString()} >
20
+ Using the @chevrotain/regexp-to-ast library
21
+ Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+msgSuffix)}}return[]}function firstCharOptimizedIndices(ast,result,ignoreCase){switch(ast.type){case"Disjunction":for(let i=0;i<ast.value.length;i++)firstCharOptimizedIndices(ast.value[i],result,ignoreCase);break;case"Alternative":const terms=ast.value;for(let i=0;i<terms.length;i++){const term=terms[i];switch(term.type){case"EndAnchor":case"GroupBackReference":case"Lookahead":case"NegativeLookahead":case"Lookbehind":case"NegativeLookbehind":case"StartAnchor":case"WordBoundary":case"NonWordBoundary":continue}const atom2=term;switch(atom2.type){case"Character":addOptimizedIdxToResult(atom2.value,result,ignoreCase);break;case"Set":if(atom2.complement===!0)throw Error(complementErrorMessage);atom2.value.forEach(code=>{if(typeof code=="number")addOptimizedIdxToResult(code,result,ignoreCase);else{const range=code;if(ignoreCase===!0)for(let rangeCode=range.from;rangeCode<=range.to;rangeCode++)addOptimizedIdxToResult(rangeCode,result,ignoreCase);else{for(let rangeCode=range.from;rangeCode<=range.to&&rangeCode<minOptimizationVal;rangeCode++)addOptimizedIdxToResult(rangeCode,result,ignoreCase);if(range.to>=minOptimizationVal){const minUnOptVal=range.from>=minOptimizationVal?range.from:minOptimizationVal,maxUnOptVal=range.to,minOptIdx=charCodeToOptimizedIndex(minUnOptVal),maxOptIdx=charCodeToOptimizedIndex(maxUnOptVal);for(let currOptIdx=minOptIdx;currOptIdx<=maxOptIdx;currOptIdx++)result[currOptIdx]=currOptIdx}}}});break;case"Group":firstCharOptimizedIndices(atom2.value,result,ignoreCase);break;default:throw Error("Non Exhaustive Match")}const isOptionalQuantifier=atom2.quantifier!==void 0&&atom2.quantifier.atLeast===0;if(atom2.type==="Group"&&isWholeOptional(atom2)===!1||atom2.type!=="Group"&&isOptionalQuantifier===!1)break}break;default:throw Error("non exhaustive match!")}return Object.values(result)}function addOptimizedIdxToResult(code,result,ignoreCase){const optimizedCharIdx=charCodeToOptimizedIndex(code);result[optimizedCharIdx]=optimizedCharIdx,ignoreCase===!0&&handleIgnoreCase(code,result)}function handleIgnoreCase(code,result){const char=String.fromCharCode(code),upperChar=char.toUpperCase();if(upperChar!==char){const optimizedCharIdx=charCodeToOptimizedIndex(upperChar.charCodeAt(0));result[optimizedCharIdx]=optimizedCharIdx}else{const lowerChar=char.toLowerCase();if(lowerChar!==char){const optimizedCharIdx=charCodeToOptimizedIndex(lowerChar.charCodeAt(0));result[optimizedCharIdx]=optimizedCharIdx}}}function findCode(setNode,targetCharCodes){return setNode.value.find(codeOrRange=>{if(typeof codeOrRange=="number")return targetCharCodes.includes(codeOrRange);{const range=codeOrRange;return targetCharCodes.find(targetCode=>range.from<=targetCode&&targetCode<=range.to)!==void 0}})}function isWholeOptional(ast){const quantifier=ast.quantifier;return quantifier&&quantifier.atLeast===0?!0:ast.value?Array.isArray(ast.value)?ast.value.every(isWholeOptional):isWholeOptional(ast.value):!1}class CharCodeFinder extends BaseRegExpVisitor{constructor(targetCharCodes){super(),this.targetCharCodes=targetCharCodes,this.found=!1}visitChildren(node){if(this.found!==!0){switch(node.type){case"Lookahead":this.visitLookahead(node);return;case"NegativeLookahead":this.visitNegativeLookahead(node);return;case"Lookbehind":this.visitLookbehind(node);return;case"NegativeLookbehind":this.visitNegativeLookbehind(node);return}super.visitChildren(node)}}visitCharacter(node){this.targetCharCodes.includes(node.value)&&(this.found=!0)}visitSet(node){node.complement?findCode(node,this.targetCharCodes)===void 0&&(this.found=!0):findCode(node,this.targetCharCodes)!==void 0&&(this.found=!0)}}function canMatchCharCode(charCodes,pattern){if(pattern instanceof RegExp){const ast=getRegExpAst(pattern),charCodeFinder=new CharCodeFinder(charCodes);return charCodeFinder.visit(ast),charCodeFinder.found}else{for(const char of pattern){const charCode=char.charCodeAt(0);if(charCodes.includes(charCode))return!0}return!1}}const PATTERN="PATTERN",DEFAULT_MODE="defaultMode",MODES="modes";function analyzeTokenTypes(tokenTypes,options){options=Object.assign({safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",`
22
+ `],tracer:(msg,action)=>action()},options);const tracer=options.tracer;tracer("initCharCodeToOptimizedIndexMap",()=>{initCharCodeToOptimizedIndexMap()});let onlyRelevantTypes;tracer("Reject Lexer.NA",()=>{onlyRelevantTypes=tokenTypes.filter(currType=>currType[PATTERN]!==Lexer.NA)});let hasCustom=!1,allTransformedPatterns;tracer("Transform Patterns",()=>{hasCustom=!1,allTransformedPatterns=onlyRelevantTypes.map(currType=>{const currPattern=currType[PATTERN];if(currPattern instanceof RegExp){const regExpSource=currPattern.source;return regExpSource.length===1&&regExpSource!=="^"&&regExpSource!=="$"&&regExpSource!=="."&&!currPattern.ignoreCase?regExpSource:regExpSource.length===2&&regExpSource[0]==="\\"&&!["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"].includes(regExpSource[1])?regExpSource[1]:addStickyFlag(currPattern)}else{if(typeof currPattern=="function")return hasCustom=!0,{exec:currPattern};if(typeof currPattern=="object")return hasCustom=!0,currPattern;if(typeof currPattern=="string"){if(currPattern.length===1)return currPattern;{const escapedRegExpString=currPattern.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),wrappedRegExp=new RegExp(escapedRegExpString);return addStickyFlag(wrappedRegExp)}}else throw Error("non exhaustive match")}})});let patternIdxToType,patternIdxToGroup,patternIdxToLongerAltIdxArr,patternIdxToPushMode,patternIdxToPopMode;tracer("misc mapping",()=>{patternIdxToType=onlyRelevantTypes.map(currType=>currType.tokenTypeIdx),patternIdxToGroup=onlyRelevantTypes.map(clazz=>{const groupName=clazz.GROUP;if(groupName!==Lexer.SKIPPED){if(typeof groupName=="string")return groupName;if(groupName===void 0)return!1;throw Error("non exhaustive match")}}),patternIdxToLongerAltIdxArr=onlyRelevantTypes.map(clazz=>{const longerAltType=clazz.LONGER_ALT;if(longerAltType)return Array.isArray(longerAltType)?longerAltType.map(type=>onlyRelevantTypes.indexOf(type)):[onlyRelevantTypes.indexOf(longerAltType)]}),patternIdxToPushMode=onlyRelevantTypes.map(clazz=>clazz.PUSH_MODE),patternIdxToPopMode=onlyRelevantTypes.map(clazz=>Object.hasOwn(clazz,"POP_MODE"))});let patternIdxToCanLineTerminator;tracer("Line Terminator Handling",()=>{const lineTerminatorCharCodes=getCharCodes(options.lineTerminatorCharacters);patternIdxToCanLineTerminator=onlyRelevantTypes.map(tokType=>!1),options.positionTracking!=="onlyOffset"&&(patternIdxToCanLineTerminator=onlyRelevantTypes.map(tokType=>Object.hasOwn(tokType,"LINE_BREAKS")?!!tokType.LINE_BREAKS:checkLineBreaksIssues(tokType,lineTerminatorCharCodes)===!1&&canMatchCharCode(lineTerminatorCharCodes,tokType.PATTERN)))});let patternIdxToIsCustom,patternIdxToShort,emptyGroups,patternIdxToConfig;tracer("Misc Mapping #2",()=>{patternIdxToIsCustom=onlyRelevantTypes.map(isCustomPattern),patternIdxToShort=allTransformedPatterns.map(isShortPattern),emptyGroups=onlyRelevantTypes.reduce((acc,clazz)=>{const groupName=clazz.GROUP;return typeof groupName=="string"&&groupName!==Lexer.SKIPPED&&(acc[groupName]=[]),acc},{}),patternIdxToConfig=allTransformedPatterns.map((x,idx)=>({pattern:allTransformedPatterns[idx],longerAlt:patternIdxToLongerAltIdxArr[idx],canLineTerminator:patternIdxToCanLineTerminator[idx],isCustom:patternIdxToIsCustom[idx],short:patternIdxToShort[idx],group:patternIdxToGroup[idx],push:patternIdxToPushMode[idx],pop:patternIdxToPopMode[idx],tokenTypeIdx:patternIdxToType[idx],tokenType:onlyRelevantTypes[idx]}))});let canBeOptimized=!0,charCodeToPatternIdxToConfig=[];return options.safeMode||tracer("First Char Optimization",()=>{charCodeToPatternIdxToConfig=onlyRelevantTypes.reduce((result,currTokType,idx)=>{if(typeof currTokType.PATTERN=="string"){const charCode=currTokType.PATTERN.charCodeAt(0),optimizedIdx=charCodeToOptimizedIndex(charCode);addToMapOfArrays(result,optimizedIdx,patternIdxToConfig[idx])}else if(Array.isArray(currTokType.START_CHARS_HINT)){let lastOptimizedIdx;currTokType.START_CHARS_HINT.forEach(charOrInt=>{const charCode=typeof charOrInt=="string"?charOrInt.charCodeAt(0):charOrInt,currOptimizedIdx=charCodeToOptimizedIndex(charCode);lastOptimizedIdx!==currOptimizedIdx&&(lastOptimizedIdx=currOptimizedIdx,addToMapOfArrays(result,currOptimizedIdx,patternIdxToConfig[idx]))})}else if(currTokType.PATTERN instanceof RegExp)if(currTokType.PATTERN.unicode)canBeOptimized=!1,options.ensureOptimizations&&PRINT_ERROR(`${failedOptimizationPrefixMsg} Unable to analyze < ${currTokType.PATTERN.toString()} > pattern.
23
+ The regexp unicode flag is not currently supported by the regexp-to-ast library.
24
+ This will disable the lexer's first char optimizations.
25
+ For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{const optimizedCodes=getOptimizedStartCodesIndices(currTokType.PATTERN,options.ensureOptimizations);optimizedCodes.length===0&&(canBeOptimized=!1),optimizedCodes.forEach(code=>{addToMapOfArrays(result,code,patternIdxToConfig[idx])})}else options.ensureOptimizations&&PRINT_ERROR(`${failedOptimizationPrefixMsg} TokenType: <${currTokType.name}> is using a custom token pattern without providing <start_chars_hint> parameter.
26
+ This will disable the lexer's first char optimizations.
27
+ For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),canBeOptimized=!1;return result},[])}),{emptyGroups,patternIdxToConfig,charCodeToPatternIdxToConfig,hasCustom,canBeOptimized}}function validatePatterns(tokenTypes,validModesNames){let errors=[];const missingResult=findMissingPatterns(tokenTypes);errors=errors.concat(missingResult.errors);const invalidResult=findInvalidPatterns(missingResult.valid),validTokenTypes=invalidResult.valid;return errors=errors.concat(invalidResult.errors),errors=errors.concat(validateRegExpPattern(validTokenTypes)),errors=errors.concat(findInvalidGroupType(validTokenTypes)),errors=errors.concat(findModesThatDoNotExist(validTokenTypes,validModesNames)),errors=errors.concat(findUnreachablePatterns(validTokenTypes)),errors}function validateRegExpPattern(tokenTypes){let errors=[];const withRegExpPatterns=tokenTypes.filter(currTokType=>currTokType[PATTERN]instanceof RegExp);return errors=errors.concat(findEndOfInputAnchor(withRegExpPatterns)),errors=errors.concat(findStartOfInputAnchor(withRegExpPatterns)),errors=errors.concat(findUnsupportedFlags(withRegExpPatterns)),errors=errors.concat(findDuplicatePatterns(withRegExpPatterns)),errors=errors.concat(findEmptyMatchRegExps(withRegExpPatterns)),errors}function findMissingPatterns(tokenTypes){const tokenTypesWithMissingPattern=tokenTypes.filter(currType=>!Object.hasOwn(currType,PATTERN)),errors=tokenTypesWithMissingPattern.map(currType=>({message:"Token Type: ->"+currType.name+"<- missing static 'PATTERN' property",type:LexerDefinitionErrorType.MISSING_PATTERN,tokenTypes:[currType]})),valid=tokenTypes.filter(x=>!tokenTypesWithMissingPattern.includes(x));return{errors,valid}}function findInvalidPatterns(tokenTypes){const tokenTypesWithInvalidPattern=tokenTypes.filter(currType=>{const pattern=currType[PATTERN];return!(pattern instanceof RegExp)&&typeof pattern!="function"&&!Object.hasOwn(pattern,"exec")&&typeof pattern!="string"}),errors=tokenTypesWithInvalidPattern.map(currType=>({message:"Token Type: ->"+currType.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:LexerDefinitionErrorType.INVALID_PATTERN,tokenTypes:[currType]})),valid=tokenTypes.filter(x=>!tokenTypesWithInvalidPattern.includes(x));return{errors,valid}}const end_of_input=/[^\\][$]/;function findEndOfInputAnchor(tokenTypes){class EndAnchorFinder extends BaseRegExpVisitor{constructor(){super(...arguments),this.found=!1}visitEndAnchor(node){this.found=!0}}return tokenTypes.filter(currType=>{const pattern=currType.PATTERN;try{const regexpAst=getRegExpAst(pattern),endAnchorVisitor=new EndAnchorFinder;return endAnchorVisitor.visit(regexpAst),endAnchorVisitor.found}catch{return end_of_input.test(pattern.source)}}).map(currType=>({message:`Unexpected RegExp Anchor Error:
28
+ Token Type: ->`+currType.name+`<- static 'PATTERN' cannot contain end of input anchor '$'
29
+ See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:LexerDefinitionErrorType.EOI_ANCHOR_FOUND,tokenTypes:[currType]}))}function findEmptyMatchRegExps(tokenTypes){return tokenTypes.filter(currType=>currType.PATTERN.test("")).map(currType=>({message:"Token Type: ->"+currType.name+"<- static 'PATTERN' must not match an empty string",type:LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,tokenTypes:[currType]}))}const start_of_input=/[^\\[][\^]|^\^/;function findStartOfInputAnchor(tokenTypes){class StartAnchorFinder extends BaseRegExpVisitor{constructor(){super(...arguments),this.found=!1}visitStartAnchor(node){this.found=!0}}return tokenTypes.filter(currType=>{const pattern=currType.PATTERN;try{const regexpAst=getRegExpAst(pattern),startAnchorVisitor=new StartAnchorFinder;return startAnchorVisitor.visit(regexpAst),startAnchorVisitor.found}catch{return start_of_input.test(pattern.source)}}).map(currType=>({message:`Unexpected RegExp Anchor Error:
30
+ Token Type: ->`+currType.name+`<- static 'PATTERN' cannot contain start of input anchor '^'
31
+ See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:LexerDefinitionErrorType.SOI_ANCHOR_FOUND,tokenTypes:[currType]}))}function findUnsupportedFlags(tokenTypes){return tokenTypes.filter(currType=>{const pattern=currType[PATTERN];return pattern instanceof RegExp&&(pattern.multiline||pattern.global)}).map(currType=>({message:"Token Type: ->"+currType.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[currType]}))}function findDuplicatePatterns(tokenTypes){const found=[];let identicalPatterns=tokenTypes.map(outerType=>tokenTypes.reduce((result,innerType)=>(outerType.PATTERN.source===innerType.PATTERN.source&&!found.includes(innerType)&&innerType.PATTERN!==Lexer.NA&&(found.push(innerType),result.push(innerType)),result),[]));return identicalPatterns=identicalPatterns.filter(Boolean),identicalPatterns.filter(currIdenticalSet=>currIdenticalSet.length>1).map(setOfIdentical=>{const tokenTypeNames=setOfIdentical.map(currType=>currType.name);return{message:`The same RegExp pattern ->${setOfIdentical[0].PATTERN}<-has been used in all of the following Token Types: ${tokenTypeNames.join(", ")} <-`,type:LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,tokenTypes:setOfIdentical}})}function findInvalidGroupType(tokenTypes){return tokenTypes.filter(clazz=>{if(!Object.hasOwn(clazz,"GROUP"))return!1;const group=clazz.GROUP;return group!==Lexer.SKIPPED&&group!==Lexer.NA&&typeof group!="string"}).map(currType=>({message:"Token Type: ->"+currType.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,tokenTypes:[currType]}))}function findModesThatDoNotExist(tokenTypes,validModes){return tokenTypes.filter(clazz=>clazz.PUSH_MODE!==void 0&&!validModes.includes(clazz.PUSH_MODE)).map(tokType=>({message:`Token Type: ->${tokType.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${tokType.PUSH_MODE}<-which does not exist`,type:LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[tokType]}))}function findUnreachablePatterns(tokenTypes){const errors=[],canBeTested=tokenTypes.reduce((result,tokType,idx)=>{const pattern=tokType.PATTERN;return pattern===Lexer.NA||(typeof pattern=="string"?result.push({str:pattern,idx,tokenType:tokType}):pattern instanceof RegExp&&noMetaChar(pattern)&&result.push({str:pattern.source,idx,tokenType:tokType})),result},[]);return tokenTypes.forEach((aTokType,aIdx)=>{canBeTested.forEach(({str:bStr,idx:bIdx,tokenType:bTokType})=>{if(aIdx<bIdx&&tryToMatchStrToPattern(bStr,aTokType.PATTERN)){const msg=`Token: ->${bTokType.name}<- can never be matched.
32
+ Because it appears AFTER the Token Type ->${aTokType.name}<-in the lexer's definition.
33
+ See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;errors.push({message:msg,type:LexerDefinitionErrorType.UNREACHABLE_PATTERN,tokenTypes:[aTokType,bTokType]})}})}),errors}function tryToMatchStrToPattern(str,pattern){if(pattern instanceof RegExp){if(usesLookAheadOrBehind(pattern))return!1;const regExpArray=pattern.exec(str);return regExpArray!==null&&regExpArray.index===0}else{if(typeof pattern=="function")return pattern(str,0,[],{});if(Object.hasOwn(pattern,"exec"))return pattern.exec(str,0,[],{});if(typeof pattern=="string")return pattern===str;throw Error("non exhaustive match")}}function noMetaChar(regExp){return[".","\\","[","]","|","^","$","(",")","?","*","+","{"].find(char=>regExp.source.indexOf(char)!==-1)===void 0}function usesLookAheadOrBehind(regExp){return/(\(\?=)|(\(\?!)|(\(\?<=)|(\(\?<!)/.test(regExp.source)}function addStickyFlag(pattern){const flags=pattern.ignoreCase?"iy":"y";return new RegExp(`${pattern.source}`,flags)}function performRuntimeChecks(lexerDefinition,trackLines,lineTerminatorCharacters){const errors=[];return Object.hasOwn(lexerDefinition,DEFAULT_MODE)||errors.push({message:"A MultiMode Lexer cannot be initialized without a <"+DEFAULT_MODE+`> property in its definition
34
+ `,type:LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),Object.hasOwn(lexerDefinition,MODES)||errors.push({message:"A MultiMode Lexer cannot be initialized without a <"+MODES+`> property in its definition
35
+ `,type:LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),Object.hasOwn(lexerDefinition,MODES)&&Object.hasOwn(lexerDefinition,DEFAULT_MODE)&&!Object.hasOwn(lexerDefinition.modes,lexerDefinition.defaultMode)&&errors.push({message:`A MultiMode Lexer cannot be initialized with a ${DEFAULT_MODE}: <${lexerDefinition.defaultMode}>which does not exist
36
+ `,type:LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),Object.hasOwn(lexerDefinition,MODES)&&Object.keys(lexerDefinition.modes).forEach(currModeName=>{const currModeValue=lexerDefinition.modes[currModeName];currModeValue.forEach((currTokType,currIdx)=>{currTokType===void 0?errors.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${currModeName}> at index: <${currIdx}>
37
+ `,type:LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED}):Object.hasOwn(currTokType,"LONGER_ALT")&&(Array.isArray(currTokType.LONGER_ALT)?currTokType.LONGER_ALT:[currTokType.LONGER_ALT]).forEach(currLongerAlt=>{currLongerAlt!==void 0&&!currModeValue.includes(currLongerAlt)&&errors.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${currLongerAlt.name}> on token <${currTokType.name}> outside of mode <${currModeName}>
38
+ `,type:LexerDefinitionErrorType.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})})}),errors}function performWarningRuntimeChecks(lexerDefinition,trackLines,lineTerminatorCharacters){const warnings=[];let hasAnyLineBreak=!1;const concreteTokenTypes=Object.values(lexerDefinition.modes||{}).flat().filter(Boolean).filter(currType=>currType[PATTERN]!==Lexer.NA),terminatorCharCodes=getCharCodes(lineTerminatorCharacters);return trackLines&&concreteTokenTypes.forEach(tokType=>{const currIssue=checkLineBreaksIssues(tokType,terminatorCharCodes);if(currIssue!==!1){const warningDescriptor={message:buildLineBreakIssueMessage(tokType,currIssue),type:currIssue.issue,tokenType:tokType};warnings.push(warningDescriptor)}else Object.hasOwn(tokType,"LINE_BREAKS")?tokType.LINE_BREAKS===!0&&(hasAnyLineBreak=!0):canMatchCharCode(terminatorCharCodes,tokType.PATTERN)&&(hasAnyLineBreak=!0)}),trackLines&&!hasAnyLineBreak&&warnings.push({message:`Warning: No LINE_BREAKS Found.
39
+ This Lexer has been defined to track line and column information,
40
+ But none of the Token Types can be identified as matching a line terminator.
41
+ See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS
42
+ for details.`,type:LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS}),warnings}function cloneEmptyGroups(emptyGroups){const clonedResult={};return Object.keys(emptyGroups).forEach(currKey=>{const currGroupValue=emptyGroups[currKey];if(Array.isArray(currGroupValue))clonedResult[currKey]=[];else throw Error("non exhaustive match")}),clonedResult}function isCustomPattern(tokenType){const pattern=tokenType.PATTERN;if(pattern instanceof RegExp)return!1;if(typeof pattern=="function")return!0;if(Object.hasOwn(pattern,"exec"))return!0;if(typeof pattern=="string")return!1;throw Error("non exhaustive match")}function isShortPattern(pattern){return typeof pattern=="string"&&pattern.length===1?pattern.charCodeAt(0):!1}const LineTerminatorOptimizedTester={test:function(text){const len=text.length;for(let i=this.lastIndex;i<len;i++){const c=text.charCodeAt(i);if(c===10)return this.lastIndex=i+1,!0;if(c===13)return text.charCodeAt(i+1)===10?this.lastIndex=i+2:this.lastIndex=i+1,!0}return!1},lastIndex:0};function checkLineBreaksIssues(tokType,lineTerminatorCharCodes){if(Object.hasOwn(tokType,"LINE_BREAKS"))return!1;if(tokType.PATTERN instanceof RegExp){try{canMatchCharCode(lineTerminatorCharCodes,tokType.PATTERN)}catch(e){return{issue:LexerDefinitionErrorType.IDENTIFY_TERMINATOR,errMsg:e.message}}return!1}else{if(typeof tokType.PATTERN=="string")return!1;if(isCustomPattern(tokType))return{issue:LexerDefinitionErrorType.CUSTOM_LINE_BREAK};throw Error("non exhaustive match")}}function buildLineBreakIssueMessage(tokType,details){if(details.issue===LexerDefinitionErrorType.IDENTIFY_TERMINATOR)return`Warning: unable to identify line terminator usage in pattern.
43
+ The problem is in the <${tokType.name}> Token Type
44
+ Root cause: ${details.errMsg}.
45
+ For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(details.issue===LexerDefinitionErrorType.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the <line_breaks> option.
46
+ The problem is in the <${tokType.name}> Token Type
47
+ For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function getCharCodes(charsOrCodes){return charsOrCodes.map(numOrString=>typeof numOrString=="string"?numOrString.charCodeAt(0):numOrString)}function addToMapOfArrays(map2,key,value){map2[key]===void 0?map2[key]=[value]:map2[key].push(value)}const minOptimizationVal=256;let charCodeToOptimizedIdxMap=[];function charCodeToOptimizedIndex(charCode){return charCode<minOptimizationVal?charCode:charCodeToOptimizedIdxMap[charCode]}function initCharCodeToOptimizedIndexMap(){if(charCodeToOptimizedIdxMap.length===0){charCodeToOptimizedIdxMap=new Array(65536);for(let i=0;i<65536;i++)charCodeToOptimizedIdxMap[i]=i>255?255+~~(i/255):i}}function tokenStructuredMatcher(tokInstance,tokConstructor){const instanceType=tokInstance.tokenTypeIdx;return instanceType===tokConstructor.tokenTypeIdx?!0:tokConstructor.isParent===!0&&tokConstructor.categoryMatchesMap[instanceType]===!0}function tokenStructuredMatcherNoCategories(token,tokType){return token.tokenTypeIdx===tokType.tokenTypeIdx}let tokenShortNameIdx=1;const tokenIdxToClass={};function augmentTokenTypes(tokenTypes){const tokenTypesAndParents=expandCategories(tokenTypes);assignTokenDefaultProps(tokenTypesAndParents),assignCategoriesMapProp(tokenTypesAndParents),assignCategoriesTokensProp(tokenTypesAndParents),tokenTypesAndParents.forEach(tokType=>{tokType.isParent=tokType.categoryMatches.length>0})}function expandCategories(tokenTypes){let result=[...tokenTypes],categories=tokenTypes,searching=!0;for(;searching;){categories=categories.map(currTokType=>currTokType.CATEGORIES).flat().filter(Boolean);const newCategories=categories.filter(x=>!result.includes(x));result=result.concat(newCategories),newCategories.length===0?searching=!1:categories=newCategories}return result}function assignTokenDefaultProps(tokenTypes){tokenTypes.forEach(currTokType=>{hasShortKeyProperty(currTokType)||(tokenIdxToClass[tokenShortNameIdx]=currTokType,currTokType.tokenTypeIdx=tokenShortNameIdx++),hasCategoriesProperty(currTokType)&&!Array.isArray(currTokType.CATEGORIES)&&(currTokType.CATEGORIES=[currTokType.CATEGORIES]),hasCategoriesProperty(currTokType)||(currTokType.CATEGORIES=[]),hasExtendingTokensTypesProperty(currTokType)||(currTokType.categoryMatches=[]),hasExtendingTokensTypesMapProperty(currTokType)||(currTokType.categoryMatchesMap={})})}function assignCategoriesTokensProp(tokenTypes){tokenTypes.forEach(currTokType=>{currTokType.categoryMatches=[],Object.keys(currTokType.categoryMatchesMap).forEach(key=>{currTokType.categoryMatches.push(tokenIdxToClass[key].tokenTypeIdx)})})}function assignCategoriesMapProp(tokenTypes){tokenTypes.forEach(currTokType=>{singleAssignCategoriesToksMap([],currTokType)})}function singleAssignCategoriesToksMap(path,nextNode){path.forEach(pathNode=>{nextNode.categoryMatchesMap[pathNode.tokenTypeIdx]=!0}),nextNode.CATEGORIES.forEach(nextCategory=>{const newPath=path.concat(nextNode);newPath.includes(nextCategory)||singleAssignCategoriesToksMap(newPath,nextCategory)})}function hasShortKeyProperty(tokType){return Object.hasOwn(tokType??{},"tokenTypeIdx")}function hasCategoriesProperty(tokType){return Object.hasOwn(tokType??{},"CATEGORIES")}function hasExtendingTokensTypesProperty(tokType){return Object.hasOwn(tokType??{},"categoryMatches")}function hasExtendingTokensTypesMapProperty(tokType){return Object.hasOwn(tokType??{},"categoryMatchesMap")}function isTokenType(tokType){return Object.hasOwn(tokType??{},"tokenTypeIdx")}const defaultLexerErrorProvider={buildUnableToPopLexerModeMessage(token){return`Unable to pop Lexer Mode after encountering Token ->${token.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(fullText,startOffset,length,line,column,mode){return`unexpected character: ->${fullText.charAt(startOffset)}<- at offset: ${startOffset}, skipped ${length} characters.`}};var LexerDefinitionErrorType;(function(LexerDefinitionErrorType2){LexerDefinitionErrorType2[LexerDefinitionErrorType2.MISSING_PATTERN=0]="MISSING_PATTERN",LexerDefinitionErrorType2[LexerDefinitionErrorType2.INVALID_PATTERN=1]="INVALID_PATTERN",LexerDefinitionErrorType2[LexerDefinitionErrorType2.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",LexerDefinitionErrorType2[LexerDefinitionErrorType2.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",LexerDefinitionErrorType2[LexerDefinitionErrorType2.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",LexerDefinitionErrorType2[LexerDefinitionErrorType2.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",LexerDefinitionErrorType2[LexerDefinitionErrorType2.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",LexerDefinitionErrorType2[LexerDefinitionErrorType2.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",LexerDefinitionErrorType2[LexerDefinitionErrorType2.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",LexerDefinitionErrorType2[LexerDefinitionErrorType2.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",LexerDefinitionErrorType2[LexerDefinitionErrorType2.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",LexerDefinitionErrorType2[LexerDefinitionErrorType2.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",LexerDefinitionErrorType2[LexerDefinitionErrorType2.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",LexerDefinitionErrorType2[LexerDefinitionErrorType2.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",LexerDefinitionErrorType2[LexerDefinitionErrorType2.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",LexerDefinitionErrorType2[LexerDefinitionErrorType2.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",LexerDefinitionErrorType2[LexerDefinitionErrorType2.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",LexerDefinitionErrorType2[LexerDefinitionErrorType2.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(LexerDefinitionErrorType||(LexerDefinitionErrorType={}));const DEFAULT_LEXER_CONFIG={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[`
48
+ `,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:defaultLexerErrorProvider,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(DEFAULT_LEXER_CONFIG);class Lexer{constructor(lexerDefinition,config=DEFAULT_LEXER_CONFIG){if(this.lexerDefinition=lexerDefinition,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(phaseDesc,phaseImpl)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;const indent=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent<this.traceInitMaxIdent&&console.log(`${indent}--> <${phaseDesc}>`);const{time,value}=timer(phaseImpl),traceMethod=time>10?console.warn:console.log;return this.traceInitIndent<this.traceInitMaxIdent&&traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`),this.traceInitIndent--,value}else return phaseImpl()},typeof config=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object.
49
+ a boolean 2nd argument is no longer supported`);this.config=Object.assign({},DEFAULT_LEXER_CONFIG,config);const traceInitVal=this.config.traceInitPerf;traceInitVal===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof traceInitVal=="number"&&(this.traceInitMaxIdent=traceInitVal,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let actualDefinition,hasOnlySingleMode=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===DEFAULT_LEXER_CONFIG.lineTerminatorsPattern)this.config.lineTerminatorsPattern=LineTerminatorOptimizedTester;else if(this.config.lineTerminatorCharacters===DEFAULT_LEXER_CONFIG.lineTerminatorCharacters)throw Error(`Error: Missing <lineTerminatorCharacters> property on the Lexer config.
50
+ For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(config.safeMode&&config.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),Array.isArray(lexerDefinition)?actualDefinition={modes:{defaultMode:[...lexerDefinition]},defaultMode:DEFAULT_MODE}:(hasOnlySingleMode=!1,actualDefinition=Object.assign({},lexerDefinition))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(performRuntimeChecks(actualDefinition,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(performWarningRuntimeChecks(actualDefinition,this.trackStartLines,this.config.lineTerminatorCharacters))})),actualDefinition.modes=actualDefinition.modes?actualDefinition.modes:{},Object.entries(actualDefinition.modes).forEach(([currModeName,currModeValue])=>{actualDefinition.modes[currModeName]=currModeValue.filter(currTokType=>currTokType!==void 0)});const allModeNames=Object.keys(actualDefinition.modes);if(Object.entries(actualDefinition.modes).forEach(([currModName,currModDef])=>{this.TRACE_INIT(`Mode: <${currModName}> processing`,()=>{if(this.modes.push(currModName),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(validatePatterns(currModDef,allModeNames))}),this.lexerDefinitionErrors.length===0){augmentTokenTypes(currModDef);let currAnalyzeResult;this.TRACE_INIT("analyzeTokenTypes",()=>{currAnalyzeResult=analyzeTokenTypes(currModDef,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:config.positionTracking,ensureOptimizations:config.ensureOptimizations,safeMode:config.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[currModName]=currAnalyzeResult.patternIdxToConfig,this.charCodeToPatternIdxToConfig[currModName]=currAnalyzeResult.charCodeToPatternIdxToConfig,this.emptyGroups=Object.assign({},this.emptyGroups,currAnalyzeResult.emptyGroups),this.hasCustom=currAnalyzeResult.hasCustom||this.hasCustom,this.canModeBeOptimized[currModName]=currAnalyzeResult.canBeOptimized}})}),this.defaultMode=actualDefinition.defaultMode,this.lexerDefinitionErrors.length>0&&!this.config.deferDefinitionErrorsHandling){const allErrMessagesString=this.lexerDefinitionErrors.map(error=>error.message).join(`-----------------------
51
+ `);throw new Error(`Errors detected in definition of Lexer:
52
+ `+allErrMessagesString)}this.lexerDefinitionWarning.forEach(warningDescriptor=>{PRINT_WARNING(warningDescriptor.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(hasOnlySingleMode&&(this.handleModes=()=>{}),this.trackStartLines===!1&&(this.computeNewColumn=x=>x),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=()=>{}),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid <positionTracking> config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{const unOptimizedModes=Object.entries(this.canModeBeOptimized).reduce((cannotBeOptimized,[modeName,canBeOptimized])=>(canBeOptimized===!1&&cannotBeOptimized.push(modeName),cannotBeOptimized),[]);if(config.ensureOptimizations&&unOptimizedModes.length>0)throw Error(`Lexer Modes: < ${unOptimizedModes.join(", ")} > cannot be optimized.
53
+ Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.
54
+ Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{clearRegExpParserCache()}),this.TRACE_INIT("toFastProperties",()=>{toFastProperties(this)})})}tokenize(text,initialMode=this.defaultMode){if(this.lexerDefinitionErrors.length>0){const allErrMessagesString=this.lexerDefinitionErrors.map(error=>error.message).join(`-----------------------
55
+ `);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer:
56
+ `+allErrMessagesString)}return this.tokenizeInternal(text,initialMode)}tokenizeInternal(text,initialMode){let i,j,k,matchAltImage,longerAlt,matchedImage,payload,altPayload,imageLength,group,tokType,newToken,errLength,msg,match;const orgText=text,orgLength=orgText.length;let offset=0,matchedTokensIndex=0;const guessedNumberOfTokens=this.hasCustom?0:Math.floor(text.length/10),matchedTokens=new Array(guessedNumberOfTokens),errors=[];let line=this.trackStartLines?1:void 0,column=this.trackStartLines?1:void 0;const groups=cloneEmptyGroups(this.emptyGroups),trackLines=this.trackStartLines,lineTerminatorPattern=this.config.lineTerminatorsPattern;let currModePatternsLength=0,patternIdxToConfig=[],currCharCodeToPatternIdxToConfig=[];const modeStack=[],emptyArray=[];Object.freeze(emptyArray);let isOptimizedMode=!1;const pop_mode=popToken=>{if(modeStack.length===1&&popToken.tokenType.PUSH_MODE===void 0){const msg2=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(popToken);errors.push({offset:popToken.startOffset,line:popToken.startLine,column:popToken.startColumn,length:popToken.image.length,message:msg2})}else{modeStack.pop();const newMode=modeStack.at(-1);patternIdxToConfig=this.patternIdxToConfig[newMode],currCharCodeToPatternIdxToConfig=this.charCodeToPatternIdxToConfig[newMode],currModePatternsLength=patternIdxToConfig.length;const modeCanBeOptimized=this.canModeBeOptimized[newMode]&&this.config.safeMode===!1;currCharCodeToPatternIdxToConfig&&modeCanBeOptimized?isOptimizedMode=!0:isOptimizedMode=!1}};function push_mode(newMode){modeStack.push(newMode),currCharCodeToPatternIdxToConfig=this.charCodeToPatternIdxToConfig[newMode],patternIdxToConfig=this.patternIdxToConfig[newMode],currModePatternsLength=patternIdxToConfig.length,currModePatternsLength=patternIdxToConfig.length;const modeCanBeOptimized=this.canModeBeOptimized[newMode]&&this.config.safeMode===!1;currCharCodeToPatternIdxToConfig&&modeCanBeOptimized?isOptimizedMode=!0:isOptimizedMode=!1}push_mode.call(this,initialMode);let currConfig;const recoveryEnabled=this.config.recoveryEnabled;for(;offset<orgLength;){matchedImage=null,imageLength=-1;const nextCharCode=orgText.charCodeAt(offset);let chosenPatternIdxToConfig;if(isOptimizedMode){const optimizedCharIdx=charCodeToOptimizedIndex(nextCharCode),possiblePatterns=currCharCodeToPatternIdxToConfig[optimizedCharIdx];chosenPatternIdxToConfig=possiblePatterns!==void 0?possiblePatterns:emptyArray}else chosenPatternIdxToConfig=patternIdxToConfig;const chosenPatternsLength=chosenPatternIdxToConfig.length;for(i=0;i<chosenPatternsLength;i++){currConfig=chosenPatternIdxToConfig[i];const currPattern=currConfig.pattern;payload=null;const singleCharCode=currConfig.short;if(singleCharCode!==!1?nextCharCode===singleCharCode&&(imageLength=1,matchedImage=currPattern):currConfig.isCustom===!0?(match=currPattern.exec(orgText,offset,matchedTokens,groups),match!==null?(matchedImage=match[0],imageLength=matchedImage.length,match.payload!==void 0&&(payload=match.payload)):matchedImage=null):(currPattern.lastIndex=offset,imageLength=this.matchLength(currPattern,text,offset)),imageLength!==-1){if(longerAlt=currConfig.longerAlt,longerAlt!==void 0){matchedImage=text.substring(offset,offset+imageLength);const longerAltLength=longerAlt.length;for(k=0;k<longerAltLength;k++){const longerAltConfig=patternIdxToConfig[longerAlt[k]],longerAltPattern=longerAltConfig.pattern;if(altPayload=null,longerAltConfig.isCustom===!0?(match=longerAltPattern.exec(orgText,offset,matchedTokens,groups),match!==null?(matchAltImage=match[0],match.payload!==void 0&&(altPayload=match.payload)):matchAltImage=null):(longerAltPattern.lastIndex=offset,matchAltImage=this.match(longerAltPattern,text,offset)),matchAltImage&&matchAltImage.length>matchedImage.length){matchedImage=matchAltImage,imageLength=matchAltImage.length,payload=altPayload,currConfig=longerAltConfig;break}}}break}}if(imageLength!==-1){if(group=currConfig.group,group!==void 0&&(matchedImage=matchedImage!==null?matchedImage:text.substring(offset,offset+imageLength),tokType=currConfig.tokenTypeIdx,newToken=this.createTokenInstance(matchedImage,offset,tokType,currConfig.tokenType,line,column,imageLength),this.handlePayload(newToken,payload),group===!1?matchedTokensIndex=this.addToken(matchedTokens,matchedTokensIndex,newToken):groups[group].push(newToken)),trackLines===!0&&currConfig.canLineTerminator===!0){let numOfLTsInMatch=0,foundTerminator,lastLTEndOffset;lineTerminatorPattern.lastIndex=0;do matchedImage=matchedImage!==null?matchedImage:text.substring(offset,offset+imageLength),foundTerminator=lineTerminatorPattern.test(matchedImage),foundTerminator===!0&&(lastLTEndOffset=lineTerminatorPattern.lastIndex-1,numOfLTsInMatch++);while(foundTerminator===!0);numOfLTsInMatch!==0?(line=line+numOfLTsInMatch,column=imageLength-lastLTEndOffset,this.updateTokenEndLineColumnLocation(newToken,group,lastLTEndOffset,numOfLTsInMatch,line,column,imageLength)):column=this.computeNewColumn(column,imageLength)}else column=this.computeNewColumn(column,imageLength);offset=offset+imageLength,this.handleModes(currConfig,pop_mode,push_mode,newToken)}else{const errorStartOffset=offset,errorLine=line,errorColumn=column;let foundResyncPoint=recoveryEnabled===!1;for(;foundResyncPoint===!1&&offset<orgLength;)for(offset++,j=0;j<currModePatternsLength;j++){const currConfig2=patternIdxToConfig[j],currPattern=currConfig2.pattern,singleCharCode=currConfig2.short;if(singleCharCode!==!1?orgText.charCodeAt(offset)===singleCharCode&&(foundResyncPoint=!0):currConfig2.isCustom===!0?foundResyncPoint=currPattern.exec(orgText,offset,matchedTokens,groups)!==null:(currPattern.lastIndex=offset,foundResyncPoint=currPattern.exec(text)!==null),foundResyncPoint===!0)break}if(errLength=offset-errorStartOffset,column=this.computeNewColumn(column,errLength),msg=this.config.errorMessageProvider.buildUnexpectedCharactersMessage(orgText,errorStartOffset,errLength,errorLine,errorColumn,modeStack.at(-1)),errors.push({offset:errorStartOffset,line:errorLine,column:errorColumn,length:errLength,message:msg}),recoveryEnabled===!1)break}}return this.hasCustom||(matchedTokens.length=matchedTokensIndex),{tokens:matchedTokens,groups,errors}}handleModes(config,pop_mode,push_mode,newToken){if(config.pop===!0){const pushMode=config.push;pop_mode(newToken),pushMode!==void 0&&push_mode.call(this,pushMode)}else config.push!==void 0&&push_mode.call(this,config.push)}updateTokenEndLineColumnLocation(newToken,group,lastLTIdx,numOfLTsInMatch,line,column,imageLength){let lastCharIsLT,fixForEndingInLT;group!==void 0&&(lastCharIsLT=lastLTIdx===imageLength-1,fixForEndingInLT=lastCharIsLT?-1:0,numOfLTsInMatch===1&&lastCharIsLT===!0||(newToken.endLine=line+fixForEndingInLT,newToken.endColumn=column-1+-fixForEndingInLT))}computeNewColumn(oldColumn,imageLength){return oldColumn+imageLength}createOffsetOnlyToken(image,startOffset,tokenTypeIdx,tokenType){return{image,startOffset,tokenTypeIdx,tokenType}}createStartOnlyToken(image,startOffset,tokenTypeIdx,tokenType,startLine,startColumn){return{image,startOffset,startLine,startColumn,tokenTypeIdx,tokenType}}createFullToken(image,startOffset,tokenTypeIdx,tokenType,startLine,startColumn,imageLength){return{image,startOffset,endOffset:startOffset+imageLength-1,startLine,endLine:startLine,startColumn,endColumn:startColumn+imageLength-1,tokenTypeIdx,tokenType}}addTokenUsingPush(tokenVector,index,tokenToAdd){return tokenVector.push(tokenToAdd),index}addTokenUsingMemberAccess(tokenVector,index,tokenToAdd){return tokenVector[index]=tokenToAdd,index++,index}handlePayloadNoCustom(token,payload){}handlePayloadWithCustom(token,payload){payload!==null&&(token.payload=payload)}match(pattern,text,offset){return pattern.test(text)===!0?text.substring(offset,pattern.lastIndex):null}matchLength(pattern,text,offset){return pattern.test(text)===!0?pattern.lastIndex-offset:-1}}Lexer.SKIPPED="This marks a skipped Token pattern, this means each token identified by it will be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.";Lexer.NA=/NOT_APPLICABLE/;function tokenLabel(tokType){return hasTokenLabel(tokType)?tokType.LABEL:tokType.name}function hasTokenLabel(obj){return typeof obj.LABEL=="string"&&obj.LABEL!==""}const PARENT="parent",CATEGORIES="categories",LABEL="label",GROUP="group",PUSH_MODE="push_mode",POP_MODE="pop_mode",LONGER_ALT="longer_alt",LINE_BREAKS="line_breaks",START_CHARS_HINT="start_chars_hint";function createToken(config){return createTokenInternal(config)}function createTokenInternal(config){const pattern=config.pattern,tokenType={};if(tokenType.name=config.name,pattern!==void 0&&(tokenType.PATTERN=pattern),Object.hasOwn(config,PARENT))throw`The parent property is no longer supported.
57
+ See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`;return Object.hasOwn(config,CATEGORIES)&&(tokenType.CATEGORIES=config[CATEGORIES]),augmentTokenTypes([tokenType]),Object.hasOwn(config,LABEL)&&(tokenType.LABEL=config[LABEL]),Object.hasOwn(config,GROUP)&&(tokenType.GROUP=config[GROUP]),Object.hasOwn(config,POP_MODE)&&(tokenType.POP_MODE=config[POP_MODE]),Object.hasOwn(config,PUSH_MODE)&&(tokenType.PUSH_MODE=config[PUSH_MODE]),Object.hasOwn(config,LONGER_ALT)&&(tokenType.LONGER_ALT=config[LONGER_ALT]),Object.hasOwn(config,LINE_BREAKS)&&(tokenType.LINE_BREAKS=config[LINE_BREAKS]),Object.hasOwn(config,START_CHARS_HINT)&&(tokenType.START_CHARS_HINT=config[START_CHARS_HINT]),tokenType}const EOF=createToken({name:"EOF",pattern:Lexer.NA});augmentTokenTypes([EOF]);function createTokenInstance(tokType,image,startOffset,endOffset,startLine,endLine,startColumn,endColumn){return{image,startOffset,endOffset,startLine,endLine,startColumn,endColumn,tokenTypeIdx:tokType.tokenTypeIdx,tokenType:tokType}}function tokenMatcher(token,tokType){return tokenStructuredMatcher(token,tokType)}const defaultParserErrorProvider={buildMismatchTokenMessage({expected,actual,previous,ruleName}){return`Expecting ${hasTokenLabel(expected)?`--> ${tokenLabel(expected)} <--`:`token of type --> ${expected.name} <--`} but found --> '${actual.image}' <--`},buildNotAllInputParsedMessage({firstRedundant,ruleName}){return"Redundant input, expecting EOF but found: "+firstRedundant.image},buildNoViableAltMessage({expectedPathsPerAlt,actual,previous,customUserDescription,ruleName}){const errPrefix="Expecting: ",errSuffix=`
58
+ but found: '`+actual[0].image+"'";if(customUserDescription)return errPrefix+customUserDescription+errSuffix;{const calculatedDescription=`one of these possible Token sequences:
59
+ ${expectedPathsPerAlt.reduce((result,currAltPaths)=>result.concat(currAltPaths),[]).map(currPath=>`[${currPath.map(currTokenType=>tokenLabel(currTokenType)).join(", ")}]`).map((itemMsg,idx)=>` ${idx+1}. ${itemMsg}`).join(`
60
+ `)}`;return errPrefix+calculatedDescription+errSuffix}},buildEarlyExitMessage({expectedIterationPaths,actual,customUserDescription,ruleName}){const errPrefix="Expecting: ",errSuffix=`
61
+ but found: '`+actual[0].image+"'";if(customUserDescription)return errPrefix+customUserDescription+errSuffix;{const calculatedDescription=`expecting at least one iteration which starts with one of these possible Token sequences::
62
+ <${expectedIterationPaths.map(currPath=>`[${currPath.map(currTokenType=>tokenLabel(currTokenType)).join(",")}]`).join(" ,")}>`;return errPrefix+calculatedDescription+errSuffix}}};Object.freeze(defaultParserErrorProvider);const defaultGrammarResolverErrorProvider={buildRuleNotFoundError(topLevelRule,undefinedRule){return"Invalid grammar, reference to a rule which is not defined: ->"+undefinedRule.nonTerminalName+`<-
63
+ inside top level rule: ->`+topLevelRule.name+"<-"}},defaultGrammarValidatorErrorProvider={buildDuplicateFoundError(topLevelRule,duplicateProds){function getExtraProductionArgument2(prod){return prod instanceof Terminal?prod.terminalType.name:prod instanceof NonTerminal?prod.nonTerminalName:""}const topLevelName=topLevelRule.name,duplicateProd=duplicateProds[0],index=duplicateProd.idx,dslName=getProductionDslName$1(duplicateProd),extraArgument=getExtraProductionArgument2(duplicateProd),hasExplicitIndex=index>0;let msg=`->${dslName}${hasExplicitIndex?index:""}<- ${extraArgument?`with argument: ->${extraArgument}<-`:""}
64
+ appears more than once (${duplicateProds.length} times) in the top level rule: ->${topLevelName}<-.
65
+ For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES
66
+ `;return msg=msg.replace(/[ \t]+/g," "),msg=msg.replace(/\s\s+/g,`
67
+ `),msg},buildNamespaceConflictError(rule){return`Namespace conflict found in grammar.
68
+ The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${rule.name}>.
69
+ To resolve this make sure each Terminal and Non-Terminal names are unique
70
+ This is easy to accomplish by using the convention that Terminal names start with an uppercase letter
71
+ and Non-Terminal names start with a lower case letter.`},buildAlternationPrefixAmbiguityError(options){const pathMsg=options.prefixPath.map(currTok=>tokenLabel(currTok)).join(", "),occurrence=options.alternation.idx===0?"":options.alternation.idx;return`Ambiguous alternatives: <${options.ambiguityIndices.join(" ,")}> due to common lookahead prefix
72
+ in <OR${occurrence}> inside <${options.topLevelRule.name}> Rule,
73
+ <${pathMsg}> may appears as a prefix path in all these alternatives.
74
+ See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX
75
+ For Further details.`},buildAlternationAmbiguityError(options){const occurrence=options.alternation.idx===0?"":options.alternation.idx,isEmptyPath=options.prefixPath.length===0;let currMessage=`Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(" ,")}> in <OR${occurrence}> inside <${options.topLevelRule.name}> Rule,
76
+ `;if(isEmptyPath)currMessage+=`These alternatives are all empty (match no tokens), making them indistinguishable.
77
+ Only the last alternative may be empty.
78
+ `;else{const pathMsg=options.prefixPath.map(currtok=>tokenLabel(currtok)).join(", ");currMessage+=`<${pathMsg}> may appears as a prefix path in all these alternatives.
79
+ `}return currMessage+=`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES
80
+ For Further details.`,currMessage},buildEmptyRepetitionError(options){let dslName=getProductionDslName$1(options.repetition);return options.repetition.idx!==0&&(dslName+=options.repetition.idx),`The repetition <${dslName}> within Rule <${options.topLevelRule.name}> can never consume any tokens.
81
+ This could lead to an infinite loop.`},buildTokenNameError(options){return"deprecated"},buildEmptyAlternationError(options){return`Ambiguous empty alternative: <${options.emptyChoiceIdx+1}> in <OR${options.alternation.idx}> inside <${options.topLevelRule.name}> Rule.
82
+ Only the last alternative may be an empty alternative.`},buildTooManyAlternativesError(options){return`An Alternation cannot have more than 256 alternatives:
83
+ <OR${options.alternation.idx}> inside <${options.topLevelRule.name}> Rule.
84
+ has ${options.alternation.definition.length+1} alternatives.`},buildLeftRecursionError(options){const ruleName=options.topLevelRule.name,pathNames=options.leftRecursionPath.map(currRule=>currRule.name),leftRecursivePath=`${ruleName} --> ${pathNames.concat([ruleName]).join(" --> ")}`;return`Left Recursion found in grammar.
85
+ rule: <${ruleName}> can be invoked from itself (directly or indirectly)
86
+ without consuming any Tokens. The grammar path that causes this is:
87
+ ${leftRecursivePath}
88
+ To fix this refactor your grammar to remove the left recursion.
89
+ see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(options){return"deprecated"},buildDuplicateRuleNameError(options){let ruleName;return options.topLevelRule instanceof Rule?ruleName=options.topLevelRule.name:ruleName=options.topLevelRule,`Duplicate definition, rule: ->${ruleName}<- is already defined in the grammar: ->${options.grammarName}<-`}};function resolveGrammar$1(topLevels,errMsgProvider){const refResolver=new GastRefResolverVisitor(topLevels,errMsgProvider);return refResolver.resolveRefs(),refResolver.errors}class GastRefResolverVisitor extends GAstVisitor{constructor(nameToTopRule,errMsgProvider){super(),this.nameToTopRule=nameToTopRule,this.errMsgProvider=errMsgProvider,this.errors=[]}resolveRefs(){Object.values(this.nameToTopRule).forEach(prod=>{this.currTopLevel=prod,prod.accept(this)})}visitNonTerminal(node){const ref=this.nameToTopRule[node.nonTerminalName];if(ref)node.referencedRule=ref;else{const msg=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,node);this.errors.push({message:msg,type:ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:node.nonTerminalName})}}}class AbstractNextPossibleTokensWalker extends RestWalker{constructor(topProd,path){super(),this.topProd=topProd,this.path=path,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=[...this.path.ruleStack].reverse(),this.occurrenceStack=[...this.path.occurrenceStack].reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(prod,prevRest=[]){this.found||super.walk(prod,prevRest)}walkProdRef(refProd,currRest,prevRest){if(refProd.referencedRule.name===this.nextProductionName&&refProd.idx===this.nextProductionOccurrence){const fullRest=currRest.concat(prevRest);this.updateExpectedNext(),this.walk(refProd.referencedRule,fullRest)}}updateExpectedNext(){this.ruleStack.length===0?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}}class NextAfterTokenWalker extends AbstractNextPossibleTokensWalker{constructor(topProd,path){super(topProd,path),this.path=path,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(terminal,currRest,prevRest){if(this.isAtEndOfPath&&terminal.terminalType.name===this.nextTerminalName&&terminal.idx===this.nextTerminalOccurrence&&!this.found){const fullRest=currRest.concat(prevRest),restProd=new Alternative({definition:fullRest});this.possibleTokTypes=first(restProd),this.found=!0}}}class AbstractNextTerminalAfterProductionWalker extends RestWalker{constructor(topRule,occurrence){super(),this.topRule=topRule,this.occurrence=occurrence,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}}class NextTerminalAfterManyWalker extends AbstractNextTerminalAfterProductionWalker{walkMany(manyProd,currRest,prevRest){if(manyProd.idx===this.occurrence){const firstAfterMany=currRest.concat(prevRest)[0];this.result.isEndOfRule=firstAfterMany===void 0,firstAfterMany instanceof Terminal&&(this.result.token=firstAfterMany.terminalType,this.result.occurrence=firstAfterMany.idx)}else super.walkMany(manyProd,currRest,prevRest)}}class NextTerminalAfterManySepWalker extends AbstractNextTerminalAfterProductionWalker{walkManySep(manySepProd,currRest,prevRest){if(manySepProd.idx===this.occurrence){const firstAfterManySep=currRest.concat(prevRest)[0];this.result.isEndOfRule=firstAfterManySep===void 0,firstAfterManySep instanceof Terminal&&(this.result.token=firstAfterManySep.terminalType,this.result.occurrence=firstAfterManySep.idx)}else super.walkManySep(manySepProd,currRest,prevRest)}}class NextTerminalAfterAtLeastOneWalker extends AbstractNextTerminalAfterProductionWalker{walkAtLeastOne(atLeastOneProd,currRest,prevRest){if(atLeastOneProd.idx===this.occurrence){const firstAfterAtLeastOne=currRest.concat(prevRest)[0];this.result.isEndOfRule=firstAfterAtLeastOne===void 0,firstAfterAtLeastOne instanceof Terminal&&(this.result.token=firstAfterAtLeastOne.terminalType,this.result.occurrence=firstAfterAtLeastOne.idx)}else super.walkAtLeastOne(atLeastOneProd,currRest,prevRest)}}class NextTerminalAfterAtLeastOneSepWalker extends AbstractNextTerminalAfterProductionWalker{walkAtLeastOneSep(atleastOneSepProd,currRest,prevRest){if(atleastOneSepProd.idx===this.occurrence){const firstAfterfirstAfterAtLeastOneSep=currRest.concat(prevRest)[0];this.result.isEndOfRule=firstAfterfirstAfterAtLeastOneSep===void 0,firstAfterfirstAfterAtLeastOneSep instanceof Terminal&&(this.result.token=firstAfterfirstAfterAtLeastOneSep.terminalType,this.result.occurrence=firstAfterfirstAfterAtLeastOneSep.idx)}else super.walkAtLeastOneSep(atleastOneSepProd,currRest,prevRest)}}function possiblePathsFrom(targetDef,maxLength,currPath=[]){currPath=[...currPath];let result=[],i=0;function remainingPathWith(nextDef){return nextDef.concat(targetDef.slice(i+1))}function getAlternativesForProd(definition){const alternatives=possiblePathsFrom(remainingPathWith(definition),maxLength,currPath);return result.concat(alternatives)}for(;currPath.length<maxLength&&i<targetDef.length;){const prod=targetDef[i];if(prod instanceof Alternative)return getAlternativesForProd(prod.definition);if(prod instanceof NonTerminal)return getAlternativesForProd(prod.definition);if(prod instanceof Option$1)result=getAlternativesForProd(prod.definition);else if(prod instanceof RepetitionMandatory){const newDef=prod.definition.concat([new Repetition({definition:prod.definition})]);return getAlternativesForProd(newDef)}else if(prod instanceof RepetitionMandatoryWithSeparator){const newDef=[new Alternative({definition:prod.definition}),new Repetition({definition:[new Terminal({terminalType:prod.separator})].concat(prod.definition)})];return getAlternativesForProd(newDef)}else if(prod instanceof RepetitionWithSeparator){const newDef=prod.definition.concat([new Repetition({definition:[new Terminal({terminalType:prod.separator})].concat(prod.definition)})]);result=getAlternativesForProd(newDef)}else if(prod instanceof Repetition){const newDef=prod.definition.concat([new Repetition({definition:prod.definition})]);result=getAlternativesForProd(newDef)}else{if(prod instanceof Alternation)return prod.definition.forEach(currAlt=>{currAlt.definition.length!==0&&(result=getAlternativesForProd(currAlt.definition))}),result;if(prod instanceof Terminal)currPath.push(prod.terminalType);else throw Error("non exhaustive match")}i++}return result.push({partialPath:currPath,suffixDef:targetDef.slice(i)}),result}function nextPossibleTokensAfter(initialDef,tokenVector,tokMatcher,maxLookAhead){const EXIT_NON_TERMINAL="EXIT_NONE_TERMINAL",EXIT_NON_TERMINAL_ARR=[EXIT_NON_TERMINAL],EXIT_ALTERNATIVE="EXIT_ALTERNATIVE";let foundCompletePath=!1;const tokenVectorLength=tokenVector.length,minimalAlternativesIndex=tokenVectorLength-maxLookAhead-1,result=[],possiblePaths=[];for(possiblePaths.push({idx:-1,def:initialDef,ruleStack:[],occurrenceStack:[]});possiblePaths.length!==0;){const currPath=possiblePaths.pop();if(currPath===EXIT_ALTERNATIVE){foundCompletePath&&possiblePaths.at(-1).idx<=minimalAlternativesIndex&&possiblePaths.pop();continue}const currDef=currPath.def,currIdx=currPath.idx,currRuleStack=currPath.ruleStack,currOccurrenceStack=currPath.occurrenceStack;if(currDef.length===0)continue;const prod=currDef[0];if(prod===EXIT_NON_TERMINAL){const nextPath={idx:currIdx,def:currDef.slice(1),ruleStack:currRuleStack.slice(0,-1),occurrenceStack:currOccurrenceStack.slice(0,-1)};possiblePaths.push(nextPath)}else if(prod instanceof Terminal)if(currIdx<tokenVectorLength-1){const nextIdx=currIdx+1,actualToken=tokenVector[nextIdx];if(tokMatcher(actualToken,prod.terminalType)){const nextPath={idx:nextIdx,def:currDef.slice(1),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPath)}}else if(currIdx===tokenVectorLength-1)result.push({nextTokenType:prod.terminalType,nextTokenOccurrence:prod.idx,ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack}),foundCompletePath=!0;else throw Error("non exhaustive match");else if(prod instanceof NonTerminal){const newRuleStack=[...currRuleStack];newRuleStack.push(prod.nonTerminalName);const newOccurrenceStack=[...currOccurrenceStack];newOccurrenceStack.push(prod.idx);const nextPath={idx:currIdx,def:prod.definition.concat(EXIT_NON_TERMINAL_ARR,currDef.slice(1)),ruleStack:newRuleStack,occurrenceStack:newOccurrenceStack};possiblePaths.push(nextPath)}else if(prod instanceof Option$1){const nextPathWithout={idx:currIdx,def:currDef.slice(1),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWithout),possiblePaths.push(EXIT_ALTERNATIVE);const nextPathWith={idx:currIdx,def:prod.definition.concat(currDef.slice(1)),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWith)}else if(prod instanceof RepetitionMandatory){const secondIteration=new Repetition({definition:prod.definition,idx:prod.idx}),nextDef=prod.definition.concat([secondIteration],currDef.slice(1)),nextPath={idx:currIdx,def:nextDef,ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPath)}else if(prod instanceof RepetitionMandatoryWithSeparator){const separatorGast=new Terminal({terminalType:prod.separator}),secondIteration=new Repetition({definition:[separatorGast].concat(prod.definition),idx:prod.idx}),nextDef=prod.definition.concat([secondIteration],currDef.slice(1)),nextPath={idx:currIdx,def:nextDef,ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPath)}else if(prod instanceof RepetitionWithSeparator){const nextPathWithout={idx:currIdx,def:currDef.slice(1),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWithout),possiblePaths.push(EXIT_ALTERNATIVE);const separatorGast=new Terminal({terminalType:prod.separator}),nthRepetition=new Repetition({definition:[separatorGast].concat(prod.definition),idx:prod.idx}),nextDef=prod.definition.concat([nthRepetition],currDef.slice(1)),nextPathWith={idx:currIdx,def:nextDef,ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWith)}else if(prod instanceof Repetition){const nextPathWithout={idx:currIdx,def:currDef.slice(1),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWithout),possiblePaths.push(EXIT_ALTERNATIVE);const nthRepetition=new Repetition({definition:prod.definition,idx:prod.idx}),nextDef=prod.definition.concat([nthRepetition],currDef.slice(1)),nextPathWith={idx:currIdx,def:nextDef,ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(nextPathWith)}else if(prod instanceof Alternation)for(let i=prod.definition.length-1;i>=0;i--){const currAlt=prod.definition[i],currAltPath={idx:currIdx,def:currAlt.definition.concat(currDef.slice(1)),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack};possiblePaths.push(currAltPath),possiblePaths.push(EXIT_ALTERNATIVE)}else if(prod instanceof Alternative)possiblePaths.push({idx:currIdx,def:prod.definition.concat(currDef.slice(1)),ruleStack:currRuleStack,occurrenceStack:currOccurrenceStack});else if(prod instanceof Rule)possiblePaths.push(expandTopLevelRule(prod,currIdx,currRuleStack,currOccurrenceStack));else throw Error("non exhaustive match")}return result}function expandTopLevelRule(topRule,currIdx,currRuleStack,currOccurrenceStack){const newRuleStack=[...currRuleStack];newRuleStack.push(topRule.name);const newCurrOccurrenceStack=[...currOccurrenceStack];return newCurrOccurrenceStack.push(1),{idx:currIdx,def:topRule.definition,ruleStack:newRuleStack,occurrenceStack:newCurrOccurrenceStack}}var PROD_TYPE;(function(PROD_TYPE2){PROD_TYPE2[PROD_TYPE2.OPTION=0]="OPTION",PROD_TYPE2[PROD_TYPE2.REPETITION=1]="REPETITION",PROD_TYPE2[PROD_TYPE2.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",PROD_TYPE2[PROD_TYPE2.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",PROD_TYPE2[PROD_TYPE2.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",PROD_TYPE2[PROD_TYPE2.ALTERNATION=5]="ALTERNATION"})(PROD_TYPE||(PROD_TYPE={}));function getProdType$1(prod){if(prod instanceof Option$1||prod==="Option")return PROD_TYPE.OPTION;if(prod instanceof Repetition||prod==="Repetition")return PROD_TYPE.REPETITION;if(prod instanceof RepetitionMandatory||prod==="RepetitionMandatory")return PROD_TYPE.REPETITION_MANDATORY;if(prod instanceof RepetitionMandatoryWithSeparator||prod==="RepetitionMandatoryWithSeparator")return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;if(prod instanceof RepetitionWithSeparator||prod==="RepetitionWithSeparator")return PROD_TYPE.REPETITION_WITH_SEPARATOR;if(prod instanceof Alternation||prod==="Alternation")return PROD_TYPE.ALTERNATION;throw Error("non exhaustive match")}function getLookaheadPaths(options){const{occurrence,rule,prodType,maxLookahead}=options,type=getProdType$1(prodType);return type===PROD_TYPE.ALTERNATION?getLookaheadPathsForOr(occurrence,rule,maxLookahead):getLookaheadPathsForOptionalProd(occurrence,rule,type,maxLookahead)}function buildLookaheadFuncForOr(occurrence,ruleGrammar,maxLookahead,hasPredicates,dynamicTokensEnabled,laFuncBuilder){const lookAheadPaths=getLookaheadPathsForOr(occurrence,ruleGrammar,maxLookahead),tokenMatcher2=areTokenCategoriesNotUsed(lookAheadPaths)?tokenStructuredMatcherNoCategories:tokenStructuredMatcher;return laFuncBuilder(lookAheadPaths,hasPredicates,tokenMatcher2,dynamicTokensEnabled)}function buildLookaheadFuncForOptionalProd(occurrence,ruleGrammar,k,dynamicTokensEnabled,prodType,lookaheadBuilder){const lookAheadPaths=getLookaheadPathsForOptionalProd(occurrence,ruleGrammar,prodType,k),tokenMatcher2=areTokenCategoriesNotUsed(lookAheadPaths)?tokenStructuredMatcherNoCategories:tokenStructuredMatcher;return lookaheadBuilder(lookAheadPaths[0],tokenMatcher2,dynamicTokensEnabled)}function buildAlternativesLookAheadFunc(alts,hasPredicates,tokenMatcher2,dynamicTokensEnabled){const numOfAlts=alts.length,areAllOneTokenLookahead=alts.every(currAlt=>currAlt.every(currPath=>currPath.length===1));if(hasPredicates)return function(orAlts){const predicates=orAlts.map(currAlt=>currAlt.GATE);for(let t=0;t<numOfAlts;t++){const currAlt=alts[t],currNumOfPaths=currAlt.length,currPredicate=predicates[t];if(!(currPredicate!==void 0&&currPredicate.call(this)===!1))nextPath:for(let j=0;j<currNumOfPaths;j++){const currPath=currAlt[j],currPathLength=currPath.length;for(let i=0;i<currPathLength;i++){const nextToken=this.LA_FAST(i+1);if(tokenMatcher2(nextToken,currPath[i])===!1)continue nextPath}return t}}};if(areAllOneTokenLookahead&&!dynamicTokensEnabled){const choiceToAlt=alts.map(currAlt=>currAlt.flat()).reduce((result,currAlt,idx)=>(currAlt.forEach(currTokType=>{currTokType.tokenTypeIdx in result||(result[currTokType.tokenTypeIdx]=idx),currTokType.categoryMatches.forEach(currExtendingType=>{Object.hasOwn(result,currExtendingType)||(result[currExtendingType]=idx)})}),result),{});return function(){const nextToken=this.LA_FAST(1);return choiceToAlt[nextToken.tokenTypeIdx]}}else return function(){for(let t=0;t<numOfAlts;t++){const currAlt=alts[t],currNumOfPaths=currAlt.length;nextPath:for(let j=0;j<currNumOfPaths;j++){const currPath=currAlt[j],currPathLength=currPath.length;for(let i=0;i<currPathLength;i++){const nextToken=this.LA_FAST(i+1);if(tokenMatcher2(nextToken,currPath[i])===!1)continue nextPath}return t}}}}function buildSingleAlternativeLookaheadFunction(alt,tokenMatcher2,dynamicTokensEnabled){const areAllOneTokenLookahead=alt.every(currPath=>currPath.length===1),numOfPaths=alt.length;if(areAllOneTokenLookahead&&!dynamicTokensEnabled){const singleTokensTypes=alt.flat();if(singleTokensTypes.length===1&&singleTokensTypes[0].categoryMatches.length===0){const expectedTokenUniqueKey=singleTokensTypes[0].tokenTypeIdx;return function(){return this.LA_FAST(1).tokenTypeIdx===expectedTokenUniqueKey}}else{const choiceToAlt=singleTokensTypes.reduce((result,currTokType,idx)=>(result[currTokType.tokenTypeIdx]=!0,currTokType.categoryMatches.forEach(currExtendingType=>{result[currExtendingType]=!0}),result),[]);return function(){const nextToken=this.LA_FAST(1);return choiceToAlt[nextToken.tokenTypeIdx]===!0}}}else return function(){nextPath:for(let j=0;j<numOfPaths;j++){const currPath=alt[j],currPathLength=currPath.length;for(let i=0;i<currPathLength;i++){const nextToken=this.LA_FAST(i+1);if(tokenMatcher2(nextToken,currPath[i])===!1)continue nextPath}return!0}return!1}}class RestDefinitionFinderWalker extends RestWalker{constructor(topProd,targetOccurrence,targetProdType){super(),this.topProd=topProd,this.targetOccurrence=targetOccurrence,this.targetProdType=targetProdType}startWalking(){return this.walk(this.topProd),this.restDef}checkIsTarget(node,expectedProdType,currRest,prevRest){return node.idx===this.targetOccurrence&&this.targetProdType===expectedProdType?(this.restDef=currRest.concat(prevRest),!0):!1}walkOption(optionProd,currRest,prevRest){this.checkIsTarget(optionProd,PROD_TYPE.OPTION,currRest,prevRest)||super.walkOption(optionProd,currRest,prevRest)}walkAtLeastOne(atLeastOneProd,currRest,prevRest){this.checkIsTarget(atLeastOneProd,PROD_TYPE.REPETITION_MANDATORY,currRest,prevRest)||super.walkOption(atLeastOneProd,currRest,prevRest)}walkAtLeastOneSep(atLeastOneSepProd,currRest,prevRest){this.checkIsTarget(atLeastOneSepProd,PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,currRest,prevRest)||super.walkOption(atLeastOneSepProd,currRest,prevRest)}walkMany(manyProd,currRest,prevRest){this.checkIsTarget(manyProd,PROD_TYPE.REPETITION,currRest,prevRest)||super.walkOption(manyProd,currRest,prevRest)}walkManySep(manySepProd,currRest,prevRest){this.checkIsTarget(manySepProd,PROD_TYPE.REPETITION_WITH_SEPARATOR,currRest,prevRest)||super.walkOption(manySepProd,currRest,prevRest)}}class InsideDefinitionFinderVisitor extends GAstVisitor{constructor(targetOccurrence,targetProdType,targetRef){super(),this.targetOccurrence=targetOccurrence,this.targetProdType=targetProdType,this.targetRef=targetRef,this.result=[]}checkIsTarget(node,expectedProdName){node.idx===this.targetOccurrence&&this.targetProdType===expectedProdName&&(this.targetRef===void 0||node===this.targetRef)&&(this.result=node.definition)}visitOption(node){this.checkIsTarget(node,PROD_TYPE.OPTION)}visitRepetition(node){this.checkIsTarget(node,PROD_TYPE.REPETITION)}visitRepetitionMandatory(node){this.checkIsTarget(node,PROD_TYPE.REPETITION_MANDATORY)}visitRepetitionMandatoryWithSeparator(node){this.checkIsTarget(node,PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR)}visitRepetitionWithSeparator(node){this.checkIsTarget(node,PROD_TYPE.REPETITION_WITH_SEPARATOR)}visitAlternation(node){this.checkIsTarget(node,PROD_TYPE.ALTERNATION)}}function initializeArrayOfArrays(size){const result=new Array(size);for(let i=0;i<size;i++)result[i]=[];return result}function pathToHashKeys(path){let keys=[""];for(let i=0;i<path.length;i++){const tokType=path[i],longerKeys=[];for(let j=0;j<keys.length;j++){const currShorterKey=keys[j];longerKeys.push(currShorterKey+"_"+tokType.tokenTypeIdx);for(let t=0;t<tokType.categoryMatches.length;t++){const categoriesKeySuffix="_"+tokType.categoryMatches[t];longerKeys.push(currShorterKey+categoriesKeySuffix)}}keys=longerKeys}return keys}function isUniquePrefixHash(altKnownPathsKeys,searchPathKeys,idx){for(let currAltIdx=0;currAltIdx<altKnownPathsKeys.length;currAltIdx++){if(currAltIdx===idx)continue;const otherAltKnownPathsKeys=altKnownPathsKeys[currAltIdx];for(let searchIdx=0;searchIdx<searchPathKeys.length;searchIdx++){const searchKey=searchPathKeys[searchIdx];if(otherAltKnownPathsKeys[searchKey]===!0)return!1}}return!0}function lookAheadSequenceFromAlternatives(altsDefs,k){const partialAlts=altsDefs.map(currAlt=>possiblePathsFrom([currAlt],1)),finalResult=initializeArrayOfArrays(partialAlts.length),altsHashes=partialAlts.map(currAltPaths=>{const dict={};return currAltPaths.forEach(item=>{pathToHashKeys(item.partialPath).forEach(currKey=>{dict[currKey]=!0})}),dict});let newData=partialAlts;for(let pathLength=1;pathLength<=k;pathLength++){const currDataset=newData;newData=initializeArrayOfArrays(currDataset.length);for(let altIdx=0;altIdx<currDataset.length;altIdx++){const currAltPathsAndSuffixes=currDataset[altIdx];for(let currPathIdx=0;currPathIdx<currAltPathsAndSuffixes.length;currPathIdx++){const currPathPrefix=currAltPathsAndSuffixes[currPathIdx].partialPath,suffixDef=currAltPathsAndSuffixes[currPathIdx].suffixDef,prefixKeys=pathToHashKeys(currPathPrefix);if(isUniquePrefixHash(altsHashes,prefixKeys,altIdx)||suffixDef.length===0||currPathPrefix.length===k){const currAltResult=finalResult[altIdx];if(containsPath(currAltResult,currPathPrefix)===!1){currAltResult.push(currPathPrefix);for(let j=0;j<prefixKeys.length;j++){const currKey=prefixKeys[j];altsHashes[altIdx][currKey]=!0}}}else{const newPartialPathsAndSuffixes=possiblePathsFrom(suffixDef,pathLength+1,currPathPrefix);newData[altIdx]=newData[altIdx].concat(newPartialPathsAndSuffixes),newPartialPathsAndSuffixes.forEach(item=>{pathToHashKeys(item.partialPath).forEach(key=>{altsHashes[altIdx][key]=!0})})}}}}return finalResult}function getLookaheadPathsForOr(occurrence,ruleGrammar,k,orProd){const visitor2=new InsideDefinitionFinderVisitor(occurrence,PROD_TYPE.ALTERNATION,orProd);return ruleGrammar.accept(visitor2),lookAheadSequenceFromAlternatives(visitor2.result,k)}function getLookaheadPathsForOptionalProd(occurrence,ruleGrammar,prodType,k){const insideDefVisitor=new InsideDefinitionFinderVisitor(occurrence,prodType);ruleGrammar.accept(insideDefVisitor);const insideDef=insideDefVisitor.result,afterDef=new RestDefinitionFinderWalker(ruleGrammar,occurrence,prodType).startWalking(),insideFlat=new Alternative({definition:insideDef}),afterFlat=new Alternative({definition:afterDef});return lookAheadSequenceFromAlternatives([insideFlat,afterFlat],k)}function containsPath(alternative,searchPath){compareOtherPath:for(let i=0;i<alternative.length;i++){const otherPath=alternative[i];if(otherPath.length===searchPath.length){for(let j=0;j<otherPath.length;j++){const searchTok=searchPath[j],otherTok=otherPath[j];if((searchTok===otherTok||otherTok.categoryMatchesMap[searchTok.tokenTypeIdx]!==void 0)===!1)continue compareOtherPath}return!0}}return!1}function isStrictPrefixOfPath(prefix,other){return prefix.length<other.length&&prefix.every((tokType,idx)=>{const otherTokType=other[idx];return tokType===otherTokType||otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]})}function areTokenCategoriesNotUsed(lookAheadPaths){return lookAheadPaths.every(singleAltPaths=>singleAltPaths.every(singlePath=>singlePath.every(token=>token.categoryMatches.length===0)))}function validateLookahead(options){return options.lookaheadStrategy.validate({rules:options.rules,tokenTypes:options.tokenTypes,grammarName:options.grammarName}).map(errorMessage=>Object.assign({type:ParserDefinitionErrorType.CUSTOM_LOOKAHEAD_VALIDATION},errorMessage))}function validateGrammar$1(topLevels,tokenTypes,errMsgProvider,grammarName){const duplicateErrors=topLevels.flatMap(currTopLevel=>validateDuplicateProductions(currTopLevel,errMsgProvider)),termsNamespaceConflictErrors=checkTerminalAndNoneTerminalsNameSpace(topLevels,tokenTypes,errMsgProvider),tooManyAltsErrors=topLevels.flatMap(curRule=>validateTooManyAlts(curRule,errMsgProvider)),duplicateRulesError=topLevels.flatMap(curRule=>validateRuleDoesNotAlreadyExist(curRule,topLevels,grammarName,errMsgProvider));return duplicateErrors.concat(termsNamespaceConflictErrors,tooManyAltsErrors,duplicateRulesError)}function validateDuplicateProductions(topLevelRule,errMsgProvider){const collectorVisitor2=new OccurrenceValidationCollector;topLevelRule.accept(collectorVisitor2);const allRuleProductions=collectorVisitor2.allProductions,productionGroups=Object.groupBy(allRuleProductions,identifyProductionForDuplicates),duplicates=Object.fromEntries(Object.entries(productionGroups).filter(([_k,currGroup])=>currGroup.length>1));return Object.values(duplicates).map(currDuplicates=>{const firstProd=currDuplicates[0],msg=errMsgProvider.buildDuplicateFoundError(topLevelRule,currDuplicates),dslName=getProductionDslName$1(firstProd),defError={message:msg,type:ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,ruleName:topLevelRule.name,dslName,occurrence:firstProd.idx},param=getExtraProductionArgument(firstProd);return param&&(defError.parameter=param),defError})}function identifyProductionForDuplicates(prod){return`${getProductionDslName$1(prod)}_#_${prod.idx}_#_${getExtraProductionArgument(prod)}`}function getExtraProductionArgument(prod){return prod instanceof Terminal?prod.terminalType.name:prod instanceof NonTerminal?prod.nonTerminalName:""}class OccurrenceValidationCollector extends GAstVisitor{constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(subrule){this.allProductions.push(subrule)}visitOption(option2){this.allProductions.push(option2)}visitRepetitionWithSeparator(manySep){this.allProductions.push(manySep)}visitRepetitionMandatory(atLeastOne){this.allProductions.push(atLeastOne)}visitRepetitionMandatoryWithSeparator(atLeastOneSep){this.allProductions.push(atLeastOneSep)}visitRepetition(many){this.allProductions.push(many)}visitAlternation(or){this.allProductions.push(or)}visitTerminal(terminal){this.allProductions.push(terminal)}}function validateRuleDoesNotAlreadyExist(rule,allRules,className,errMsgProvider){const errors=[];if(allRules.reduce((result,curRule)=>curRule.name===rule.name?result+1:result,0)>1){const errMsg=errMsgProvider.buildDuplicateRuleNameError({topLevelRule:rule,grammarName:className});errors.push({message:errMsg,type:ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:rule.name})}return errors}function validateRuleIsOverridden(ruleName,definedRulesNames,className){const errors=[];let errMsg;return definedRulesNames.includes(ruleName)||(errMsg=`Invalid rule override, rule: ->${ruleName}<- cannot be overridden in the grammar: ->${className}<-as it is not defined in any of the super grammars `,errors.push({message:errMsg,type:ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,ruleName})),errors}function validateNoLeftRecursion(topRule,currRule,errMsgProvider,path=[]){const errors=[],nextNonTerminals=getFirstNoneTerminal(currRule.definition);if(nextNonTerminals.length===0)return[];{const ruleName=topRule.name;nextNonTerminals.includes(topRule)&&errors.push({message:errMsgProvider.buildLeftRecursionError({topLevelRule:topRule,leftRecursionPath:path}),type:ParserDefinitionErrorType.LEFT_RECURSION,ruleName});const excluded=path.concat([topRule]),errorsFromNextSteps=nextNonTerminals.filter(x=>!excluded.includes(x)).flatMap(currRefRule=>{const newPath=[...path];return newPath.push(currRefRule),validateNoLeftRecursion(topRule,currRefRule,errMsgProvider,newPath)});return errors.concat(errorsFromNextSteps)}}function getFirstNoneTerminal(definition){let result=[];if(definition.length===0)return result;const firstProd=definition[0];if(firstProd instanceof NonTerminal)result.push(firstProd.referencedRule);else if(firstProd instanceof Alternative||firstProd instanceof Option$1||firstProd instanceof RepetitionMandatory||firstProd instanceof RepetitionMandatoryWithSeparator||firstProd instanceof RepetitionWithSeparator||firstProd instanceof Repetition)result=result.concat(getFirstNoneTerminal(firstProd.definition));else if(firstProd instanceof Alternation)result=firstProd.definition.map(currSubDef=>getFirstNoneTerminal(currSubDef.definition)).flat();else if(!(firstProd instanceof Terminal))throw Error("non exhaustive match");const isFirstOptional=isOptionalProd(firstProd),hasMore=definition.length>1;if(isFirstOptional&&hasMore){const rest=definition.slice(1);return result.concat(getFirstNoneTerminal(rest))}else return result}class OrCollector extends GAstVisitor{constructor(){super(...arguments),this.alternations=[]}visitAlternation(node){this.alternations.push(node)}}function validateEmptyOrAlternative(topLevelRule,errMsgProvider){const orCollector=new OrCollector;return topLevelRule.accept(orCollector),orCollector.alternations.flatMap(currOr=>currOr.definition.slice(0,-1).flatMap((currAlternative,currAltIdx)=>nextPossibleTokensAfter([currAlternative],[],tokenStructuredMatcher,1).length===0?[{message:errMsgProvider.buildEmptyAlternationError({topLevelRule,alternation:currOr,emptyChoiceIdx:currAltIdx}),type:ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,ruleName:topLevelRule.name,occurrence:currOr.idx,alternative:currAltIdx+1}]:[]))}function validateAmbiguousAlternationAlternatives(topLevelRule,globalMaxLookahead,errMsgProvider){const orCollector=new OrCollector;topLevelRule.accept(orCollector);let ors=orCollector.alternations;return ors=ors.filter(currOr=>currOr.ignoreAmbiguities!==!0),ors.flatMap(currOr=>{const currOccurrence=currOr.idx,actualMaxLookahead=currOr.maxLookahead||globalMaxLookahead,alternatives=getLookaheadPathsForOr(currOccurrence,topLevelRule,actualMaxLookahead,currOr),altsAmbiguityErrors=checkAlternativesAmbiguities(alternatives,currOr,topLevelRule,errMsgProvider),altsPrefixAmbiguityErrors=checkPrefixAlternativesAmbiguities(alternatives,currOr,topLevelRule,errMsgProvider);return altsAmbiguityErrors.concat(altsPrefixAmbiguityErrors)})}class RepetitionCollector extends GAstVisitor{constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(manySep){this.allProductions.push(manySep)}visitRepetitionMandatory(atLeastOne){this.allProductions.push(atLeastOne)}visitRepetitionMandatoryWithSeparator(atLeastOneSep){this.allProductions.push(atLeastOneSep)}visitRepetition(many){this.allProductions.push(many)}}function validateTooManyAlts(topLevelRule,errMsgProvider){const orCollector=new OrCollector;return topLevelRule.accept(orCollector),orCollector.alternations.flatMap(currOr=>currOr.definition.length>255?[{message:errMsgProvider.buildTooManyAlternativesError({topLevelRule,alternation:currOr}),type:ParserDefinitionErrorType.TOO_MANY_ALTS,ruleName:topLevelRule.name,occurrence:currOr.idx}]:[])}function validateSomeNonEmptyLookaheadPath(topLevelRules,maxLookahead,errMsgProvider){const errors=[];return topLevelRules.forEach(currTopRule=>{const collectorVisitor2=new RepetitionCollector;currTopRule.accept(collectorVisitor2),collectorVisitor2.allProductions.forEach(currProd=>{const prodType=getProdType$1(currProd),actualMaxLookahead=currProd.maxLookahead||maxLookahead,currOccurrence=currProd.idx;if(getLookaheadPathsForOptionalProd(currOccurrence,currTopRule,prodType,actualMaxLookahead)[0].flat().length===0){const errMsg=errMsgProvider.buildEmptyRepetitionError({topLevelRule:currTopRule,repetition:currProd});errors.push({message:errMsg,type:ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,ruleName:currTopRule.name})}})}),errors}function checkAlternativesAmbiguities(alternatives,alternation2,rule,errMsgProvider){const foundAmbiguousPaths=[];return alternatives.reduce((result,currAlt,currAltIdx)=>(alternation2.definition[currAltIdx].ignoreAmbiguities===!0||currAlt.forEach(currPath=>{const altsCurrPathAppearsIn=[currAltIdx];alternatives.forEach((currOtherAlt,currOtherAltIdx)=>{currAltIdx!==currOtherAltIdx&&containsPath(currOtherAlt,currPath)&&alternation2.definition[currOtherAltIdx].ignoreAmbiguities!==!0&&altsCurrPathAppearsIn.push(currOtherAltIdx)}),altsCurrPathAppearsIn.length>1&&!containsPath(foundAmbiguousPaths,currPath)&&(foundAmbiguousPaths.push(currPath),result.push({alts:altsCurrPathAppearsIn,path:currPath}))}),result),[]).map(currAmbDescriptor=>{const ambgIndices=currAmbDescriptor.alts.map(currAltIdx=>currAltIdx+1);return{message:errMsgProvider.buildAlternationAmbiguityError({topLevelRule:rule,alternation:alternation2,ambiguityIndices:ambgIndices,prefixPath:currAmbDescriptor.path}),type:ParserDefinitionErrorType.AMBIGUOUS_ALTS,ruleName:rule.name,occurrence:alternation2.idx,alternatives:currAmbDescriptor.alts}})}function checkPrefixAlternativesAmbiguities(alternatives,alternation2,rule,errMsgProvider){const pathsAndIndices=alternatives.reduce((result,currAlt,idx)=>{const currPathsAndIdx=currAlt.map(currPath=>({idx,path:currPath}));return result.concat(currPathsAndIdx)},[]);return pathsAndIndices.flatMap(currPathAndIdx=>{if(alternation2.definition[currPathAndIdx.idx].ignoreAmbiguities===!0)return[];const targetIdx=currPathAndIdx.idx,targetPath=currPathAndIdx.path;return pathsAndIndices.filter(searchPathAndIdx=>alternation2.definition[searchPathAndIdx.idx].ignoreAmbiguities!==!0&&searchPathAndIdx.idx<targetIdx&&isStrictPrefixOfPath(searchPathAndIdx.path,targetPath)).map(currAmbPathAndIdx=>{const ambgIndices=[currAmbPathAndIdx.idx+1,targetIdx+1],occurrence=alternation2.idx===0?"":alternation2.idx;return{message:errMsgProvider.buildAlternationPrefixAmbiguityError({topLevelRule:rule,alternation:alternation2,ambiguityIndices:ambgIndices,prefixPath:currAmbPathAndIdx.path}),type:ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,ruleName:rule.name,occurrence,alternatives:ambgIndices}})})}function checkTerminalAndNoneTerminalsNameSpace(topLevels,tokenTypes,errMsgProvider){const errors=[],tokenNames=tokenTypes.map(currToken=>currToken.name);return topLevels.forEach(currRule=>{const currRuleName=currRule.name;if(tokenNames.includes(currRuleName)){const errMsg=errMsgProvider.buildNamespaceConflictError(currRule);errors.push({message:errMsg,type:ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:currRuleName})}}),errors}function resolveGrammar(options){const actualOptions=Object.assign({errMsgProvider:defaultGrammarResolverErrorProvider},options),topRulesTable={};return options.rules.forEach(rule=>{topRulesTable[rule.name]=rule}),resolveGrammar$1(topRulesTable,actualOptions.errMsgProvider)}function validateGrammar(options){var _a21;const errMsgProvider=(_a21=options.errMsgProvider)!==null&&_a21!==void 0?_a21:defaultGrammarValidatorErrorProvider;return validateGrammar$1(options.rules,options.tokenTypes,errMsgProvider,options.grammarName)}const MISMATCHED_TOKEN_EXCEPTION="MismatchedTokenException",NO_VIABLE_ALT_EXCEPTION="NoViableAltException",EARLY_EXIT_EXCEPTION="EarlyExitException",NOT_ALL_INPUT_PARSED_EXCEPTION="NotAllInputParsedException",RECOGNITION_EXCEPTION_NAMES=[MISMATCHED_TOKEN_EXCEPTION,NO_VIABLE_ALT_EXCEPTION,EARLY_EXIT_EXCEPTION,NOT_ALL_INPUT_PARSED_EXCEPTION];Object.freeze(RECOGNITION_EXCEPTION_NAMES);function isRecognitionException(error){return RECOGNITION_EXCEPTION_NAMES.includes(error.name)}class RecognitionException extends Error{constructor(message,token){super(message),this.token=token,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}class MismatchedTokenException extends RecognitionException{constructor(message,token,previousToken){super(message,token),this.previousToken=previousToken,this.name=MISMATCHED_TOKEN_EXCEPTION}}class NoViableAltException extends RecognitionException{constructor(message,token,previousToken){super(message,token),this.previousToken=previousToken,this.name=NO_VIABLE_ALT_EXCEPTION}}class NotAllInputParsedException extends RecognitionException{constructor(message,token){super(message,token),this.name=NOT_ALL_INPUT_PARSED_EXCEPTION}}class EarlyExitException extends RecognitionException{constructor(message,token,previousToken){super(message,token),this.previousToken=previousToken,this.name=EARLY_EXIT_EXCEPTION}}const EOF_FOLLOW_KEY={},IN_RULE_RECOVERY_EXCEPTION="InRuleRecoveryException";class InRuleRecoveryException extends Error{constructor(message){super(message),this.name=IN_RULE_RECOVERY_EXCEPTION}}class Recoverable{initRecoverable(config){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=Object.hasOwn(config,"recoveryEnabled")?config.recoveryEnabled:DEFAULT_PARSER_CONFIG.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=attemptInRepetitionRecovery)}getTokenToInsert(tokType){const tokToInsert=createTokenInstance(tokType,"",NaN,NaN,NaN,NaN,NaN,NaN);return tokToInsert.isInsertedInRecovery=!0,tokToInsert}canTokenTypeBeInsertedInRecovery(tokType){return!0}canTokenTypeBeDeletedInRecovery(tokType){return!0}tryInRepetitionRecovery(grammarRule,grammarRuleArgs,lookAheadFunc,expectedTokType){const reSyncTokType=this.findReSyncTokenType(),savedLexerState=this.exportLexerState(),resyncedTokens=[];let passedResyncPoint=!1;const nextTokenWithoutResync=this.LA_FAST(1);let currToken=this.LA_FAST(1);const generateErrorMessage=()=>{const previousToken=this.LA(0),msg=this.errorMessageProvider.buildMismatchTokenMessage({expected:expectedTokType,actual:nextTokenWithoutResync,previous:previousToken,ruleName:this.getCurrRuleFullName()}),error=new MismatchedTokenException(msg,nextTokenWithoutResync,this.LA(0));error.resyncedTokens=resyncedTokens.slice(0,-1),this.SAVE_ERROR(error)};for(;!passedResyncPoint;)if(this.tokenMatcher(currToken,expectedTokType)){generateErrorMessage();return}else if(lookAheadFunc.call(this)){generateErrorMessage(),grammarRule.apply(this,grammarRuleArgs);return}else this.tokenMatcher(currToken,reSyncTokType)?passedResyncPoint=!0:(currToken=this.SKIP_TOKEN(),this.addToResyncTokens(currToken,resyncedTokens));this.importLexerState(savedLexerState)}shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch,nextTokIdx,notStuck){return!(notStuck===!1||this.tokenMatcher(this.LA_FAST(1),expectTokAfterLastMatch)||this.isBackTracking()||this.canPerformInRuleRecovery(expectTokAfterLastMatch,this.getFollowsForInRuleRecovery(expectTokAfterLastMatch,nextTokIdx)))}getNextPossibleTokenTypes(grammarPath){const topRuleName=grammarPath.ruleStack[0],topProduction=this.getGAstProductions()[topRuleName];return new NextAfterTokenWalker(topProduction,grammarPath).startWalking()}getFollowsForInRuleRecovery(tokType,tokIdxInRule){const grammarPath=this.getCurrentGrammarPath(tokType,tokIdxInRule);return this.getNextPossibleTokenTypes(grammarPath)}tryInRuleRecovery(expectedTokType,follows){if(this.canRecoverWithSingleTokenInsertion(expectedTokType,follows))return this.getTokenToInsert(expectedTokType);if(this.canRecoverWithSingleTokenDeletion(expectedTokType)){const nextTok=this.SKIP_TOKEN();return this.consumeToken(),nextTok}throw new InRuleRecoveryException("sad sad panda")}canPerformInRuleRecovery(expectedToken,follows){return this.canRecoverWithSingleTokenInsertion(expectedToken,follows)||this.canRecoverWithSingleTokenDeletion(expectedToken)}canRecoverWithSingleTokenInsertion(expectedTokType,follows){if(!this.canTokenTypeBeInsertedInRecovery(expectedTokType)||follows.length===0)return!1;const mismatchedTok=this.LA_FAST(1);return follows.find(possibleFollowsTokType=>this.tokenMatcher(mismatchedTok,possibleFollowsTokType))!==void 0}canRecoverWithSingleTokenDeletion(expectedTokType){return this.canTokenTypeBeDeletedInRecovery(expectedTokType)?this.tokenMatcher(this.LA(2),expectedTokType):!1}isInCurrentRuleReSyncSet(tokenTypeIdx){const followKey=this.getCurrFollowKey();return this.getFollowSetFromFollowKey(followKey).includes(tokenTypeIdx)}findReSyncTokenType(){const allPossibleReSyncTokTypes=this.flattenFollowSet();let nextToken=this.LA_FAST(1),k=2;for(;;){const foundMatch=allPossibleReSyncTokTypes.find(resyncTokType=>tokenMatcher(nextToken,resyncTokType));if(foundMatch!==void 0)return foundMatch;nextToken=this.LA(k),k++}}getCurrFollowKey(){if(this.RULE_STACK_IDX===0)return EOF_FOLLOW_KEY;const currRuleShortName=this.currRuleShortName,currRuleIdx=this.getLastExplicitRuleOccurrenceIndex(),prevRuleShortName=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(currRuleShortName),idxInCallingRule:currRuleIdx,inRule:this.shortRuleNameToFullName(prevRuleShortName)}}buildFullFollowKeyStack(){const explicitRuleStack=this.RULE_STACK,explicitOccurrenceStack=this.RULE_OCCURRENCE_STACK,len=this.RULE_STACK_IDX+1,result=new Array(len);for(let idx=0;idx<len;idx++)idx===0?result[idx]=EOF_FOLLOW_KEY:result[idx]={ruleName:this.shortRuleNameToFullName(explicitRuleStack[idx]),idxInCallingRule:explicitOccurrenceStack[idx],inRule:this.shortRuleNameToFullName(explicitRuleStack[idx-1])};return result}flattenFollowSet(){return this.buildFullFollowKeyStack().map(currKey=>this.getFollowSetFromFollowKey(currKey)).flat()}getFollowSetFromFollowKey(followKey){if(followKey===EOF_FOLLOW_KEY)return[EOF];const followName=followKey.ruleName+followKey.idxInCallingRule+IN+followKey.inRule;return this.resyncFollows[followName]}addToResyncTokens(token,resyncTokens){return this.tokenMatcher(token,EOF)||resyncTokens.push(token),resyncTokens}reSyncTo(tokType){const resyncedTokens=[];let nextTok=this.LA_FAST(1);for(;this.tokenMatcher(nextTok,tokType)===!1;)nextTok=this.SKIP_TOKEN(),this.addToResyncTokens(nextTok,resyncedTokens);return resyncedTokens.slice(0,-1)}attemptInRepetitionRecovery(prodFunc,args,lookaheadFunc,dslMethodIdx,prodOccurrence,nextToksWalker,notStuck){}getCurrentGrammarPath(tokType,tokIdxInRule){const pathRuleStack=this.getHumanReadableRuleStack(),pathOccurrenceStack=this.RULE_OCCURRENCE_STACK.slice(0,this.RULE_OCCURRENCE_STACK_IDX+1);return{ruleStack:pathRuleStack,occurrenceStack:pathOccurrenceStack,lastTok:tokType,lastTokOccurrence:tokIdxInRule}}getHumanReadableRuleStack(){const len=this.RULE_STACK_IDX+1,result=new Array(len);for(let i=0;i<len;i++)result[i]=this.shortRuleNameToFullName(this.RULE_STACK[i]);return result}}function attemptInRepetitionRecovery(prodFunc,args,lookaheadFunc,dslMethodIdx,prodOccurrence,nextToksWalker,notStuck){const key=this.getKeyForAutomaticLookahead(dslMethodIdx,prodOccurrence);let firstAfterRepInfo=this.firstAfterRepMap[key];if(firstAfterRepInfo===void 0){const currRuleName=this.getCurrRuleFullName(),ruleGrammar=this.getGAstProductions()[currRuleName];firstAfterRepInfo=new nextToksWalker(ruleGrammar,prodOccurrence).startWalking(),this.firstAfterRepMap[key]=firstAfterRepInfo}let expectTokAfterLastMatch=firstAfterRepInfo.token,nextTokIdx=firstAfterRepInfo.occurrence;const isEndOfRule=firstAfterRepInfo.isEndOfRule;this.RULE_STACK_IDX===0&&isEndOfRule&&expectTokAfterLastMatch===void 0&&(expectTokAfterLastMatch=EOF,nextTokIdx=1),!(expectTokAfterLastMatch===void 0||nextTokIdx===void 0)&&this.shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch,nextTokIdx,notStuck)&&this.tryInRepetitionRecovery(prodFunc,args,lookaheadFunc,expectTokAfterLastMatch)}const BITS_FOR_METHOD_TYPE=4,BITS_FOR_OCCURRENCE_IDX=8,OR_IDX=1<<BITS_FOR_OCCURRENCE_IDX,OPTION_IDX=2<<BITS_FOR_OCCURRENCE_IDX,MANY_IDX=3<<BITS_FOR_OCCURRENCE_IDX,AT_LEAST_ONE_IDX=4<<BITS_FOR_OCCURRENCE_IDX,MANY_SEP_IDX=5<<BITS_FOR_OCCURRENCE_IDX,AT_LEAST_ONE_SEP_IDX=6<<BITS_FOR_OCCURRENCE_IDX;function getKeyForAutomaticLookahead(ruleIdx,dslMethodIdx,occurrence){return occurrence|dslMethodIdx|ruleIdx}class LLkLookaheadStrategy{constructor(options){var _a21;this.maxLookahead=(_a21=options==null?void 0:options.maxLookahead)!==null&&_a21!==void 0?_a21:DEFAULT_PARSER_CONFIG.maxLookahead}validate(options){const leftRecursionErrors=this.validateNoLeftRecursion(options.rules);if(leftRecursionErrors.length===0){const emptyAltErrors=this.validateEmptyOrAlternatives(options.rules),ambiguousAltsErrors=this.validateAmbiguousAlternationAlternatives(options.rules,this.maxLookahead),emptyRepetitionErrors=this.validateSomeNonEmptyLookaheadPath(options.rules,this.maxLookahead);return[...leftRecursionErrors,...emptyAltErrors,...ambiguousAltsErrors,...emptyRepetitionErrors]}return leftRecursionErrors}validateNoLeftRecursion(rules){return rules.flatMap(currTopRule=>validateNoLeftRecursion(currTopRule,currTopRule,defaultGrammarValidatorErrorProvider))}validateEmptyOrAlternatives(rules){return rules.flatMap(currTopRule=>validateEmptyOrAlternative(currTopRule,defaultGrammarValidatorErrorProvider))}validateAmbiguousAlternationAlternatives(rules,maxLookahead){return rules.flatMap(currTopRule=>validateAmbiguousAlternationAlternatives(currTopRule,maxLookahead,defaultGrammarValidatorErrorProvider))}validateSomeNonEmptyLookaheadPath(rules,maxLookahead){return validateSomeNonEmptyLookaheadPath(rules,maxLookahead,defaultGrammarValidatorErrorProvider)}buildLookaheadForAlternation(options){return buildLookaheadFuncForOr(options.prodOccurrence,options.rule,options.maxLookahead,options.hasPredicates,options.dynamicTokensEnabled,buildAlternativesLookAheadFunc)}buildLookaheadForOptional(options){return buildLookaheadFuncForOptionalProd(options.prodOccurrence,options.rule,options.maxLookahead,options.dynamicTokensEnabled,getProdType$1(options.prodType),buildSingleAlternativeLookaheadFunction)}}class LooksAhead{initLooksAhead(config){this.dynamicTokensEnabled=Object.hasOwn(config,"dynamicTokensEnabled")?config.dynamicTokensEnabled:DEFAULT_PARSER_CONFIG.dynamicTokensEnabled,this.maxLookahead=Object.hasOwn(config,"maxLookahead")?config.maxLookahead:DEFAULT_PARSER_CONFIG.maxLookahead,this.lookaheadStrategy=Object.hasOwn(config,"lookaheadStrategy")?config.lookaheadStrategy:new LLkLookaheadStrategy({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(rules){rules.forEach(currRule=>{this.TRACE_INIT(`${currRule.name} Rule Lookahead`,()=>{const{alternation:alternation2,repetition:repetition2,option:option2,repetitionMandatory:repetitionMandatory2,repetitionMandatoryWithSeparator,repetitionWithSeparator}=collectMethods(currRule);alternation2.forEach(currProd=>{const prodIdx=currProd.idx===0?"":currProd.idx;this.TRACE_INIT(`${getProductionDslName$1(currProd)}${prodIdx}`,()=>{const laFunc=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:currProd.idx,rule:currRule,maxLookahead:currProd.maxLookahead||this.maxLookahead,hasPredicates:currProd.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),key=getKeyForAutomaticLookahead(this.fullRuleNameToShort[currRule.name],OR_IDX,currProd.idx);this.setLaFuncCache(key,laFunc)})}),repetition2.forEach(currProd=>{this.computeLookaheadFunc(currRule,currProd.idx,MANY_IDX,"Repetition",currProd.maxLookahead,getProductionDslName$1(currProd))}),option2.forEach(currProd=>{this.computeLookaheadFunc(currRule,currProd.idx,OPTION_IDX,"Option",currProd.maxLookahead,getProductionDslName$1(currProd))}),repetitionMandatory2.forEach(currProd=>{this.computeLookaheadFunc(currRule,currProd.idx,AT_LEAST_ONE_IDX,"RepetitionMandatory",currProd.maxLookahead,getProductionDslName$1(currProd))}),repetitionMandatoryWithSeparator.forEach(currProd=>{this.computeLookaheadFunc(currRule,currProd.idx,AT_LEAST_ONE_SEP_IDX,"RepetitionMandatoryWithSeparator",currProd.maxLookahead,getProductionDslName$1(currProd))}),repetitionWithSeparator.forEach(currProd=>{this.computeLookaheadFunc(currRule,currProd.idx,MANY_SEP_IDX,"RepetitionWithSeparator",currProd.maxLookahead,getProductionDslName$1(currProd))})})})}computeLookaheadFunc(rule,prodOccurrence,prodKey,prodType,prodMaxLookahead,dslMethodName){this.TRACE_INIT(`${dslMethodName}${prodOccurrence===0?"":prodOccurrence}`,()=>{const laFunc=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence,rule,maxLookahead:prodMaxLookahead||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType}),key=getKeyForAutomaticLookahead(this.fullRuleNameToShort[rule.name],prodKey,prodOccurrence);this.setLaFuncCache(key,laFunc)})}getKeyForAutomaticLookahead(dslMethodIdx,occurrence){return getKeyForAutomaticLookahead(this.currRuleShortName,dslMethodIdx,occurrence)}getLaFuncFromCache(key){return this.lookAheadFuncsCache.get(key)}setLaFuncCache(key,value){this.lookAheadFuncsCache.set(key,value)}}class DslMethodsCollectorVisitor extends GAstVisitor{constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(option2){this.dslMethods.option.push(option2)}visitRepetitionWithSeparator(manySep){this.dslMethods.repetitionWithSeparator.push(manySep)}visitRepetitionMandatory(atLeastOne){this.dslMethods.repetitionMandatory.push(atLeastOne)}visitRepetitionMandatoryWithSeparator(atLeastOneSep){this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep)}visitRepetition(many){this.dslMethods.repetition.push(many)}visitAlternation(or){this.dslMethods.alternation.push(or)}}const collectorVisitor=new DslMethodsCollectorVisitor;function collectMethods(rule){collectorVisitor.reset(),rule.accept(collectorVisitor);const dslMethods=collectorVisitor.dslMethods;return collectorVisitor.reset(),dslMethods}function setNodeLocationOnlyOffset(currNodeLocation,newLocationInfo){isNaN(currNodeLocation.startOffset)===!0?(currNodeLocation.startOffset=newLocationInfo.startOffset,currNodeLocation.endOffset=newLocationInfo.endOffset):currNodeLocation.endOffset<newLocationInfo.endOffset&&(currNodeLocation.endOffset=newLocationInfo.endOffset)}function setNodeLocationFull(currNodeLocation,newLocationInfo){isNaN(currNodeLocation.startOffset)===!0?(currNodeLocation.startOffset=newLocationInfo.startOffset,currNodeLocation.startColumn=newLocationInfo.startColumn,currNodeLocation.startLine=newLocationInfo.startLine,currNodeLocation.endOffset=newLocationInfo.endOffset,currNodeLocation.endColumn=newLocationInfo.endColumn,currNodeLocation.endLine=newLocationInfo.endLine):currNodeLocation.endOffset<newLocationInfo.endOffset&&(currNodeLocation.endOffset=newLocationInfo.endOffset,currNodeLocation.endColumn=newLocationInfo.endColumn,currNodeLocation.endLine=newLocationInfo.endLine)}function addTerminalToCst(node,token,tokenTypeName){node.children[tokenTypeName]===void 0?node.children[tokenTypeName]=[token]:node.children[tokenTypeName].push(token)}function addNoneTerminalToCst(node,ruleName,ruleResult){node.children[ruleName]===void 0?node.children[ruleName]=[ruleResult]:node.children[ruleName].push(ruleResult)}const NAME="name";function defineNameProp(obj,nameValue){Object.defineProperty(obj,NAME,{enumerable:!1,configurable:!0,writable:!1,value:nameValue})}function defaultVisit(ctx,param){const childrenNames=Object.keys(ctx),childrenNamesLength=childrenNames.length;for(let i=0;i<childrenNamesLength;i++){const currChildName=childrenNames[i],currChildArray=ctx[currChildName],currChildArrayLength=currChildArray.length;for(let j=0;j<currChildArrayLength;j++){const currChild=currChildArray[j];currChild.tokenTypeIdx===void 0&&this[currChild.name](currChild.children,param)}}}function createBaseSemanticVisitorConstructor(grammarName,ruleNames){const derivedConstructor=function(){};defineNameProp(derivedConstructor,grammarName+"BaseSemantics");const semanticProto={visit:function(cstNode,param){if(Array.isArray(cstNode)&&(cstNode=cstNode[0]),cstNode!==void 0)return this[cstNode.name](cstNode.children,param)},validateVisitor:function(){const semanticDefinitionErrors=validateVisitor(this,ruleNames);if(semanticDefinitionErrors.length!==0){const errorMessages=semanticDefinitionErrors.map(currDefError=>currDefError.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>:
90
+ ${errorMessages.join(`
91
+
92
+ `).replace(/\n/g,`
93
+ `)}`)}}};return derivedConstructor.prototype=semanticProto,derivedConstructor.prototype.constructor=derivedConstructor,derivedConstructor._RULE_NAMES=ruleNames,derivedConstructor}function createBaseVisitorConstructorWithDefaults(grammarName,ruleNames,baseConstructor){const derivedConstructor=function(){};defineNameProp(derivedConstructor,grammarName+"BaseSemanticsWithDefaults");const withDefaultsProto=Object.create(baseConstructor.prototype);return ruleNames.forEach(ruleName=>{withDefaultsProto[ruleName]=defaultVisit}),derivedConstructor.prototype=withDefaultsProto,derivedConstructor.prototype.constructor=derivedConstructor,derivedConstructor}var CstVisitorDefinitionError;(function(CstVisitorDefinitionError2){CstVisitorDefinitionError2[CstVisitorDefinitionError2.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",CstVisitorDefinitionError2[CstVisitorDefinitionError2.MISSING_METHOD=1]="MISSING_METHOD"})(CstVisitorDefinitionError||(CstVisitorDefinitionError={}));function validateVisitor(visitorInstance,ruleNames){return validateMissingCstMethods(visitorInstance,ruleNames)}function validateMissingCstMethods(visitorInstance,ruleNames){return ruleNames.filter(currRuleName=>typeof visitorInstance[currRuleName]!="function").map(currRuleName=>({msg:`Missing visitor method: <${currRuleName}> on ${visitorInstance.constructor.name} CST Visitor.`,type:CstVisitorDefinitionError.MISSING_METHOD,methodName:currRuleName})).filter(Boolean)}class TreeBuilder{initTreeBuilder(config){if(this.CST_STACK=[],this.outputCst=config.outputCst,this.nodeLocationTracking=Object.hasOwn(config,"nodeLocationTracking")?config.nodeLocationTracking:DEFAULT_PARSER_CONFIG.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=()=>{},this.cstFinallyStateUpdate=()=>{},this.cstPostTerminal=()=>{},this.cstPostNonTerminal=()=>{},this.cstPostRule=()=>{};else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=setNodeLocationFull,this.setNodeLocationFromNode=setNodeLocationFull,this.cstPostRule=()=>{},this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=()=>{},this.setNodeLocationFromNode=()=>{},this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=setNodeLocationOnlyOffset,this.setNodeLocationFromNode=setNodeLocationOnlyOffset,this.cstPostRule=()=>{},this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=()=>{},this.setNodeLocationFromNode=()=>{},this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=()=>{},this.setNodeLocationFromNode=()=>{},this.cstPostRule=()=>{},this.setInitialNodeLocation=()=>{};else throw Error(`Invalid <nodeLocationTracking> config option: "${config.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(cstNode){cstNode.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(cstNode){cstNode.location={startOffset:this.LA_FAST(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(cstNode){cstNode.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(cstNode){const nextToken=this.LA_FAST(1);cstNode.location={startOffset:nextToken.startOffset,startLine:nextToken.startLine,startColumn:nextToken.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(fullRuleName){const cstNode={name:fullRuleName,children:Object.create(null)};this.setInitialNodeLocation(cstNode),this.CST_STACK.push(cstNode)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(ruleCstNode){const prevToken=this.LA(0),loc=ruleCstNode.location;loc.startOffset<=prevToken.startOffset?(loc.endOffset=prevToken.endOffset,loc.endLine=prevToken.endLine,loc.endColumn=prevToken.endColumn):(loc.startOffset=NaN,loc.startLine=NaN,loc.startColumn=NaN)}cstPostRuleOnlyOffset(ruleCstNode){const prevToken=this.LA(0),loc=ruleCstNode.location;loc.startOffset<=prevToken.startOffset?loc.endOffset=prevToken.endOffset:loc.startOffset=NaN}cstPostTerminal(key,consumedToken){const rootCst=this.CST_STACK[this.CST_STACK.length-1];addTerminalToCst(rootCst,consumedToken,key),this.setNodeLocationFromToken(rootCst.location,consumedToken)}cstPostNonTerminal(ruleCstResult,ruleName){const preCstNode=this.CST_STACK[this.CST_STACK.length-1];addNoneTerminalToCst(preCstNode,ruleName,ruleCstResult),this.setNodeLocationFromNode(preCstNode.location,ruleCstResult.location)}getBaseCstVisitorConstructor(){if(this.baseCstVisitorConstructor===void 0){const newBaseCstVisitorConstructor=createBaseSemanticVisitorConstructor(this.className,Object.keys(this.gastProductionsCache));return this.baseCstVisitorConstructor=newBaseCstVisitorConstructor,newBaseCstVisitorConstructor}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(this.baseCstVisitorWithDefaultsConstructor===void 0){const newConstructor=createBaseVisitorConstructorWithDefaults(this.className,Object.keys(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=newConstructor,newConstructor}return this.baseCstVisitorWithDefaultsConstructor}getPreviousExplicitRuleShortName(){return this.RULE_STACK[this.RULE_STACK_IDX-1]}getLastExplicitRuleOccurrenceIndex(){return this.RULE_OCCURRENCE_STACK[this.RULE_OCCURRENCE_STACK_IDX]}}class LexerAdapter{initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(newInput){if(this.selfAnalysisDone!==!0)throw Error("Missing <performSelfAnalysis> invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=newInput,this.tokVectorLength=newInput.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVectorLength-2?(this.consumeToken(),this.LA_FAST(1)):END_OF_FILE}LA_FAST(howMuch){const soughtIdx=this.currIdx+howMuch;return this.tokVector[soughtIdx]}LA(howMuch){const soughtIdx=this.currIdx+howMuch;return soughtIdx<0||this.tokVectorLength<=soughtIdx?END_OF_FILE:this.tokVector[soughtIdx]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(newState2){this.currIdx=newState2}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVectorLength-1}getLexerPosition(){return this.exportLexerState()}}class RecognizerApi{ACTION(impl){return impl.call(this)}consume(idx,tokType,options){return this.consumeInternal(tokType,idx,options)}subrule(idx,ruleToCall,options){return this.subruleInternal(ruleToCall,idx,options)}option(idx,actionORMethodDef){return this.optionInternal(actionORMethodDef,idx)}or(idx,altsOrOpts){return this.orInternal(altsOrOpts,idx)}many(idx,actionORMethodDef){return this.manyInternal(idx,actionORMethodDef)}atLeastOne(idx,actionORMethodDef){return this.atLeastOneInternal(idx,actionORMethodDef)}CONSUME(tokType,options){return this.consumeInternal(tokType,0,options)}CONSUME1(tokType,options){return this.consumeInternal(tokType,1,options)}CONSUME2(tokType,options){return this.consumeInternal(tokType,2,options)}CONSUME3(tokType,options){return this.consumeInternal(tokType,3,options)}CONSUME4(tokType,options){return this.consumeInternal(tokType,4,options)}CONSUME5(tokType,options){return this.consumeInternal(tokType,5,options)}CONSUME6(tokType,options){return this.consumeInternal(tokType,6,options)}CONSUME7(tokType,options){return this.consumeInternal(tokType,7,options)}CONSUME8(tokType,options){return this.consumeInternal(tokType,8,options)}CONSUME9(tokType,options){return this.consumeInternal(tokType,9,options)}SUBRULE(ruleToCall,options){return this.subruleInternal(ruleToCall,0,options)}SUBRULE1(ruleToCall,options){return this.subruleInternal(ruleToCall,1,options)}SUBRULE2(ruleToCall,options){return this.subruleInternal(ruleToCall,2,options)}SUBRULE3(ruleToCall,options){return this.subruleInternal(ruleToCall,3,options)}SUBRULE4(ruleToCall,options){return this.subruleInternal(ruleToCall,4,options)}SUBRULE5(ruleToCall,options){return this.subruleInternal(ruleToCall,5,options)}SUBRULE6(ruleToCall,options){return this.subruleInternal(ruleToCall,6,options)}SUBRULE7(ruleToCall,options){return this.subruleInternal(ruleToCall,7,options)}SUBRULE8(ruleToCall,options){return this.subruleInternal(ruleToCall,8,options)}SUBRULE9(ruleToCall,options){return this.subruleInternal(ruleToCall,9,options)}OPTION(actionORMethodDef){return this.optionInternal(actionORMethodDef,0)}OPTION1(actionORMethodDef){return this.optionInternal(actionORMethodDef,1)}OPTION2(actionORMethodDef){return this.optionInternal(actionORMethodDef,2)}OPTION3(actionORMethodDef){return this.optionInternal(actionORMethodDef,3)}OPTION4(actionORMethodDef){return this.optionInternal(actionORMethodDef,4)}OPTION5(actionORMethodDef){return this.optionInternal(actionORMethodDef,5)}OPTION6(actionORMethodDef){return this.optionInternal(actionORMethodDef,6)}OPTION7(actionORMethodDef){return this.optionInternal(actionORMethodDef,7)}OPTION8(actionORMethodDef){return this.optionInternal(actionORMethodDef,8)}OPTION9(actionORMethodDef){return this.optionInternal(actionORMethodDef,9)}OR(altsOrOpts){return this.orInternal(altsOrOpts,0)}OR1(altsOrOpts){return this.orInternal(altsOrOpts,1)}OR2(altsOrOpts){return this.orInternal(altsOrOpts,2)}OR3(altsOrOpts){return this.orInternal(altsOrOpts,3)}OR4(altsOrOpts){return this.orInternal(altsOrOpts,4)}OR5(altsOrOpts){return this.orInternal(altsOrOpts,5)}OR6(altsOrOpts){return this.orInternal(altsOrOpts,6)}OR7(altsOrOpts){return this.orInternal(altsOrOpts,7)}OR8(altsOrOpts){return this.orInternal(altsOrOpts,8)}OR9(altsOrOpts){return this.orInternal(altsOrOpts,9)}MANY(actionORMethodDef){this.manyInternal(0,actionORMethodDef)}MANY1(actionORMethodDef){this.manyInternal(1,actionORMethodDef)}MANY2(actionORMethodDef){this.manyInternal(2,actionORMethodDef)}MANY3(actionORMethodDef){this.manyInternal(3,actionORMethodDef)}MANY4(actionORMethodDef){this.manyInternal(4,actionORMethodDef)}MANY5(actionORMethodDef){this.manyInternal(5,actionORMethodDef)}MANY6(actionORMethodDef){this.manyInternal(6,actionORMethodDef)}MANY7(actionORMethodDef){this.manyInternal(7,actionORMethodDef)}MANY8(actionORMethodDef){this.manyInternal(8,actionORMethodDef)}MANY9(actionORMethodDef){this.manyInternal(9,actionORMethodDef)}MANY_SEP(options){this.manySepFirstInternal(0,options)}MANY_SEP1(options){this.manySepFirstInternal(1,options)}MANY_SEP2(options){this.manySepFirstInternal(2,options)}MANY_SEP3(options){this.manySepFirstInternal(3,options)}MANY_SEP4(options){this.manySepFirstInternal(4,options)}MANY_SEP5(options){this.manySepFirstInternal(5,options)}MANY_SEP6(options){this.manySepFirstInternal(6,options)}MANY_SEP7(options){this.manySepFirstInternal(7,options)}MANY_SEP8(options){this.manySepFirstInternal(8,options)}MANY_SEP9(options){this.manySepFirstInternal(9,options)}AT_LEAST_ONE(actionORMethodDef){this.atLeastOneInternal(0,actionORMethodDef)}AT_LEAST_ONE1(actionORMethodDef){return this.atLeastOneInternal(1,actionORMethodDef)}AT_LEAST_ONE2(actionORMethodDef){this.atLeastOneInternal(2,actionORMethodDef)}AT_LEAST_ONE3(actionORMethodDef){this.atLeastOneInternal(3,actionORMethodDef)}AT_LEAST_ONE4(actionORMethodDef){this.atLeastOneInternal(4,actionORMethodDef)}AT_LEAST_ONE5(actionORMethodDef){this.atLeastOneInternal(5,actionORMethodDef)}AT_LEAST_ONE6(actionORMethodDef){this.atLeastOneInternal(6,actionORMethodDef)}AT_LEAST_ONE7(actionORMethodDef){this.atLeastOneInternal(7,actionORMethodDef)}AT_LEAST_ONE8(actionORMethodDef){this.atLeastOneInternal(8,actionORMethodDef)}AT_LEAST_ONE9(actionORMethodDef){this.atLeastOneInternal(9,actionORMethodDef)}AT_LEAST_ONE_SEP(options){this.atLeastOneSepFirstInternal(0,options)}AT_LEAST_ONE_SEP1(options){this.atLeastOneSepFirstInternal(1,options)}AT_LEAST_ONE_SEP2(options){this.atLeastOneSepFirstInternal(2,options)}AT_LEAST_ONE_SEP3(options){this.atLeastOneSepFirstInternal(3,options)}AT_LEAST_ONE_SEP4(options){this.atLeastOneSepFirstInternal(4,options)}AT_LEAST_ONE_SEP5(options){this.atLeastOneSepFirstInternal(5,options)}AT_LEAST_ONE_SEP6(options){this.atLeastOneSepFirstInternal(6,options)}AT_LEAST_ONE_SEP7(options){this.atLeastOneSepFirstInternal(7,options)}AT_LEAST_ONE_SEP8(options){this.atLeastOneSepFirstInternal(8,options)}AT_LEAST_ONE_SEP9(options){this.atLeastOneSepFirstInternal(9,options)}RULE(name,implementation,config=DEFAULT_RULE_CONFIG){if(this.definedRulesNames.includes(name)){const error={message:defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({topLevelRule:name,grammarName:this.className}),type:ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:name};this.definitionErrors.push(error)}this.definedRulesNames.push(name);const ruleImplementation=this.defineRule(name,implementation,config);return this[name]=ruleImplementation,ruleImplementation}OVERRIDE_RULE(name,impl,config=DEFAULT_RULE_CONFIG){const ruleErrors=validateRuleIsOverridden(name,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(ruleErrors);const ruleImplementation=this.defineRule(name,impl,config);return this[name]=ruleImplementation,ruleImplementation}BACKTRACK(grammarRule,args){var _a21;const ruleToCall=(_a21=grammarRule.coreRule)!==null&&_a21!==void 0?_a21:grammarRule;return function(){this.isBackTrackingStack.push(1);const orgState=this.saveRecogState();try{return ruleToCall.apply(this,args),!0}catch(e){if(isRecognitionException(e))return!1;throw e}finally{this.reloadRecogState(orgState),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return serializeGrammar(Object.values(this.gastProductionsCache))}}class RecognizerEngine{initRecognizerEngine(tokenVocabulary,config){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=tokenStructuredMatcherNoCategories,this.subruleIdx=0,this.currRuleShortName=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_STACK_IDX=-1,this.RULE_OCCURRENCE_STACK=[],this.RULE_OCCURRENCE_STACK_IDX=-1,this.gastProductionsCache={},Object.hasOwn(config,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a <serializedGrammar> property.
94
+ See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0
95
+ For Further details.`);if(Array.isArray(tokenVocabulary)){if(tokenVocabulary.length===0)throw Error(`A Token Vocabulary cannot be empty.
96
+ Note that the first argument for the parser constructor
97
+ is no longer a Token vector (since v4.0).`);if(typeof tokenVocabulary[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument.
98
+ See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0
99
+ For Further details.`)}if(Array.isArray(tokenVocabulary))this.tokensMap=tokenVocabulary.reduce((acc,tokType)=>(acc[tokType.name]=tokType,acc),{});else if(Object.hasOwn(tokenVocabulary,"modes")&&Object.values(tokenVocabulary.modes).flat().every(isTokenType)){const allTokenTypes2=Object.values(tokenVocabulary.modes).flat(),uniqueTokens=[...new Set(allTokenTypes2)];this.tokensMap=uniqueTokens.reduce((acc,tokType)=>(acc[tokType.name]=tokType,acc),{})}else if(typeof tokenVocabulary=="object"&&tokenVocabulary!==null)this.tokensMap=Object.assign({},tokenVocabulary);else throw new Error("<tokensDictionary> argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=EOF;const noTokenCategoriesUsed=(Object.hasOwn(tokenVocabulary,"modes")?Object.values(tokenVocabulary.modes).flat():Object.values(tokenVocabulary)).every(tokenConstructor=>{var _a21;return((_a21=tokenConstructor.categoryMatches)===null||_a21===void 0?void 0:_a21.length)==0});this.tokenMatcher=noTokenCategoriesUsed?tokenStructuredMatcherNoCategories:tokenStructuredMatcher,augmentTokenTypes(Object.values(this.tokensMap))}defineRule(ruleName,impl,config){if(this.selfAnalysisDone)throw Error(`Grammar rule <${ruleName}> may not be defined after the 'performSelfAnalysis' method has been called'
100
+ Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);const resyncEnabled=Object.hasOwn(config,"resyncEnabled")?config.resyncEnabled:DEFAULT_RULE_CONFIG.resyncEnabled,recoveryValueFunc=Object.hasOwn(config,"recoveryValueFunc")?config.recoveryValueFunc:DEFAULT_RULE_CONFIG.recoveryValueFunc,shortName=this.ruleShortNameIdx<<BITS_FOR_METHOD_TYPE+BITS_FOR_OCCURRENCE_IDX;this.ruleShortNameIdx++,this.shortRuleNameToFull[shortName]=ruleName,this.fullRuleNameToShort[ruleName]=shortName;let coreRuleFunction;return this.outputCst===!0?coreRuleFunction=function(...args){try{this.ruleInvocationStateUpdate(shortName,ruleName,this.subruleIdx),impl.apply(this,args);const cst=this.CST_STACK[this.CST_STACK.length-1];return this.cstPostRule(cst),cst}catch(e){return this.invokeRuleCatch(e,resyncEnabled,recoveryValueFunc)}finally{this.ruleFinallyStateUpdate()}}:coreRuleFunction=function(...args){try{return this.ruleInvocationStateUpdate(shortName,ruleName,this.subruleIdx),impl.apply(this,args)}catch(e){return this.invokeRuleCatch(e,resyncEnabled,recoveryValueFunc)}finally{this.ruleFinallyStateUpdate()}},Object.assign(function(...args){this.onBeforeParse(ruleName);try{return coreRuleFunction.apply(this,args)}finally{this.onAfterParse(ruleName)}},{ruleName,originalGrammarAction:impl,coreRule:coreRuleFunction})}invokeRuleCatch(e,resyncEnabledConfig,recoveryValueFunc){const isFirstInvokedRule=this.RULE_STACK_IDX===0,reSyncEnabled=resyncEnabledConfig&&!this.isBackTracking()&&this.recoveryEnabled;if(isRecognitionException(e)){const recogError=e;if(reSyncEnabled){const reSyncTokType=this.findReSyncTokenType();if(this.isInCurrentRuleReSyncSet(reSyncTokType))if(recogError.resyncedTokens=this.reSyncTo(reSyncTokType),this.outputCst){const partialCstResult=this.CST_STACK[this.CST_STACK.length-1];return partialCstResult.recoveredNode=!0,partialCstResult}else return recoveryValueFunc(e);else{if(this.outputCst){const partialCstResult=this.CST_STACK[this.CST_STACK.length-1];partialCstResult.recoveredNode=!0,recogError.partialCstResult=partialCstResult}throw recogError}}else{if(isFirstInvokedRule)return this.moveToTerminatedState(),recoveryValueFunc(e);throw recogError}}else throw e}optionInternal(actionORMethodDef,occurrence){const key=this.getKeyForAutomaticLookahead(OPTION_IDX,occurrence);return this.optionInternalLogic(actionORMethodDef,occurrence,key)}optionInternalLogic(actionORMethodDef,occurrence,key){let lookAheadFunc=this.getLaFuncFromCache(key),action;if(typeof actionORMethodDef!="function"){action=actionORMethodDef.DEF;const predicate=actionORMethodDef.GATE;if(predicate!==void 0){const orgLookaheadFunction=lookAheadFunc;lookAheadFunc=()=>predicate.call(this)&&orgLookaheadFunction.call(this)}}else action=actionORMethodDef;if(lookAheadFunc.call(this)===!0)return action.call(this)}atLeastOneInternal(prodOccurrence,actionORMethodDef){const laKey=this.getKeyForAutomaticLookahead(AT_LEAST_ONE_IDX,prodOccurrence);return this.atLeastOneInternalLogic(prodOccurrence,actionORMethodDef,laKey)}atLeastOneInternalLogic(prodOccurrence,actionORMethodDef,key){let lookAheadFunc=this.getLaFuncFromCache(key),action;if(typeof actionORMethodDef!="function"){action=actionORMethodDef.DEF;const predicate=actionORMethodDef.GATE;if(predicate!==void 0){const orgLookaheadFunction=lookAheadFunc;lookAheadFunc=()=>predicate.call(this)&&orgLookaheadFunction.call(this)}}else action=actionORMethodDef;if(lookAheadFunc.call(this)===!0){let notStuck=this.doSingleRepetition(action);for(;lookAheadFunc.call(this)===!0&&notStuck===!0;)notStuck=this.doSingleRepetition(action)}else throw this.raiseEarlyExitException(prodOccurrence,PROD_TYPE.REPETITION_MANDATORY,actionORMethodDef.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[prodOccurrence,actionORMethodDef],lookAheadFunc,AT_LEAST_ONE_IDX,prodOccurrence,NextTerminalAfterAtLeastOneWalker)}atLeastOneSepFirstInternal(prodOccurrence,options){const laKey=this.getKeyForAutomaticLookahead(AT_LEAST_ONE_SEP_IDX,prodOccurrence);this.atLeastOneSepFirstInternalLogic(prodOccurrence,options,laKey)}atLeastOneSepFirstInternalLogic(prodOccurrence,options,key){const action=options.DEF,separator=options.SEP;if(this.getLaFuncFromCache(key).call(this)===!0){action.call(this);const separatorLookAheadFunc=()=>this.tokenMatcher(this.LA_FAST(1),separator);for(;this.tokenMatcher(this.LA_FAST(1),separator)===!0;)this.CONSUME(separator),action.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[prodOccurrence,separator,separatorLookAheadFunc,action,NextTerminalAfterAtLeastOneSepWalker],separatorLookAheadFunc,AT_LEAST_ONE_SEP_IDX,prodOccurrence,NextTerminalAfterAtLeastOneSepWalker)}else throw this.raiseEarlyExitException(prodOccurrence,PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,options.ERR_MSG)}manyInternal(prodOccurrence,actionORMethodDef){const laKey=this.getKeyForAutomaticLookahead(MANY_IDX,prodOccurrence);return this.manyInternalLogic(prodOccurrence,actionORMethodDef,laKey)}manyInternalLogic(prodOccurrence,actionORMethodDef,key){let lookaheadFunction=this.getLaFuncFromCache(key),action;if(typeof actionORMethodDef!="function"){action=actionORMethodDef.DEF;const predicate=actionORMethodDef.GATE;if(predicate!==void 0){const orgLookaheadFunction=lookaheadFunction;lookaheadFunction=()=>predicate.call(this)&&orgLookaheadFunction.call(this)}}else action=actionORMethodDef;let notStuck=!0;for(;lookaheadFunction.call(this)===!0&&notStuck===!0;)notStuck=this.doSingleRepetition(action);this.attemptInRepetitionRecovery(this.manyInternal,[prodOccurrence,actionORMethodDef],lookaheadFunction,MANY_IDX,prodOccurrence,NextTerminalAfterManyWalker,notStuck)}manySepFirstInternal(prodOccurrence,options){const laKey=this.getKeyForAutomaticLookahead(MANY_SEP_IDX,prodOccurrence);this.manySepFirstInternalLogic(prodOccurrence,options,laKey)}manySepFirstInternalLogic(prodOccurrence,options,key){const action=options.DEF,separator=options.SEP;if(this.getLaFuncFromCache(key).call(this)===!0){action.call(this);const separatorLookAheadFunc=()=>this.tokenMatcher(this.LA_FAST(1),separator);for(;this.tokenMatcher(this.LA_FAST(1),separator)===!0;)this.CONSUME(separator),action.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[prodOccurrence,separator,separatorLookAheadFunc,action,NextTerminalAfterManySepWalker],separatorLookAheadFunc,MANY_SEP_IDX,prodOccurrence,NextTerminalAfterManySepWalker)}}repetitionSepSecondInternal(prodOccurrence,separator,separatorLookAheadFunc,action,nextTerminalAfterWalker){for(;separatorLookAheadFunc();)this.CONSUME(separator),action.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[prodOccurrence,separator,separatorLookAheadFunc,action,nextTerminalAfterWalker],separatorLookAheadFunc,AT_LEAST_ONE_SEP_IDX,prodOccurrence,nextTerminalAfterWalker)}doSingleRepetition(action){const beforeIteration=this.getLexerPosition();return action.call(this),this.getLexerPosition()>beforeIteration}orInternal(altsOrOpts,occurrence){const laKey=this.getKeyForAutomaticLookahead(OR_IDX,occurrence),alts=Array.isArray(altsOrOpts)?altsOrOpts:altsOrOpts.DEF,altIdxToTake=this.getLaFuncFromCache(laKey).call(this,alts);if(altIdxToTake!==void 0)return alts[altIdxToTake].ALT.call(this);this.raiseNoAltException(occurrence,altsOrOpts.ERR_MSG)}ruleFinallyStateUpdate(){this.RULE_STACK_IDX--,this.RULE_OCCURRENCE_STACK_IDX--,this.RULE_STACK_IDX>=0&&(this.currRuleShortName=this.RULE_STACK[this.RULE_STACK_IDX]),this.cstFinallyStateUpdate()}subruleInternal(ruleToCall,idx,options){let ruleResult;try{const args=options!==void 0?options.ARGS:void 0;return this.subruleIdx=idx,ruleResult=ruleToCall.coreRule.apply(this,args),this.cstPostNonTerminal(ruleResult,options!==void 0&&options.LABEL!==void 0?options.LABEL:ruleToCall.ruleName),ruleResult}catch(e){throw this.subruleInternalError(e,options,ruleToCall.ruleName)}}subruleInternalError(e,options,ruleName){throw isRecognitionException(e)&&e.partialCstResult!==void 0&&(this.cstPostNonTerminal(e.partialCstResult,options!==void 0&&options.LABEL!==void 0?options.LABEL:ruleName),delete e.partialCstResult),e}consumeInternal(tokType,idx,options){let consumedToken;try{const nextToken=this.LA_FAST(1);this.tokenMatcher(nextToken,tokType)===!0?(this.consumeToken(),consumedToken=nextToken):this.consumeInternalError(tokType,nextToken,options)}catch(eFromConsumption){consumedToken=this.consumeInternalRecovery(tokType,idx,eFromConsumption)}return this.cstPostTerminal(options!==void 0&&options.LABEL!==void 0?options.LABEL:tokType.name,consumedToken),consumedToken}consumeInternalError(tokType,nextToken,options){let msg;const previousToken=this.LA(0);throw options!==void 0&&options.ERR_MSG?msg=options.ERR_MSG:msg=this.errorMessageProvider.buildMismatchTokenMessage({expected:tokType,actual:nextToken,previous:previousToken,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new MismatchedTokenException(msg,nextToken,previousToken))}consumeInternalRecovery(tokType,idx,eFromConsumption){if(this.recoveryEnabled&&eFromConsumption.name==="MismatchedTokenException"&&!this.isBackTracking()){const follows=this.getFollowsForInRuleRecovery(tokType,idx);try{return this.tryInRuleRecovery(tokType,follows)}catch(eFromInRuleRecovery){throw eFromInRuleRecovery.name===IN_RULE_RECOVERY_EXCEPTION?eFromConsumption:eFromInRuleRecovery}}else throw eFromConsumption}saveRecogState(){const savedErrors=this.errors,savedRuleStack=this.RULE_STACK.slice(0,this.RULE_STACK_IDX+1);return{errors:savedErrors,lexerState:this.exportLexerState(),RULE_STACK:savedRuleStack,CST_STACK:this.CST_STACK}}reloadRecogState(newState2){this.errors=newState2.errors,this.importLexerState(newState2.lexerState);const saved=newState2.RULE_STACK;for(let i=0;i<saved.length;i++)this.RULE_STACK[i]=saved[i];this.RULE_STACK_IDX=saved.length-1,this.RULE_STACK_IDX>=0&&(this.currRuleShortName=this.RULE_STACK[this.RULE_STACK_IDX])}ruleInvocationStateUpdate(shortName,fullName,idxInCallingRule){this.RULE_OCCURRENCE_STACK[++this.RULE_OCCURRENCE_STACK_IDX]=idxInCallingRule,this.RULE_STACK[++this.RULE_STACK_IDX]=shortName,this.currRuleShortName=shortName,this.cstInvocationStateUpdate(fullName)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){const shortName=this.currRuleShortName;return this.shortRuleNameToFull[shortName]}shortRuleNameToFullName(shortName){return this.shortRuleNameToFull[shortName]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),EOF)}reset(){this.resetLexerState(),this.subruleIdx=0,this.currRuleShortName=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK_IDX=-1,this.RULE_OCCURRENCE_STACK_IDX=-1,this.CST_STACK=[]}onBeforeParse(ruleName){for(let i=0;i<this.maxLookahead+1;i++)this.tokVector.push(END_OF_FILE)}onAfterParse(ruleName){if(this.isAtEndOfInput()===!1){const firstRedundantTok=this.LA(1),errMsg=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:firstRedundantTok,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new NotAllInputParsedException(errMsg,firstRedundantTok))}for(;this.tokVector.at(-1)===END_OF_FILE;)this.tokVector.pop()}}class ErrorHandler{initErrorHandler(config){this._errors=[],this.errorMessageProvider=Object.hasOwn(config,"errorMessageProvider")?config.errorMessageProvider:DEFAULT_PARSER_CONFIG.errorMessageProvider}SAVE_ERROR(error){if(isRecognitionException(error))return error.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:this.RULE_OCCURRENCE_STACK.slice(0,this.RULE_OCCURRENCE_STACK_IDX+1)},this._errors.push(error),error;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return[...this._errors]}set errors(newErrors){this._errors=newErrors}raiseEarlyExitException(occurrence,prodType,userDefinedErrMsg){const ruleName=this.getCurrRuleFullName(),ruleGrammar=this.getGAstProductions()[ruleName],insideProdPaths=getLookaheadPathsForOptionalProd(occurrence,ruleGrammar,prodType,this.maxLookahead)[0],actualTokens=[];for(let i=1;i<=this.maxLookahead;i++)actualTokens.push(this.LA(i));const msg=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:insideProdPaths,actual:actualTokens,previous:this.LA(0),customUserDescription:userDefinedErrMsg,ruleName});throw this.SAVE_ERROR(new EarlyExitException(msg,this.LA(1),this.LA(0)))}raiseNoAltException(occurrence,errMsgTypes){const ruleName=this.getCurrRuleFullName(),ruleGrammar=this.getGAstProductions()[ruleName],lookAheadPathsPerAlternative=getLookaheadPathsForOr(occurrence,ruleGrammar,this.maxLookahead),actualTokens=[];for(let i=1;i<=this.maxLookahead;i++)actualTokens.push(this.LA(i));const previousToken=this.LA(0),errMsg=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:lookAheadPathsPerAlternative,actual:actualTokens,previous:previousToken,customUserDescription:errMsgTypes,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new NoViableAltException(errMsg,this.LA(1),previousToken))}}const RECORDING_NULL_OBJECT={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(RECORDING_NULL_OBJECT);const HANDLE_SEPARATOR=!0,MAX_METHOD_IDX=Math.pow(2,BITS_FOR_OCCURRENCE_IDX)-1,RFT=createToken({name:"RECORDING_PHASE_TOKEN",pattern:Lexer.NA});augmentTokenTypes([RFT]);const RECORDING_PHASE_TOKEN=createTokenInstance(RFT,`This IToken indicates the Parser is in Recording Phase
101
+ See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(RECORDING_PHASE_TOKEN);const RECORDING_PHASE_CSTNODE={name:`This CSTNode indicates the Parser is in Recording Phase
102
+ See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}};class GastRecorder{initGastRecorder(config){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let i=0;i<10;i++){const idx=i>0?i:"";this[`CONSUME${idx}`]=function(arg1,arg2){return this.consumeInternalRecord(arg1,i,arg2)},this[`SUBRULE${idx}`]=function(arg1,arg2){return this.subruleInternalRecord(arg1,i,arg2)},this[`OPTION${idx}`]=function(arg1){return this.optionInternalRecord(arg1,i)},this[`OR${idx}`]=function(arg1){return this.orInternalRecord(arg1,i)},this[`MANY${idx}`]=function(arg1){this.manyInternalRecord(i,arg1)},this[`MANY_SEP${idx}`]=function(arg1){this.manySepFirstInternalRecord(i,arg1)},this[`AT_LEAST_ONE${idx}`]=function(arg1){this.atLeastOneInternalRecord(i,arg1)},this[`AT_LEAST_ONE_SEP${idx}`]=function(arg1){this.atLeastOneSepFirstInternalRecord(i,arg1)}}this.consume=function(idx,arg1,arg2){return this.consumeInternalRecord(arg1,idx,arg2)},this.subrule=function(idx,arg1,arg2){return this.subruleInternalRecord(arg1,idx,arg2)},this.option=function(idx,arg1){return this.optionInternalRecord(arg1,idx)},this.or=function(idx,arg1){return this.orInternalRecord(arg1,idx)},this.many=function(idx,arg1){this.manyInternalRecord(idx,arg1)},this.atLeastOne=function(idx,arg1){this.atLeastOneInternalRecord(idx,arg1)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{const that=this;for(let i=0;i<10;i++){const idx=i>0?i:"";delete that[`CONSUME${idx}`],delete that[`SUBRULE${idx}`],delete that[`OPTION${idx}`],delete that[`OR${idx}`],delete that[`MANY${idx}`],delete that[`MANY_SEP${idx}`],delete that[`AT_LEAST_ONE${idx}`],delete that[`AT_LEAST_ONE_SEP${idx}`]}delete that.consume,delete that.subrule,delete that.option,delete that.or,delete that.many,delete that.atLeastOne,delete that.ACTION,delete that.BACKTRACK,delete that.LA})}ACTION_RECORD(impl){}BACKTRACK_RECORD(grammarRule,args){return()=>!0}LA_RECORD(howMuch){return END_OF_FILE}topLevelRuleRecord(name,def){try{const newTopLevelRule=new Rule({definition:[],name});return newTopLevelRule.name=name,this.recordingProdStack.push(newTopLevelRule),def.call(this),this.recordingProdStack.pop(),newTopLevelRule}catch(originalError){if(originalError.KNOWN_RECORDER_ERROR!==!0)try{originalError.message=originalError.message+`
103
+ This error was thrown during the "grammar recording phase" For more info see:
104
+ https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw originalError}throw originalError}}optionInternalRecord(actionORMethodDef,occurrence){return recordProd.call(this,Option$1,actionORMethodDef,occurrence)}atLeastOneInternalRecord(occurrence,actionORMethodDef){recordProd.call(this,RepetitionMandatory,actionORMethodDef,occurrence)}atLeastOneSepFirstInternalRecord(occurrence,options){recordProd.call(this,RepetitionMandatoryWithSeparator,options,occurrence,HANDLE_SEPARATOR)}manyInternalRecord(occurrence,actionORMethodDef){recordProd.call(this,Repetition,actionORMethodDef,occurrence)}manySepFirstInternalRecord(occurrence,options){recordProd.call(this,RepetitionWithSeparator,options,occurrence,HANDLE_SEPARATOR)}orInternalRecord(altsOrOpts,occurrence){return recordOrProd.call(this,altsOrOpts,occurrence)}subruleInternalRecord(ruleToCall,occurrence,options){if(assertMethodIdxIsValid(occurrence),!ruleToCall||!Object.hasOwn(ruleToCall,"ruleName")){const error=new Error(`<SUBRULE${getIdxSuffix(occurrence)}> argument is invalid expecting a Parser method reference but got: <${JSON.stringify(ruleToCall)}>
105
+ inside top level rule: <${this.recordingProdStack[0].name}>`);throw error.KNOWN_RECORDER_ERROR=!0,error}const prevProd=this.recordingProdStack.at(-1),ruleName=ruleToCall.ruleName,newNoneTerminal=new NonTerminal({idx:occurrence,nonTerminalName:ruleName,label:options==null?void 0:options.LABEL,referencedRule:void 0});return prevProd.definition.push(newNoneTerminal),this.outputCst?RECORDING_PHASE_CSTNODE:RECORDING_NULL_OBJECT}consumeInternalRecord(tokType,occurrence,options){if(assertMethodIdxIsValid(occurrence),!hasShortKeyProperty(tokType)){const error=new Error(`<CONSUME${getIdxSuffix(occurrence)}> argument is invalid expecting a TokenType reference but got: <${JSON.stringify(tokType)}>
106
+ inside top level rule: <${this.recordingProdStack[0].name}>`);throw error.KNOWN_RECORDER_ERROR=!0,error}const prevProd=this.recordingProdStack.at(-1),newNoneTerminal=new Terminal({idx:occurrence,terminalType:tokType,label:options==null?void 0:options.LABEL});return prevProd.definition.push(newNoneTerminal),RECORDING_PHASE_TOKEN}}function recordProd(prodConstructor,mainProdArg,occurrence,handleSep=!1){assertMethodIdxIsValid(occurrence);const prevProd=this.recordingProdStack.at(-1),grammarAction=typeof mainProdArg=="function"?mainProdArg:mainProdArg.DEF,newProd=new prodConstructor({definition:[],idx:occurrence});return handleSep&&(newProd.separator=mainProdArg.SEP),Object.hasOwn(mainProdArg,"MAX_LOOKAHEAD")&&(newProd.maxLookahead=mainProdArg.MAX_LOOKAHEAD),this.recordingProdStack.push(newProd),grammarAction.call(this),prevProd.definition.push(newProd),this.recordingProdStack.pop(),RECORDING_NULL_OBJECT}function recordOrProd(mainProdArg,occurrence){assertMethodIdxIsValid(occurrence);const prevProd=this.recordingProdStack.at(-1),hasOptions=Array.isArray(mainProdArg)===!1,alts=hasOptions===!1?mainProdArg:mainProdArg.DEF,newOrProd=new Alternation({definition:[],idx:occurrence,ignoreAmbiguities:hasOptions&&mainProdArg.IGNORE_AMBIGUITIES===!0});Object.hasOwn(mainProdArg,"MAX_LOOKAHEAD")&&(newOrProd.maxLookahead=mainProdArg.MAX_LOOKAHEAD);const hasPredicates=alts.some(currAlt=>typeof currAlt.GATE=="function");return newOrProd.hasPredicates=hasPredicates,prevProd.definition.push(newOrProd),alts.forEach(currAlt=>{const currAltFlat=new Alternative({definition:[]});newOrProd.definition.push(currAltFlat),Object.hasOwn(currAlt,"IGNORE_AMBIGUITIES")?currAltFlat.ignoreAmbiguities=currAlt.IGNORE_AMBIGUITIES:Object.hasOwn(currAlt,"GATE")&&(currAltFlat.ignoreAmbiguities=!0),this.recordingProdStack.push(currAltFlat),currAlt.ALT.call(this),this.recordingProdStack.pop()}),RECORDING_NULL_OBJECT}function getIdxSuffix(idx){return idx===0?"":`${idx}`}function assertMethodIdxIsValid(idx){if(idx<0||idx>MAX_METHOD_IDX){const error=new Error(`Invalid DSL Method idx value: <${idx}>
107
+ Idx value must be a none negative value smaller than ${MAX_METHOD_IDX+1}`);throw error.KNOWN_RECORDER_ERROR=!0,error}}class PerformanceTracer{initPerformanceTracer(config){if(Object.hasOwn(config,"traceInitPerf")){const userTraceInitPerf=config.traceInitPerf,traceIsNumber=typeof userTraceInitPerf=="number";this.traceInitMaxIdent=traceIsNumber?userTraceInitPerf:1/0,this.traceInitPerf=traceIsNumber?userTraceInitPerf>0:userTraceInitPerf}else this.traceInitMaxIdent=0,this.traceInitPerf=DEFAULT_PARSER_CONFIG.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(phaseDesc,phaseImpl){if(this.traceInitPerf===!0){this.traceInitIndent++;const indent=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent<this.traceInitMaxIdent&&console.log(`${indent}--> <${phaseDesc}>`);const{time,value}=timer(phaseImpl),traceMethod=time>10?console.warn:console.log;return this.traceInitIndent<this.traceInitMaxIdent&&traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`),this.traceInitIndent--,value}else return phaseImpl()}}function applyMixins(derivedCtor,baseCtors){baseCtors.forEach(baseCtor=>{const baseProto=baseCtor.prototype;Object.getOwnPropertyNames(baseProto).forEach(propName=>{if(propName==="constructor")return;const basePropDescriptor=Object.getOwnPropertyDescriptor(baseProto,propName);basePropDescriptor&&(basePropDescriptor.get||basePropDescriptor.set)?Object.defineProperty(derivedCtor.prototype,propName,basePropDescriptor):derivedCtor.prototype[propName]=baseCtor.prototype[propName]})})}const END_OF_FILE=createTokenInstance(EOF,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(END_OF_FILE);const DEFAULT_PARSER_CONFIG=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:defaultParserErrorProvider,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),DEFAULT_RULE_CONFIG=Object.freeze({recoveryValueFunc:()=>{},resyncEnabled:!0});var ParserDefinitionErrorType;(function(ParserDefinitionErrorType2){ParserDefinitionErrorType2[ParserDefinitionErrorType2.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",ParserDefinitionErrorType2[ParserDefinitionErrorType2.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",ParserDefinitionErrorType2[ParserDefinitionErrorType2.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",ParserDefinitionErrorType2[ParserDefinitionErrorType2.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",ParserDefinitionErrorType2[ParserDefinitionErrorType2.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",ParserDefinitionErrorType2[ParserDefinitionErrorType2.LEFT_RECURSION=5]="LEFT_RECURSION",ParserDefinitionErrorType2[ParserDefinitionErrorType2.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",ParserDefinitionErrorType2[ParserDefinitionErrorType2.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",ParserDefinitionErrorType2[ParserDefinitionErrorType2.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",ParserDefinitionErrorType2[ParserDefinitionErrorType2.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",ParserDefinitionErrorType2[ParserDefinitionErrorType2.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",ParserDefinitionErrorType2[ParserDefinitionErrorType2.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",ParserDefinitionErrorType2[ParserDefinitionErrorType2.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",ParserDefinitionErrorType2[ParserDefinitionErrorType2.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION"})(ParserDefinitionErrorType||(ParserDefinitionErrorType={}));function EMPTY_ALT(value=void 0){return function(){return value}}class Parser{static performSelfAnalysis(parserInstance){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let defErrorsMsgs;this.selfAnalysisDone=!0;const className=this.className;this.TRACE_INIT("toFastProps",()=>{toFastProperties(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),this.definedRulesNames.forEach(currRuleName=>{const originalGrammarAction=this[currRuleName].originalGrammarAction;let recordedRuleGast;this.TRACE_INIT(`${currRuleName} Rule`,()=>{recordedRuleGast=this.topLevelRuleRecord(currRuleName,originalGrammarAction)}),this.gastProductionsCache[currRuleName]=recordedRuleGast})}finally{this.disableRecording()}});let resolverErrors=[];if(this.TRACE_INIT("Grammar Resolving",()=>{resolverErrors=resolveGrammar({rules:Object.values(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(resolverErrors)}),this.TRACE_INIT("Grammar Validations",()=>{if(resolverErrors.length===0&&this.skipValidations===!1){const validationErrors=validateGrammar({rules:Object.values(this.gastProductionsCache),tokenTypes:Object.values(this.tokensMap),errMsgProvider:defaultGrammarValidatorErrorProvider,grammarName:className}),lookaheadValidationErrors=validateLookahead({lookaheadStrategy:this.lookaheadStrategy,rules:Object.values(this.gastProductionsCache),tokenTypes:Object.values(this.tokensMap),grammarName:className});this.definitionErrors=this.definitionErrors.concat(validationErrors,lookaheadValidationErrors)}}),this.definitionErrors.length===0&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{const allFollows=computeAllProdsFollows(Object.values(this.gastProductionsCache));this.resyncFollows=allFollows}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var _a21,_b;(_b=(_a21=this.lookaheadStrategy).initialize)===null||_b===void 0||_b.call(_a21,{rules:Object.values(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(Object.values(this.gastProductionsCache))})),!Parser.DEFER_DEFINITION_ERRORS_HANDLING&&this.definitionErrors.length!==0)throw defErrorsMsgs=this.definitionErrors.map(defError=>defError.message),new Error(`Parser Definition Errors detected:
108
+ ${defErrorsMsgs.join(`
109
+ -------------------------------
110
+ `)}`)})}constructor(tokenVocabulary,config){this.definitionErrors=[],this.selfAnalysisDone=!1;const that=this;if(that.initErrorHandler(config),that.initLexerAdapter(),that.initLooksAhead(config),that.initRecognizerEngine(tokenVocabulary,config),that.initRecoverable(config),that.initTreeBuilder(config),that.initGastRecorder(config),that.initPerformanceTracer(config),Object.hasOwn(config,"ignoredIssues"))throw new Error(`The <ignoredIssues> IParserConfig property has been deprecated.
111
+ Please use the <IGNORE_AMBIGUITIES> flag on the relevant DSL method instead.
112
+ See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES
113
+ For further details.`);this.skipValidations=Object.hasOwn(config,"skipValidations")?config.skipValidations:DEFAULT_PARSER_CONFIG.skipValidations}}Parser.DEFER_DEFINITION_ERRORS_HANDLING=!1;applyMixins(Parser,[Recoverable,LooksAhead,TreeBuilder,LexerAdapter,RecognizerEngine,RecognizerApi,ErrorHandler,GastRecorder,PerformanceTracer]);class EmbeddedActionsParser extends Parser{constructor(tokenVocabulary,config=DEFAULT_PARSER_CONFIG){const configClone=Object.assign({},config);configClone.outputCst=!1,super(tokenVocabulary,configClone)}}function buildATNKey(rule,type,occurrence){return`${rule.name}_${type}_${occurrence}`}const ATN_BASIC=1,ATN_RULE_START=2,ATN_PLUS_BLOCK_START=4,ATN_STAR_BLOCK_START=5,ATN_RULE_STOP=7,ATN_BLOCK_END=8,ATN_STAR_LOOP_BACK=9,ATN_STAR_LOOP_ENTRY=10,ATN_PLUS_LOOP_BACK=11,ATN_LOOP_END=12;class AbstractTransition{constructor(target){this.target=target}isEpsilon(){return!1}}class AtomTransition extends AbstractTransition{constructor(target,tokenType){super(target),this.tokenType=tokenType}}class EpsilonTransition extends AbstractTransition{constructor(target){super(target)}isEpsilon(){return!0}}class RuleTransition extends AbstractTransition{constructor(ruleStart,rule,followState){super(ruleStart),this.rule=rule,this.followState=followState}isEpsilon(){return!0}}function createATN(rules){const atn={decisionMap:{},decisionStates:[],ruleToStartState:new Map,ruleToStopState:new Map,states:[]};createRuleStartAndStopATNStates(atn,rules);const ruleLength=rules.length;for(let i=0;i<ruleLength;i++){const rule=rules[i],ruleBlock=block(atn,rule,rule);ruleBlock!==void 0&&buildRuleHandle(atn,rule,ruleBlock)}return atn}function createRuleStartAndStopATNStates(atn,rules){const ruleLength=rules.length;for(let i=0;i<ruleLength;i++){const rule=rules[i],start=newState(atn,rule,void 0,{type:ATN_RULE_START}),stop=newState(atn,rule,void 0,{type:ATN_RULE_STOP});start.stop=stop,atn.ruleToStartState.set(rule,start),atn.ruleToStopState.set(rule,stop)}}function atom(atn,rule,production){return production instanceof Terminal?tokenRef(atn,rule,production.terminalType,production):production instanceof NonTerminal?ruleRef(atn,rule,production):production instanceof Alternation?alternation(atn,rule,production):production instanceof Option$1?option(atn,rule,production):production instanceof Repetition?repetition(atn,rule,production):production instanceof RepetitionWithSeparator?repetitionSep(atn,rule,production):production instanceof RepetitionMandatory?repetitionMandatory(atn,rule,production):production instanceof RepetitionMandatoryWithSeparator?repetitionMandatorySep(atn,rule,production):block(atn,rule,production)}function repetition(atn,rule,repetition2){const starState=newState(atn,rule,repetition2,{type:ATN_STAR_BLOCK_START});defineDecisionState(atn,starState);const handle=makeAlts(atn,rule,starState,repetition2,block(atn,rule,repetition2));return star(atn,rule,repetition2,handle)}function repetitionSep(atn,rule,repetition2){const starState=newState(atn,rule,repetition2,{type:ATN_STAR_BLOCK_START});defineDecisionState(atn,starState);const handle=makeAlts(atn,rule,starState,repetition2,block(atn,rule,repetition2)),sep=tokenRef(atn,rule,repetition2.separator,repetition2);return star(atn,rule,repetition2,handle,sep)}function repetitionMandatory(atn,rule,repetition2){const plusState=newState(atn,rule,repetition2,{type:ATN_PLUS_BLOCK_START});defineDecisionState(atn,plusState);const handle=makeAlts(atn,rule,plusState,repetition2,block(atn,rule,repetition2));return plus(atn,rule,repetition2,handle)}function repetitionMandatorySep(atn,rule,repetition2){const plusState=newState(atn,rule,repetition2,{type:ATN_PLUS_BLOCK_START});defineDecisionState(atn,plusState);const handle=makeAlts(atn,rule,plusState,repetition2,block(atn,rule,repetition2)),sep=tokenRef(atn,rule,repetition2.separator,repetition2);return plus(atn,rule,repetition2,handle,sep)}function alternation(atn,rule,alternation2){const start=newState(atn,rule,alternation2,{type:ATN_BASIC});defineDecisionState(atn,start);const alts=map(alternation2.definition,e=>atom(atn,rule,e));return makeAlts(atn,rule,start,alternation2,...alts)}function option(atn,rule,option2){const start=newState(atn,rule,option2,{type:ATN_BASIC});defineDecisionState(atn,start);const handle=makeAlts(atn,rule,start,option2,block(atn,rule,option2));return optional(atn,rule,option2,handle)}function block(atn,rule,block2){const handles=filter(map(block2.definition,e=>atom(atn,rule,e)),e=>e!==void 0);return handles.length===1?handles[0]:handles.length===0?void 0:makeBlock(atn,handles)}function plus(atn,rule,plus2,handle,sep){const blkStart=handle.left,blkEnd=handle.right,loop=newState(atn,rule,plus2,{type:ATN_PLUS_LOOP_BACK});defineDecisionState(atn,loop);const end=newState(atn,rule,plus2,{type:ATN_LOOP_END});return blkStart.loopback=loop,end.loopback=loop,atn.decisionMap[buildATNKey(rule,sep?"RepetitionMandatoryWithSeparator":"RepetitionMandatory",plus2.idx)]=loop,epsilon(blkEnd,loop),sep===void 0?(epsilon(loop,blkStart),epsilon(loop,end)):(epsilon(loop,end),epsilon(loop,sep.left),epsilon(sep.right,blkStart)),{left:blkStart,right:end}}function star(atn,rule,star2,handle,sep){const start=handle.left,end=handle.right,entry=newState(atn,rule,star2,{type:ATN_STAR_LOOP_ENTRY});defineDecisionState(atn,entry);const loopEnd=newState(atn,rule,star2,{type:ATN_LOOP_END}),loop=newState(atn,rule,star2,{type:ATN_STAR_LOOP_BACK});return entry.loopback=loop,loopEnd.loopback=loop,epsilon(entry,start),epsilon(entry,loopEnd),epsilon(end,loop),sep!==void 0?(epsilon(loop,loopEnd),epsilon(loop,sep.left),epsilon(sep.right,start)):epsilon(loop,entry),atn.decisionMap[buildATNKey(rule,sep?"RepetitionWithSeparator":"Repetition",star2.idx)]=entry,{left:entry,right:loopEnd}}function optional(atn,rule,optional2,handle){const start=handle.left,end=handle.right;return epsilon(start,end),atn.decisionMap[buildATNKey(rule,"Option",optional2.idx)]=start,handle}function defineDecisionState(atn,state){return atn.decisionStates.push(state),state.decision=atn.decisionStates.length-1,state.decision}function makeAlts(atn,rule,start,production,...alts){const end=newState(atn,rule,production,{type:ATN_BLOCK_END,start});start.end=end;for(const alt of alts)alt!==void 0?(epsilon(start,alt.left),epsilon(alt.right,end)):epsilon(start,end);const handle={left:start,right:end};return atn.decisionMap[buildATNKey(rule,getProdType(production),production.idx)]=start,handle}function getProdType(production){if(production instanceof Alternation)return"Alternation";if(production instanceof Option$1)return"Option";if(production instanceof Repetition)return"Repetition";if(production instanceof RepetitionWithSeparator)return"RepetitionWithSeparator";if(production instanceof RepetitionMandatory)return"RepetitionMandatory";if(production instanceof RepetitionMandatoryWithSeparator)return"RepetitionMandatoryWithSeparator";throw new Error("Invalid production type encountered")}function makeBlock(atn,alts){const altsLength=alts.length;for(let i=0;i<altsLength-1;i++){const handle=alts[i];let transition;handle.left.transitions.length===1&&(transition=handle.left.transitions[0]);const isRuleTransition=transition instanceof RuleTransition,ruleTransition=transition,next=alts[i+1].left;handle.left.type===ATN_BASIC&&handle.right.type===ATN_BASIC&&transition!==void 0&&(isRuleTransition&&ruleTransition.followState===handle.right||transition.target===handle.right)?(isRuleTransition?ruleTransition.followState=next:transition.target=next,removeState(atn,handle.right)):epsilon(handle.right,next)}const first2=alts[0],last=alts[altsLength-1];return{left:first2.left,right:last.right}}function tokenRef(atn,rule,tokenType,production){const left=newState(atn,rule,production,{type:ATN_BASIC}),right=newState(atn,rule,production,{type:ATN_BASIC});return addTransition(left,new AtomTransition(right,tokenType)),{left,right}}function ruleRef(atn,currentRule,nonTerminal){const rule=nonTerminal.referencedRule,start=atn.ruleToStartState.get(rule),left=newState(atn,currentRule,nonTerminal,{type:ATN_BASIC}),right=newState(atn,currentRule,nonTerminal,{type:ATN_BASIC}),call=new RuleTransition(start,rule,right);return addTransition(left,call),{left,right}}function buildRuleHandle(atn,rule,block2){const start=atn.ruleToStartState.get(rule);epsilon(start,block2.left);const stop=atn.ruleToStopState.get(rule);return epsilon(block2.right,stop),{left:start,right:stop}}function epsilon(a,b){const transition=new EpsilonTransition(b);addTransition(a,transition)}function newState(atn,rule,production,partial){const t=Object.assign({atn,production,epsilonOnlyTransitions:!1,rule,transitions:[],nextTokenWithinRule:[],stateNumber:atn.states.length},partial);return atn.states.push(t),t}function addTransition(state,transition){state.transitions.length===0&&(state.epsilonOnlyTransitions=transition.isEpsilon()),state.transitions.push(transition)}function removeState(atn,state){atn.states.splice(atn.states.indexOf(state),1)}const DFA_ERROR={};class ATNConfigSet{constructor(){this.map={},this.configs=[]}get size(){return this.configs.length}finalize(){this.map={}}add(config){const key=getATNConfigKey(config);key in this.map||(this.map[key]=this.configs.length,this.configs.push(config))}get elements(){return this.configs}get alts(){return map(this.configs,e=>e.alt)}get key(){let value="";for(const k in this.map)value+=k+":";return value}}function getATNConfigKey(config,alt=!0){return`${alt?`a${config.alt}`:""}s${config.state.stateNumber}:${config.stack.map(e=>e.stateNumber.toString()).join("_")}`}function createDFACache(startState,decision){const map2={};return predicateSet=>{const key=predicateSet.toString();let existing=map2[key];return existing!==void 0||(existing={atnStartState:startState,decision,states:{}},map2[key]=existing),existing}}class PredicateSet{constructor(){this.predicates=[]}is(index){return index>=this.predicates.length||this.predicates[index]}set(index,value){this.predicates[index]=value}toString(){let value="";const size=this.predicates.length;for(let i=0;i<size;i++)value+=this.predicates[i]===!0?"1":"0";return value}}const EMPTY_PREDICATES=new PredicateSet;class LLStarLookaheadStrategy extends LLkLookaheadStrategy{constructor(options){var _a21;super(),this.logging=(_a21=options==null?void 0:options.logging)!==null&&_a21!==void 0?_a21:(message=>console.log(message))}initialize(options){this.atn=createATN(options.rules),this.dfas=initATNSimulator(this.atn)}validateAmbiguousAlternationAlternatives(){return[]}validateEmptyOrAlternatives(){return[]}buildLookaheadForAlternation(options){const{prodOccurrence,rule,hasPredicates,dynamicTokensEnabled}=options,dfas=this.dfas,logging=this.logging,key=buildATNKey(rule,"Alternation",prodOccurrence),decisionIndex=this.atn.decisionMap[key].decision,partialAlts=map(getLookaheadPaths({maxLookahead:1,occurrence:prodOccurrence,prodType:"Alternation",rule}),currAlt=>map(currAlt,path=>path[0]));if(isLL1Sequence(partialAlts,!1)&&!dynamicTokensEnabled){const choiceToAlt=reduce(partialAlts,(result,currAlt,idx)=>(forEach(currAlt,currTokType=>{currTokType&&(result[currTokType.tokenTypeIdx]=idx,forEach(currTokType.categoryMatches,currExtendingType=>{result[currExtendingType]=idx}))}),result),{});return hasPredicates?function(orAlts){var _a21;const nextToken=this.LA_FAST(1),prediction=choiceToAlt[nextToken.tokenTypeIdx];if(orAlts!==void 0&&prediction!==void 0){const gate=(_a21=orAlts[prediction])===null||_a21===void 0?void 0:_a21.GATE;if(gate!==void 0&&gate.call(this)===!1)return}return prediction}:function(){const nextToken=this.LA_FAST(1);return choiceToAlt[nextToken.tokenTypeIdx]}}else return hasPredicates?function(orAlts){const predicates=new PredicateSet,length=orAlts===void 0?0:orAlts.length;for(let i=0;i<length;i++){const gate=orAlts==null?void 0:orAlts[i].GATE;predicates.set(i,gate===void 0||gate.call(this))}const result=adaptivePredict.call(this,dfas,decisionIndex,predicates,logging);return typeof result=="number"?result:void 0}:function(){const result=adaptivePredict.call(this,dfas,decisionIndex,EMPTY_PREDICATES,logging);return typeof result=="number"?result:void 0}}buildLookaheadForOptional(options){const{prodOccurrence,rule,prodType,dynamicTokensEnabled}=options,dfas=this.dfas,logging=this.logging,key=buildATNKey(rule,prodType,prodOccurrence),decisionIndex=this.atn.decisionMap[key].decision,alts=map(getLookaheadPaths({maxLookahead:1,occurrence:prodOccurrence,prodType,rule}),e=>map(e,g=>g[0]));if(isLL1Sequence(alts)&&alts[0][0]&&!dynamicTokensEnabled){const alt=alts[0],singleTokensTypes=flatten(alt);if(singleTokensTypes.length===1&&isEmpty(singleTokensTypes[0].categoryMatches)){const expectedTokenUniqueKey=singleTokensTypes[0].tokenTypeIdx;return function(){return this.LA_FAST(1).tokenTypeIdx===expectedTokenUniqueKey}}else{const choiceToAlt=reduce(singleTokensTypes,(result,currTokType)=>(currTokType!==void 0&&(result[currTokType.tokenTypeIdx]=!0,forEach(currTokType.categoryMatches,currExtendingType=>{result[currExtendingType]=!0})),result),{});return function(){const nextToken=this.LA_FAST(1);return choiceToAlt[nextToken.tokenTypeIdx]===!0}}}return function(){const result=adaptivePredict.call(this,dfas,decisionIndex,EMPTY_PREDICATES,logging);return typeof result=="object"?!1:result===0}}}function isLL1Sequence(sequences,allowEmpty=!0){const fullSet=new Set;for(const alt of sequences){const altSet=new Set;for(const tokType of alt){if(tokType===void 0){if(allowEmpty)break;return!1}const indices=[tokType.tokenTypeIdx].concat(tokType.categoryMatches);for(const index of indices)if(fullSet.has(index)){if(!altSet.has(index))return!1}else fullSet.add(index),altSet.add(index)}}return!0}function initATNSimulator(atn){const decisionLength=atn.decisionStates.length,decisionToDFA=Array(decisionLength);for(let i=0;i<decisionLength;i++)decisionToDFA[i]=createDFACache(atn.decisionStates[i],i);return decisionToDFA}function adaptivePredict(dfaCaches,decision,predicateSet,logging){const dfa=dfaCaches[decision](predicateSet);let start=dfa.start;if(start===void 0){const closure2=computeStartState(dfa.atnStartState);start=addDFAState(dfa,newDFAState(closure2)),dfa.start=start}return performLookahead.apply(this,[dfa,start,predicateSet,logging])}function performLookahead(dfa,s0,predicateSet,logging){let previousD=s0,i=1;const path=[];let t=this.LA_FAST(i++);for(;;){let d=getExistingTargetState(previousD,t);if(d===void 0&&(d=computeLookaheadTarget.apply(this,[dfa,previousD,t,i,predicateSet,logging])),d===DFA_ERROR)return buildAdaptivePredictError(path,previousD,t);if(d.isAcceptState===!0)return d.prediction;previousD=d,path.push(t),t=this.LA(i++)}}function computeLookaheadTarget(dfa,previousD,token,lookahead,predicateSet,logging){const reach=computeReachSet(previousD.configs,token,predicateSet);if(reach.size===0)return addDFAEdge(dfa,previousD,token,DFA_ERROR),DFA_ERROR;let newState2=newDFAState(reach);const predictedAlt=getUniqueAlt(reach,predicateSet);if(predictedAlt!==void 0)newState2.isAcceptState=!0,newState2.prediction=predictedAlt,newState2.configs.uniqueAlt=predictedAlt;else if(hasConflictTerminatingPrediction(reach)){const prediction=min(reach.alts);newState2.isAcceptState=!0,newState2.prediction=prediction,newState2.configs.uniqueAlt=prediction,reportLookaheadAmbiguity.apply(this,[dfa,lookahead,reach.alts,logging])}return newState2=addDFAEdge(dfa,previousD,token,newState2),newState2}function reportLookaheadAmbiguity(dfa,lookahead,ambiguityIndices,logging){const prefixPath=[];for(let i=1;i<=lookahead;i++)prefixPath.push(this.LA(i).tokenType);const atnState=dfa.atnStartState,topLevelRule=atnState.rule,production=atnState.production,message=buildAmbiguityError({topLevelRule,ambiguityIndices,production,prefixPath});logging(message)}function buildAmbiguityError(options){const pathMsg=map(options.prefixPath,currtok=>tokenLabel(currtok)).join(", "),occurrence=options.production.idx===0?"":options.production.idx;let currMessage=`Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(", ")}> in <${getProductionDslName(options.production)}${occurrence}> inside <${options.topLevelRule.name}> Rule,
114
+ <${pathMsg}> may appears as a prefix path in all these alternatives.
115
+ `;return currMessage=currMessage+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES
116
+ For Further details.`,currMessage}function getProductionDslName(prod){if(prod instanceof NonTerminal)return"SUBRULE";if(prod instanceof Option$1)return"OPTION";if(prod instanceof Alternation)return"OR";if(prod instanceof RepetitionMandatory)return"AT_LEAST_ONE";if(prod instanceof RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(prod instanceof RepetitionWithSeparator)return"MANY_SEP";if(prod instanceof Repetition)return"MANY";if(prod instanceof Terminal)return"CONSUME";throw Error("non exhaustive match")}function buildAdaptivePredictError(path,previous,current){const nextTransitions=flatMap(previous.configs.elements,e=>e.state.transitions),nextTokenTypes=uniqBy(nextTransitions.filter(e=>e instanceof AtomTransition).map(e=>e.tokenType),e=>e.tokenTypeIdx);return{actualToken:current,possibleTokenTypes:nextTokenTypes,tokenPath:path}}function getExistingTargetState(state,token){return state.edges[token.tokenTypeIdx]}function computeReachSet(configs,token,predicateSet){const intermediate=new ATNConfigSet,skippedStopStates=[];for(const c of configs.elements){if(predicateSet.is(c.alt)===!1)continue;if(c.state.type===ATN_RULE_STOP){skippedStopStates.push(c);continue}const transitionLength=c.state.transitions.length;for(let i=0;i<transitionLength;i++){const transition=c.state.transitions[i],target=getReachableTarget(transition,token);target!==void 0&&intermediate.add({state:target,alt:c.alt,stack:c.stack})}}let reach;if(skippedStopStates.length===0&&intermediate.size===1&&(reach=intermediate),reach===void 0){reach=new ATNConfigSet;for(const c of intermediate.elements)closure(c,reach)}if(skippedStopStates.length>0&&!hasConfigInRuleStopState(reach))for(const c of skippedStopStates)reach.add(c);return reach}function getReachableTarget(transition,token){if(transition instanceof AtomTransition&&tokenMatcher(token,transition.tokenType))return transition.target}function getUniqueAlt(configs,predicateSet){let alt;for(const c of configs.elements)if(predicateSet.is(c.alt)===!0){if(alt===void 0)alt=c.alt;else if(alt!==c.alt)return}return alt}function newDFAState(closure2){return{configs:closure2,edges:{},isAcceptState:!1,prediction:-1}}function addDFAEdge(dfa,from,token,to){return to=addDFAState(dfa,to),from.edges[token.tokenTypeIdx]=to,to}function addDFAState(dfa,state){if(state===DFA_ERROR)return state;const mapKey=state.configs.key,existing=dfa.states[mapKey];return existing!==void 0?existing:(state.configs.finalize(),dfa.states[mapKey]=state,state)}function computeStartState(atnState){const configs=new ATNConfigSet,numberOfTransitions=atnState.transitions.length;for(let i=0;i<numberOfTransitions;i++){const config={state:atnState.transitions[i].target,alt:i,stack:[]};closure(config,configs)}return configs}function closure(config,configs){const p=config.state;if(p.type===ATN_RULE_STOP){if(config.stack.length>0){const atnStack=[...config.stack],followConfig={state:atnStack.pop(),alt:config.alt,stack:atnStack};closure(followConfig,configs)}else configs.add(config);return}p.epsilonOnlyTransitions||configs.add(config);const transitionLength=p.transitions.length;for(let i=0;i<transitionLength;i++){const transition=p.transitions[i],c=getEpsilonTarget(config,transition);c!==void 0&&closure(c,configs)}}function getEpsilonTarget(config,transition){if(transition instanceof EpsilonTransition)return{state:transition.target,alt:config.alt,stack:config.stack};if(transition instanceof RuleTransition){const stack=[...config.stack,transition.followState];return{state:transition.target,alt:config.alt,stack}}}function hasConfigInRuleStopState(configs){for(const c of configs.elements)if(c.state.type===ATN_RULE_STOP)return!0;return!1}function allConfigsInRuleStopStates(configs){for(const c of configs.elements)if(c.state.type!==ATN_RULE_STOP)return!1;return!0}function hasConflictTerminatingPrediction(configs){if(allConfigsInRuleStopStates(configs))return!0;const altSets=getConflictingAltSets(configs.elements);return hasConflictingAltSet(altSets)&&!hasStateAssociatedWithOneAlt(altSets)}function getConflictingAltSets(configs){const configToAlts=new Map;for(const c of configs){const key=getATNConfigKey(c,!1);let alts=configToAlts.get(key);alts===void 0&&(alts={},configToAlts.set(key,alts)),alts[c.alt]=!0}return configToAlts}function hasConflictingAltSet(altSets){for(const value of Array.from(altSets.values()))if(Object.keys(value).length>1)return!0;return!1}function hasStateAssociatedWithOneAlt(altSets){for(const value of Array.from(altSets.values()))if(Object.keys(value).length===1)return!0;return!1}var DocumentUri;(function(DocumentUri2){function is2(value){return typeof value=="string"}DocumentUri2.is=is2})(DocumentUri||(DocumentUri={}));var URI$1;(function(URI2){function is2(value){return typeof value=="string"}URI2.is=is2})(URI$1||(URI$1={}));var integer;(function(integer2){integer2.MIN_VALUE=-2147483648,integer2.MAX_VALUE=2147483647;function is2(value){return typeof value=="number"&&integer2.MIN_VALUE<=value&&value<=integer2.MAX_VALUE}integer2.is=is2})(integer||(integer={}));var uinteger;(function(uinteger2){uinteger2.MIN_VALUE=0,uinteger2.MAX_VALUE=2147483647;function is2(value){return typeof value=="number"&&uinteger2.MIN_VALUE<=value&&value<=uinteger2.MAX_VALUE}uinteger2.is=is2})(uinteger||(uinteger={}));var Position;(function(Position2){function create(line,character){return line===Number.MAX_VALUE&&(line=uinteger.MAX_VALUE),character===Number.MAX_VALUE&&(character=uinteger.MAX_VALUE),{line,character}}Position2.create=create;function is2(value){let candidate=value;return Is.objectLiteral(candidate)&&Is.uinteger(candidate.line)&&Is.uinteger(candidate.character)}Position2.is=is2})(Position||(Position={}));var Range;(function(Range2){function create(one,two,three,four){if(Is.uinteger(one)&&Is.uinteger(two)&&Is.uinteger(three)&&Is.uinteger(four))return{start:Position.create(one,two),end:Position.create(three,four)};if(Position.is(one)&&Position.is(two))return{start:one,end:two};throw new Error(`Range#create called with invalid arguments[${one}, ${two}, ${three}, ${four}]`)}Range2.create=create;function is2(value){let candidate=value;return Is.objectLiteral(candidate)&&Position.is(candidate.start)&&Position.is(candidate.end)}Range2.is=is2})(Range||(Range={}));var Location;(function(Location2){function create(uri,range){return{uri,range}}Location2.create=create;function is2(value){let candidate=value;return Is.objectLiteral(candidate)&&Range.is(candidate.range)&&(Is.string(candidate.uri)||Is.undefined(candidate.uri))}Location2.is=is2})(Location||(Location={}));var LocationLink;(function(LocationLink2){function create(targetUri,targetRange,targetSelectionRange,originSelectionRange){return{targetUri,targetRange,targetSelectionRange,originSelectionRange}}LocationLink2.create=create;function is2(value){let candidate=value;return Is.objectLiteral(candidate)&&Range.is(candidate.targetRange)&&Is.string(candidate.targetUri)&&Range.is(candidate.targetSelectionRange)&&(Range.is(candidate.originSelectionRange)||Is.undefined(candidate.originSelectionRange))}LocationLink2.is=is2})(LocationLink||(LocationLink={}));var Color;(function(Color2){function create(red,green,blue,alpha){return{red,green,blue,alpha}}Color2.create=create;function is2(value){const candidate=value;return Is.objectLiteral(candidate)&&Is.numberRange(candidate.red,0,1)&&Is.numberRange(candidate.green,0,1)&&Is.numberRange(candidate.blue,0,1)&&Is.numberRange(candidate.alpha,0,1)}Color2.is=is2})(Color||(Color={}));var ColorInformation;(function(ColorInformation2){function create(range,color){return{range,color}}ColorInformation2.create=create;function is2(value){const candidate=value;return Is.objectLiteral(candidate)&&Range.is(candidate.range)&&Color.is(candidate.color)}ColorInformation2.is=is2})(ColorInformation||(ColorInformation={}));var ColorPresentation;(function(ColorPresentation2){function create(label,textEdit,additionalTextEdits){return{label,textEdit,additionalTextEdits}}ColorPresentation2.create=create;function is2(value){const candidate=value;return Is.objectLiteral(candidate)&&Is.string(candidate.label)&&(Is.undefined(candidate.textEdit)||TextEdit.is(candidate))&&(Is.undefined(candidate.additionalTextEdits)||Is.typedArray(candidate.additionalTextEdits,TextEdit.is))}ColorPresentation2.is=is2})(ColorPresentation||(ColorPresentation={}));var FoldingRangeKind;(function(FoldingRangeKind2){FoldingRangeKind2.Comment="comment",FoldingRangeKind2.Imports="imports",FoldingRangeKind2.Region="region"})(FoldingRangeKind||(FoldingRangeKind={}));var FoldingRange;(function(FoldingRange2){function create(startLine,endLine,startCharacter,endCharacter,kind,collapsedText){const result={startLine,endLine};return Is.defined(startCharacter)&&(result.startCharacter=startCharacter),Is.defined(endCharacter)&&(result.endCharacter=endCharacter),Is.defined(kind)&&(result.kind=kind),Is.defined(collapsedText)&&(result.collapsedText=collapsedText),result}FoldingRange2.create=create;function is2(value){const candidate=value;return Is.objectLiteral(candidate)&&Is.uinteger(candidate.startLine)&&Is.uinteger(candidate.startLine)&&(Is.undefined(candidate.startCharacter)||Is.uinteger(candidate.startCharacter))&&(Is.undefined(candidate.endCharacter)||Is.uinteger(candidate.endCharacter))&&(Is.undefined(candidate.kind)||Is.string(candidate.kind))}FoldingRange2.is=is2})(FoldingRange||(FoldingRange={}));var DiagnosticRelatedInformation;(function(DiagnosticRelatedInformation2){function create(location,message){return{location,message}}DiagnosticRelatedInformation2.create=create;function is2(value){let candidate=value;return Is.defined(candidate)&&Location.is(candidate.location)&&Is.string(candidate.message)}DiagnosticRelatedInformation2.is=is2})(DiagnosticRelatedInformation||(DiagnosticRelatedInformation={}));var DiagnosticSeverity;(function(DiagnosticSeverity2){DiagnosticSeverity2.Error=1,DiagnosticSeverity2.Warning=2,DiagnosticSeverity2.Information=3,DiagnosticSeverity2.Hint=4})(DiagnosticSeverity||(DiagnosticSeverity={}));var DiagnosticTag;(function(DiagnosticTag2){DiagnosticTag2.Unnecessary=1,DiagnosticTag2.Deprecated=2})(DiagnosticTag||(DiagnosticTag={}));var CodeDescription;(function(CodeDescription2){function is2(value){const candidate=value;return Is.objectLiteral(candidate)&&Is.string(candidate.href)}CodeDescription2.is=is2})(CodeDescription||(CodeDescription={}));var Diagnostic;(function(Diagnostic2){function create(range,message,severity,code,source,relatedInformation){let result={range,message};return Is.defined(severity)&&(result.severity=severity),Is.defined(code)&&(result.code=code),Is.defined(source)&&(result.source=source),Is.defined(relatedInformation)&&(result.relatedInformation=relatedInformation),result}Diagnostic2.create=create;function is2(value){var _a21;let candidate=value;return Is.defined(candidate)&&Range.is(candidate.range)&&Is.string(candidate.message)&&(Is.number(candidate.severity)||Is.undefined(candidate.severity))&&(Is.integer(candidate.code)||Is.string(candidate.code)||Is.undefined(candidate.code))&&(Is.undefined(candidate.codeDescription)||Is.string((_a21=candidate.codeDescription)===null||_a21===void 0?void 0:_a21.href))&&(Is.string(candidate.source)||Is.undefined(candidate.source))&&(Is.undefined(candidate.relatedInformation)||Is.typedArray(candidate.relatedInformation,DiagnosticRelatedInformation.is))}Diagnostic2.is=is2})(Diagnostic||(Diagnostic={}));var Command;(function(Command2){function create(title,command,...args){let result={title,command};return Is.defined(args)&&args.length>0&&(result.arguments=args),result}Command2.create=create;function is2(value){let candidate=value;return Is.defined(candidate)&&Is.string(candidate.title)&&Is.string(candidate.command)}Command2.is=is2})(Command||(Command={}));var TextEdit;(function(TextEdit2){function replace(range,newText){return{range,newText}}TextEdit2.replace=replace;function insert(position,newText){return{range:{start:position,end:position},newText}}TextEdit2.insert=insert;function del(range){return{range,newText:""}}TextEdit2.del=del;function is2(value){const candidate=value;return Is.objectLiteral(candidate)&&Is.string(candidate.newText)&&Range.is(candidate.range)}TextEdit2.is=is2})(TextEdit||(TextEdit={}));var ChangeAnnotation;(function(ChangeAnnotation2){function create(label,needsConfirmation,description){const result={label};return needsConfirmation!==void 0&&(result.needsConfirmation=needsConfirmation),description!==void 0&&(result.description=description),result}ChangeAnnotation2.create=create;function is2(value){const candidate=value;return Is.objectLiteral(candidate)&&Is.string(candidate.label)&&(Is.boolean(candidate.needsConfirmation)||candidate.needsConfirmation===void 0)&&(Is.string(candidate.description)||candidate.description===void 0)}ChangeAnnotation2.is=is2})(ChangeAnnotation||(ChangeAnnotation={}));var ChangeAnnotationIdentifier;(function(ChangeAnnotationIdentifier2){function is2(value){const candidate=value;return Is.string(candidate)}ChangeAnnotationIdentifier2.is=is2})(ChangeAnnotationIdentifier||(ChangeAnnotationIdentifier={}));var AnnotatedTextEdit;(function(AnnotatedTextEdit2){function replace(range,newText,annotation){return{range,newText,annotationId:annotation}}AnnotatedTextEdit2.replace=replace;function insert(position,newText,annotation){return{range:{start:position,end:position},newText,annotationId:annotation}}AnnotatedTextEdit2.insert=insert;function del(range,annotation){return{range,newText:"",annotationId:annotation}}AnnotatedTextEdit2.del=del;function is2(value){const candidate=value;return TextEdit.is(candidate)&&(ChangeAnnotation.is(candidate.annotationId)||ChangeAnnotationIdentifier.is(candidate.annotationId))}AnnotatedTextEdit2.is=is2})(AnnotatedTextEdit||(AnnotatedTextEdit={}));var TextDocumentEdit;(function(TextDocumentEdit2){function create(textDocument,edits){return{textDocument,edits}}TextDocumentEdit2.create=create;function is2(value){let candidate=value;return Is.defined(candidate)&&OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument)&&Array.isArray(candidate.edits)}TextDocumentEdit2.is=is2})(TextDocumentEdit||(TextDocumentEdit={}));var CreateFile;(function(CreateFile2){function create(uri,options,annotation){let result={kind:"create",uri};return options!==void 0&&(options.overwrite!==void 0||options.ignoreIfExists!==void 0)&&(result.options=options),annotation!==void 0&&(result.annotationId=annotation),result}CreateFile2.create=create;function is2(value){let candidate=value;return candidate&&candidate.kind==="create"&&Is.string(candidate.uri)&&(candidate.options===void 0||(candidate.options.overwrite===void 0||Is.boolean(candidate.options.overwrite))&&(candidate.options.ignoreIfExists===void 0||Is.boolean(candidate.options.ignoreIfExists)))&&(candidate.annotationId===void 0||ChangeAnnotationIdentifier.is(candidate.annotationId))}CreateFile2.is=is2})(CreateFile||(CreateFile={}));var RenameFile;(function(RenameFile2){function create(oldUri,newUri,options,annotation){let result={kind:"rename",oldUri,newUri};return options!==void 0&&(options.overwrite!==void 0||options.ignoreIfExists!==void 0)&&(result.options=options),annotation!==void 0&&(result.annotationId=annotation),result}RenameFile2.create=create;function is2(value){let candidate=value;return candidate&&candidate.kind==="rename"&&Is.string(candidate.oldUri)&&Is.string(candidate.newUri)&&(candidate.options===void 0||(candidate.options.overwrite===void 0||Is.boolean(candidate.options.overwrite))&&(candidate.options.ignoreIfExists===void 0||Is.boolean(candidate.options.ignoreIfExists)))&&(candidate.annotationId===void 0||ChangeAnnotationIdentifier.is(candidate.annotationId))}RenameFile2.is=is2})(RenameFile||(RenameFile={}));var DeleteFile;(function(DeleteFile2){function create(uri,options,annotation){let result={kind:"delete",uri};return options!==void 0&&(options.recursive!==void 0||options.ignoreIfNotExists!==void 0)&&(result.options=options),annotation!==void 0&&(result.annotationId=annotation),result}DeleteFile2.create=create;function is2(value){let candidate=value;return candidate&&candidate.kind==="delete"&&Is.string(candidate.uri)&&(candidate.options===void 0||(candidate.options.recursive===void 0||Is.boolean(candidate.options.recursive))&&(candidate.options.ignoreIfNotExists===void 0||Is.boolean(candidate.options.ignoreIfNotExists)))&&(candidate.annotationId===void 0||ChangeAnnotationIdentifier.is(candidate.annotationId))}DeleteFile2.is=is2})(DeleteFile||(DeleteFile={}));var WorkspaceEdit;(function(WorkspaceEdit2){function is2(value){let candidate=value;return candidate&&(candidate.changes!==void 0||candidate.documentChanges!==void 0)&&(candidate.documentChanges===void 0||candidate.documentChanges.every(change=>Is.string(change.kind)?CreateFile.is(change)||RenameFile.is(change)||DeleteFile.is(change):TextDocumentEdit.is(change)))}WorkspaceEdit2.is=is2})(WorkspaceEdit||(WorkspaceEdit={}));class TextEditChangeImpl{constructor(edits,changeAnnotations){this.edits=edits,this.changeAnnotations=changeAnnotations}insert(position,newText,annotation){let edit,id;if(annotation===void 0?edit=TextEdit.insert(position,newText):ChangeAnnotationIdentifier.is(annotation)?(id=annotation,edit=AnnotatedTextEdit.insert(position,newText,annotation)):(this.assertChangeAnnotations(this.changeAnnotations),id=this.changeAnnotations.manage(annotation),edit=AnnotatedTextEdit.insert(position,newText,id)),this.edits.push(edit),id!==void 0)return id}replace(range,newText,annotation){let edit,id;if(annotation===void 0?edit=TextEdit.replace(range,newText):ChangeAnnotationIdentifier.is(annotation)?(id=annotation,edit=AnnotatedTextEdit.replace(range,newText,annotation)):(this.assertChangeAnnotations(this.changeAnnotations),id=this.changeAnnotations.manage(annotation),edit=AnnotatedTextEdit.replace(range,newText,id)),this.edits.push(edit),id!==void 0)return id}delete(range,annotation){let edit,id;if(annotation===void 0?edit=TextEdit.del(range):ChangeAnnotationIdentifier.is(annotation)?(id=annotation,edit=AnnotatedTextEdit.del(range,annotation)):(this.assertChangeAnnotations(this.changeAnnotations),id=this.changeAnnotations.manage(annotation),edit=AnnotatedTextEdit.del(range,id)),this.edits.push(edit),id!==void 0)return id}add(edit){this.edits.push(edit)}all(){return this.edits}clear(){this.edits.splice(0,this.edits.length)}assertChangeAnnotations(value){if(value===void 0)throw new Error("Text edit change is not configured to manage change annotations.")}}class ChangeAnnotations{constructor(annotations){this._annotations=annotations===void 0?Object.create(null):annotations,this._counter=0,this._size=0}all(){return this._annotations}get size(){return this._size}manage(idOrAnnotation,annotation){let id;if(ChangeAnnotationIdentifier.is(idOrAnnotation)?id=idOrAnnotation:(id=this.nextId(),annotation=idOrAnnotation),this._annotations[id]!==void 0)throw new Error(`Id ${id} is already in use.`);if(annotation===void 0)throw new Error(`No annotation provided for id ${id}`);return this._annotations[id]=annotation,this._size++,id}nextId(){return this._counter++,this._counter.toString()}}class WorkspaceChange{constructor(workspaceEdit){this._textEditChanges=Object.create(null),workspaceEdit!==void 0?(this._workspaceEdit=workspaceEdit,workspaceEdit.documentChanges?(this._changeAnnotations=new ChangeAnnotations(workspaceEdit.changeAnnotations),workspaceEdit.changeAnnotations=this._changeAnnotations.all(),workspaceEdit.documentChanges.forEach(change=>{if(TextDocumentEdit.is(change)){const textEditChange=new TextEditChangeImpl(change.edits,this._changeAnnotations);this._textEditChanges[change.textDocument.uri]=textEditChange}})):workspaceEdit.changes&&Object.keys(workspaceEdit.changes).forEach(key=>{const textEditChange=new TextEditChangeImpl(workspaceEdit.changes[key]);this._textEditChanges[key]=textEditChange})):this._workspaceEdit={}}get edit(){return this.initDocumentChanges(),this._changeAnnotations!==void 0&&(this._changeAnnotations.size===0?this._workspaceEdit.changeAnnotations=void 0:this._workspaceEdit.changeAnnotations=this._changeAnnotations.all()),this._workspaceEdit}getTextEditChange(key){if(OptionalVersionedTextDocumentIdentifier.is(key)){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");const textDocument={uri:key.uri,version:key.version};let result=this._textEditChanges[textDocument.uri];if(!result){const edits=[],textDocumentEdit={textDocument,edits};this._workspaceEdit.documentChanges.push(textDocumentEdit),result=new TextEditChangeImpl(edits,this._changeAnnotations),this._textEditChanges[textDocument.uri]=result}return result}else{if(this.initChanges(),this._workspaceEdit.changes===void 0)throw new Error("Workspace edit is not configured for normal text edit changes.");let result=this._textEditChanges[key];if(!result){let edits=[];this._workspaceEdit.changes[key]=edits,result=new TextEditChangeImpl(edits),this._textEditChanges[key]=result}return result}}initDocumentChanges(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._changeAnnotations=new ChangeAnnotations,this._workspaceEdit.documentChanges=[],this._workspaceEdit.changeAnnotations=this._changeAnnotations.all())}initChanges(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._workspaceEdit.changes=Object.create(null))}createFile(uri,optionsOrAnnotation,options){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let annotation;ChangeAnnotation.is(optionsOrAnnotation)||ChangeAnnotationIdentifier.is(optionsOrAnnotation)?annotation=optionsOrAnnotation:options=optionsOrAnnotation;let operation,id;if(annotation===void 0?operation=CreateFile.create(uri,options):(id=ChangeAnnotationIdentifier.is(annotation)?annotation:this._changeAnnotations.manage(annotation),operation=CreateFile.create(uri,options,id)),this._workspaceEdit.documentChanges.push(operation),id!==void 0)return id}renameFile(oldUri,newUri,optionsOrAnnotation,options){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let annotation;ChangeAnnotation.is(optionsOrAnnotation)||ChangeAnnotationIdentifier.is(optionsOrAnnotation)?annotation=optionsOrAnnotation:options=optionsOrAnnotation;let operation,id;if(annotation===void 0?operation=RenameFile.create(oldUri,newUri,options):(id=ChangeAnnotationIdentifier.is(annotation)?annotation:this._changeAnnotations.manage(annotation),operation=RenameFile.create(oldUri,newUri,options,id)),this._workspaceEdit.documentChanges.push(operation),id!==void 0)return id}deleteFile(uri,optionsOrAnnotation,options){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let annotation;ChangeAnnotation.is(optionsOrAnnotation)||ChangeAnnotationIdentifier.is(optionsOrAnnotation)?annotation=optionsOrAnnotation:options=optionsOrAnnotation;let operation,id;if(annotation===void 0?operation=DeleteFile.create(uri,options):(id=ChangeAnnotationIdentifier.is(annotation)?annotation:this._changeAnnotations.manage(annotation),operation=DeleteFile.create(uri,options,id)),this._workspaceEdit.documentChanges.push(operation),id!==void 0)return id}}var TextDocumentIdentifier;(function(TextDocumentIdentifier2){function create(uri){return{uri}}TextDocumentIdentifier2.create=create;function is2(value){let candidate=value;return Is.defined(candidate)&&Is.string(candidate.uri)}TextDocumentIdentifier2.is=is2})(TextDocumentIdentifier||(TextDocumentIdentifier={}));var VersionedTextDocumentIdentifier;(function(VersionedTextDocumentIdentifier2){function create(uri,version){return{uri,version}}VersionedTextDocumentIdentifier2.create=create;function is2(value){let candidate=value;return Is.defined(candidate)&&Is.string(candidate.uri)&&Is.integer(candidate.version)}VersionedTextDocumentIdentifier2.is=is2})(VersionedTextDocumentIdentifier||(VersionedTextDocumentIdentifier={}));var OptionalVersionedTextDocumentIdentifier;(function(OptionalVersionedTextDocumentIdentifier2){function create(uri,version){return{uri,version}}OptionalVersionedTextDocumentIdentifier2.create=create;function is2(value){let candidate=value;return Is.defined(candidate)&&Is.string(candidate.uri)&&(candidate.version===null||Is.integer(candidate.version))}OptionalVersionedTextDocumentIdentifier2.is=is2})(OptionalVersionedTextDocumentIdentifier||(OptionalVersionedTextDocumentIdentifier={}));var TextDocumentItem;(function(TextDocumentItem2){function create(uri,languageId,version,text){return{uri,languageId,version,text}}TextDocumentItem2.create=create;function is2(value){let candidate=value;return Is.defined(candidate)&&Is.string(candidate.uri)&&Is.string(candidate.languageId)&&Is.integer(candidate.version)&&Is.string(candidate.text)}TextDocumentItem2.is=is2})(TextDocumentItem||(TextDocumentItem={}));var MarkupKind;(function(MarkupKind2){MarkupKind2.PlainText="plaintext",MarkupKind2.Markdown="markdown";function is2(value){const candidate=value;return candidate===MarkupKind2.PlainText||candidate===MarkupKind2.Markdown}MarkupKind2.is=is2})(MarkupKind||(MarkupKind={}));var MarkupContent;(function(MarkupContent2){function is2(value){const candidate=value;return Is.objectLiteral(value)&&MarkupKind.is(candidate.kind)&&Is.string(candidate.value)}MarkupContent2.is=is2})(MarkupContent||(MarkupContent={}));var CompletionItemKind;(function(CompletionItemKind2){CompletionItemKind2.Text=1,CompletionItemKind2.Method=2,CompletionItemKind2.Function=3,CompletionItemKind2.Constructor=4,CompletionItemKind2.Field=5,CompletionItemKind2.Variable=6,CompletionItemKind2.Class=7,CompletionItemKind2.Interface=8,CompletionItemKind2.Module=9,CompletionItemKind2.Property=10,CompletionItemKind2.Unit=11,CompletionItemKind2.Value=12,CompletionItemKind2.Enum=13,CompletionItemKind2.Keyword=14,CompletionItemKind2.Snippet=15,CompletionItemKind2.Color=16,CompletionItemKind2.File=17,CompletionItemKind2.Reference=18,CompletionItemKind2.Folder=19,CompletionItemKind2.EnumMember=20,CompletionItemKind2.Constant=21,CompletionItemKind2.Struct=22,CompletionItemKind2.Event=23,CompletionItemKind2.Operator=24,CompletionItemKind2.TypeParameter=25})(CompletionItemKind||(CompletionItemKind={}));var InsertTextFormat;(function(InsertTextFormat2){InsertTextFormat2.PlainText=1,InsertTextFormat2.Snippet=2})(InsertTextFormat||(InsertTextFormat={}));var CompletionItemTag;(function(CompletionItemTag2){CompletionItemTag2.Deprecated=1})(CompletionItemTag||(CompletionItemTag={}));var InsertReplaceEdit;(function(InsertReplaceEdit2){function create(newText,insert,replace){return{newText,insert,replace}}InsertReplaceEdit2.create=create;function is2(value){const candidate=value;return candidate&&Is.string(candidate.newText)&&Range.is(candidate.insert)&&Range.is(candidate.replace)}InsertReplaceEdit2.is=is2})(InsertReplaceEdit||(InsertReplaceEdit={}));var InsertTextMode;(function(InsertTextMode2){InsertTextMode2.asIs=1,InsertTextMode2.adjustIndentation=2})(InsertTextMode||(InsertTextMode={}));var CompletionItemLabelDetails;(function(CompletionItemLabelDetails2){function is2(value){const candidate=value;return candidate&&(Is.string(candidate.detail)||candidate.detail===void 0)&&(Is.string(candidate.description)||candidate.description===void 0)}CompletionItemLabelDetails2.is=is2})(CompletionItemLabelDetails||(CompletionItemLabelDetails={}));var CompletionItem;(function(CompletionItem2){function create(label){return{label}}CompletionItem2.create=create})(CompletionItem||(CompletionItem={}));var CompletionList;(function(CompletionList2){function create(items,isIncomplete){return{items:items||[],isIncomplete:!!isIncomplete}}CompletionList2.create=create})(CompletionList||(CompletionList={}));var MarkedString;(function(MarkedString2){function fromPlainText(plainText){return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")}MarkedString2.fromPlainText=fromPlainText;function is2(value){const candidate=value;return Is.string(candidate)||Is.objectLiteral(candidate)&&Is.string(candidate.language)&&Is.string(candidate.value)}MarkedString2.is=is2})(MarkedString||(MarkedString={}));var Hover;(function(Hover2){function is2(value){let candidate=value;return!!candidate&&Is.objectLiteral(candidate)&&(MarkupContent.is(candidate.contents)||MarkedString.is(candidate.contents)||Is.typedArray(candidate.contents,MarkedString.is))&&(value.range===void 0||Range.is(value.range))}Hover2.is=is2})(Hover||(Hover={}));var ParameterInformation;(function(ParameterInformation2){function create(label,documentation){return documentation?{label,documentation}:{label}}ParameterInformation2.create=create})(ParameterInformation||(ParameterInformation={}));var SignatureInformation;(function(SignatureInformation2){function create(label,documentation,...parameters){let result={label};return Is.defined(documentation)&&(result.documentation=documentation),Is.defined(parameters)?result.parameters=parameters:result.parameters=[],result}SignatureInformation2.create=create})(SignatureInformation||(SignatureInformation={}));var DocumentHighlightKind;(function(DocumentHighlightKind2){DocumentHighlightKind2.Text=1,DocumentHighlightKind2.Read=2,DocumentHighlightKind2.Write=3})(DocumentHighlightKind||(DocumentHighlightKind={}));var DocumentHighlight;(function(DocumentHighlight2){function create(range,kind){let result={range};return Is.number(kind)&&(result.kind=kind),result}DocumentHighlight2.create=create})(DocumentHighlight||(DocumentHighlight={}));var SymbolKind;(function(SymbolKind2){SymbolKind2.File=1,SymbolKind2.Module=2,SymbolKind2.Namespace=3,SymbolKind2.Package=4,SymbolKind2.Class=5,SymbolKind2.Method=6,SymbolKind2.Property=7,SymbolKind2.Field=8,SymbolKind2.Constructor=9,SymbolKind2.Enum=10,SymbolKind2.Interface=11,SymbolKind2.Function=12,SymbolKind2.Variable=13,SymbolKind2.Constant=14,SymbolKind2.String=15,SymbolKind2.Number=16,SymbolKind2.Boolean=17,SymbolKind2.Array=18,SymbolKind2.Object=19,SymbolKind2.Key=20,SymbolKind2.Null=21,SymbolKind2.EnumMember=22,SymbolKind2.Struct=23,SymbolKind2.Event=24,SymbolKind2.Operator=25,SymbolKind2.TypeParameter=26})(SymbolKind||(SymbolKind={}));var SymbolTag;(function(SymbolTag2){SymbolTag2.Deprecated=1})(SymbolTag||(SymbolTag={}));var SymbolInformation;(function(SymbolInformation2){function create(name,kind,range,uri,containerName){let result={name,kind,location:{uri,range}};return containerName&&(result.containerName=containerName),result}SymbolInformation2.create=create})(SymbolInformation||(SymbolInformation={}));var WorkspaceSymbol;(function(WorkspaceSymbol2){function create(name,kind,uri,range){return range!==void 0?{name,kind,location:{uri,range}}:{name,kind,location:{uri}}}WorkspaceSymbol2.create=create})(WorkspaceSymbol||(WorkspaceSymbol={}));var DocumentSymbol;(function(DocumentSymbol2){function create(name,detail,kind,range,selectionRange,children){let result={name,detail,kind,range,selectionRange};return children!==void 0&&(result.children=children),result}DocumentSymbol2.create=create;function is2(value){let candidate=value;return candidate&&Is.string(candidate.name)&&Is.number(candidate.kind)&&Range.is(candidate.range)&&Range.is(candidate.selectionRange)&&(candidate.detail===void 0||Is.string(candidate.detail))&&(candidate.deprecated===void 0||Is.boolean(candidate.deprecated))&&(candidate.children===void 0||Array.isArray(candidate.children))&&(candidate.tags===void 0||Array.isArray(candidate.tags))}DocumentSymbol2.is=is2})(DocumentSymbol||(DocumentSymbol={}));var CodeActionKind;(function(CodeActionKind2){CodeActionKind2.Empty="",CodeActionKind2.QuickFix="quickfix",CodeActionKind2.Refactor="refactor",CodeActionKind2.RefactorExtract="refactor.extract",CodeActionKind2.RefactorInline="refactor.inline",CodeActionKind2.RefactorRewrite="refactor.rewrite",CodeActionKind2.Source="source",CodeActionKind2.SourceOrganizeImports="source.organizeImports",CodeActionKind2.SourceFixAll="source.fixAll"})(CodeActionKind||(CodeActionKind={}));var CodeActionTriggerKind;(function(CodeActionTriggerKind2){CodeActionTriggerKind2.Invoked=1,CodeActionTriggerKind2.Automatic=2})(CodeActionTriggerKind||(CodeActionTriggerKind={}));var CodeActionContext;(function(CodeActionContext2){function create(diagnostics,only,triggerKind){let result={diagnostics};return only!=null&&(result.only=only),triggerKind!=null&&(result.triggerKind=triggerKind),result}CodeActionContext2.create=create;function is2(value){let candidate=value;return Is.defined(candidate)&&Is.typedArray(candidate.diagnostics,Diagnostic.is)&&(candidate.only===void 0||Is.typedArray(candidate.only,Is.string))&&(candidate.triggerKind===void 0||candidate.triggerKind===CodeActionTriggerKind.Invoked||candidate.triggerKind===CodeActionTriggerKind.Automatic)}CodeActionContext2.is=is2})(CodeActionContext||(CodeActionContext={}));var CodeAction;(function(CodeAction2){function create(title,kindOrCommandOrEdit,kind){let result={title},checkKind=!0;return typeof kindOrCommandOrEdit=="string"?(checkKind=!1,result.kind=kindOrCommandOrEdit):Command.is(kindOrCommandOrEdit)?result.command=kindOrCommandOrEdit:result.edit=kindOrCommandOrEdit,checkKind&&kind!==void 0&&(result.kind=kind),result}CodeAction2.create=create;function is2(value){let candidate=value;return candidate&&Is.string(candidate.title)&&(candidate.diagnostics===void 0||Is.typedArray(candidate.diagnostics,Diagnostic.is))&&(candidate.kind===void 0||Is.string(candidate.kind))&&(candidate.edit!==void 0||candidate.command!==void 0)&&(candidate.command===void 0||Command.is(candidate.command))&&(candidate.isPreferred===void 0||Is.boolean(candidate.isPreferred))&&(candidate.edit===void 0||WorkspaceEdit.is(candidate.edit))}CodeAction2.is=is2})(CodeAction||(CodeAction={}));var CodeLens;(function(CodeLens2){function create(range,data){let result={range};return Is.defined(data)&&(result.data=data),result}CodeLens2.create=create;function is2(value){let candidate=value;return Is.defined(candidate)&&Range.is(candidate.range)&&(Is.undefined(candidate.command)||Command.is(candidate.command))}CodeLens2.is=is2})(CodeLens||(CodeLens={}));var FormattingOptions;(function(FormattingOptions2){function create(tabSize,insertSpaces){return{tabSize,insertSpaces}}FormattingOptions2.create=create;function is2(value){let candidate=value;return Is.defined(candidate)&&Is.uinteger(candidate.tabSize)&&Is.boolean(candidate.insertSpaces)}FormattingOptions2.is=is2})(FormattingOptions||(FormattingOptions={}));var DocumentLink;(function(DocumentLink2){function create(range,target,data){return{range,target,data}}DocumentLink2.create=create;function is2(value){let candidate=value;return Is.defined(candidate)&&Range.is(candidate.range)&&(Is.undefined(candidate.target)||Is.string(candidate.target))}DocumentLink2.is=is2})(DocumentLink||(DocumentLink={}));var SelectionRange;(function(SelectionRange2){function create(range,parent){return{range,parent}}SelectionRange2.create=create;function is2(value){let candidate=value;return Is.objectLiteral(candidate)&&Range.is(candidate.range)&&(candidate.parent===void 0||SelectionRange2.is(candidate.parent))}SelectionRange2.is=is2})(SelectionRange||(SelectionRange={}));var SemanticTokenTypes;(function(SemanticTokenTypes2){SemanticTokenTypes2.namespace="namespace",SemanticTokenTypes2.type="type",SemanticTokenTypes2.class="class",SemanticTokenTypes2.enum="enum",SemanticTokenTypes2.interface="interface",SemanticTokenTypes2.struct="struct",SemanticTokenTypes2.typeParameter="typeParameter",SemanticTokenTypes2.parameter="parameter",SemanticTokenTypes2.variable="variable",SemanticTokenTypes2.property="property",SemanticTokenTypes2.enumMember="enumMember",SemanticTokenTypes2.event="event",SemanticTokenTypes2.function="function",SemanticTokenTypes2.method="method",SemanticTokenTypes2.macro="macro",SemanticTokenTypes2.keyword="keyword",SemanticTokenTypes2.modifier="modifier",SemanticTokenTypes2.comment="comment",SemanticTokenTypes2.string="string",SemanticTokenTypes2.number="number",SemanticTokenTypes2.regexp="regexp",SemanticTokenTypes2.operator="operator",SemanticTokenTypes2.decorator="decorator"})(SemanticTokenTypes||(SemanticTokenTypes={}));var SemanticTokenModifiers;(function(SemanticTokenModifiers2){SemanticTokenModifiers2.declaration="declaration",SemanticTokenModifiers2.definition="definition",SemanticTokenModifiers2.readonly="readonly",SemanticTokenModifiers2.static="static",SemanticTokenModifiers2.deprecated="deprecated",SemanticTokenModifiers2.abstract="abstract",SemanticTokenModifiers2.async="async",SemanticTokenModifiers2.modification="modification",SemanticTokenModifiers2.documentation="documentation",SemanticTokenModifiers2.defaultLibrary="defaultLibrary"})(SemanticTokenModifiers||(SemanticTokenModifiers={}));var SemanticTokens;(function(SemanticTokens2){function is2(value){const candidate=value;return Is.objectLiteral(candidate)&&(candidate.resultId===void 0||typeof candidate.resultId=="string")&&Array.isArray(candidate.data)&&(candidate.data.length===0||typeof candidate.data[0]=="number")}SemanticTokens2.is=is2})(SemanticTokens||(SemanticTokens={}));var InlineValueText;(function(InlineValueText2){function create(range,text){return{range,text}}InlineValueText2.create=create;function is2(value){const candidate=value;return candidate!=null&&Range.is(candidate.range)&&Is.string(candidate.text)}InlineValueText2.is=is2})(InlineValueText||(InlineValueText={}));var InlineValueVariableLookup;(function(InlineValueVariableLookup2){function create(range,variableName,caseSensitiveLookup){return{range,variableName,caseSensitiveLookup}}InlineValueVariableLookup2.create=create;function is2(value){const candidate=value;return candidate!=null&&Range.is(candidate.range)&&Is.boolean(candidate.caseSensitiveLookup)&&(Is.string(candidate.variableName)||candidate.variableName===void 0)}InlineValueVariableLookup2.is=is2})(InlineValueVariableLookup||(InlineValueVariableLookup={}));var InlineValueEvaluatableExpression;(function(InlineValueEvaluatableExpression2){function create(range,expression){return{range,expression}}InlineValueEvaluatableExpression2.create=create;function is2(value){const candidate=value;return candidate!=null&&Range.is(candidate.range)&&(Is.string(candidate.expression)||candidate.expression===void 0)}InlineValueEvaluatableExpression2.is=is2})(InlineValueEvaluatableExpression||(InlineValueEvaluatableExpression={}));var InlineValueContext;(function(InlineValueContext2){function create(frameId,stoppedLocation){return{frameId,stoppedLocation}}InlineValueContext2.create=create;function is2(value){const candidate=value;return Is.defined(candidate)&&Range.is(value.stoppedLocation)}InlineValueContext2.is=is2})(InlineValueContext||(InlineValueContext={}));var InlayHintKind;(function(InlayHintKind2){InlayHintKind2.Type=1,InlayHintKind2.Parameter=2;function is2(value){return value===1||value===2}InlayHintKind2.is=is2})(InlayHintKind||(InlayHintKind={}));var InlayHintLabelPart;(function(InlayHintLabelPart2){function create(value){return{value}}InlayHintLabelPart2.create=create;function is2(value){const candidate=value;return Is.objectLiteral(candidate)&&(candidate.tooltip===void 0||Is.string(candidate.tooltip)||MarkupContent.is(candidate.tooltip))&&(candidate.location===void 0||Location.is(candidate.location))&&(candidate.command===void 0||Command.is(candidate.command))}InlayHintLabelPart2.is=is2})(InlayHintLabelPart||(InlayHintLabelPart={}));var InlayHint;(function(InlayHint2){function create(position,label,kind){const result={position,label};return kind!==void 0&&(result.kind=kind),result}InlayHint2.create=create;function is2(value){const candidate=value;return Is.objectLiteral(candidate)&&Position.is(candidate.position)&&(Is.string(candidate.label)||Is.typedArray(candidate.label,InlayHintLabelPart.is))&&(candidate.kind===void 0||InlayHintKind.is(candidate.kind))&&candidate.textEdits===void 0||Is.typedArray(candidate.textEdits,TextEdit.is)&&(candidate.tooltip===void 0||Is.string(candidate.tooltip)||MarkupContent.is(candidate.tooltip))&&(candidate.paddingLeft===void 0||Is.boolean(candidate.paddingLeft))&&(candidate.paddingRight===void 0||Is.boolean(candidate.paddingRight))}InlayHint2.is=is2})(InlayHint||(InlayHint={}));var StringValue;(function(StringValue2){function createSnippet(value){return{kind:"snippet",value}}StringValue2.createSnippet=createSnippet})(StringValue||(StringValue={}));var InlineCompletionItem;(function(InlineCompletionItem2){function create(insertText,filterText,range,command){return{insertText,filterText,range,command}}InlineCompletionItem2.create=create})(InlineCompletionItem||(InlineCompletionItem={}));var InlineCompletionList;(function(InlineCompletionList2){function create(items){return{items}}InlineCompletionList2.create=create})(InlineCompletionList||(InlineCompletionList={}));var InlineCompletionTriggerKind;(function(InlineCompletionTriggerKind2){InlineCompletionTriggerKind2.Invoked=0,InlineCompletionTriggerKind2.Automatic=1})(InlineCompletionTriggerKind||(InlineCompletionTriggerKind={}));var SelectedCompletionInfo;(function(SelectedCompletionInfo2){function create(range,text){return{range,text}}SelectedCompletionInfo2.create=create})(SelectedCompletionInfo||(SelectedCompletionInfo={}));var InlineCompletionContext;(function(InlineCompletionContext2){function create(triggerKind,selectedCompletionInfo){return{triggerKind,selectedCompletionInfo}}InlineCompletionContext2.create=create})(InlineCompletionContext||(InlineCompletionContext={}));var WorkspaceFolder;(function(WorkspaceFolder2){function is2(value){const candidate=value;return Is.objectLiteral(candidate)&&URI$1.is(candidate.uri)&&Is.string(candidate.name)}WorkspaceFolder2.is=is2})(WorkspaceFolder||(WorkspaceFolder={}));const EOL=[`
117
+ `,`\r
118
+ `,"\r"];var TextDocument$1;(function(TextDocument2){function create(uri,languageId,version,content){return new FullTextDocument$1(uri,languageId,version,content)}TextDocument2.create=create;function is2(value){let candidate=value;return!!(Is.defined(candidate)&&Is.string(candidate.uri)&&(Is.undefined(candidate.languageId)||Is.string(candidate.languageId))&&Is.uinteger(candidate.lineCount)&&Is.func(candidate.getText)&&Is.func(candidate.positionAt)&&Is.func(candidate.offsetAt))}TextDocument2.is=is2;function applyEdits(document,edits){let text=document.getText(),sortedEdits=mergeSort2(edits,(a,b)=>{let diff=a.range.start.line-b.range.start.line;return diff===0?a.range.start.character-b.range.start.character:diff}),lastModifiedOffset=text.length;for(let i=sortedEdits.length-1;i>=0;i--){let e=sortedEdits[i],startOffset=document.offsetAt(e.range.start),endOffset=document.offsetAt(e.range.end);if(endOffset<=lastModifiedOffset)text=text.substring(0,startOffset)+e.newText+text.substring(endOffset,text.length);else throw new Error("Overlapping edit");lastModifiedOffset=startOffset}return text}TextDocument2.applyEdits=applyEdits;function mergeSort2(data,compare){if(data.length<=1)return data;const p=data.length/2|0,left=data.slice(0,p),right=data.slice(p);mergeSort2(left,compare),mergeSort2(right,compare);let leftIdx=0,rightIdx=0,i=0;for(;leftIdx<left.length&&rightIdx<right.length;)compare(left[leftIdx],right[rightIdx])<=0?data[i++]=left[leftIdx++]:data[i++]=right[rightIdx++];for(;leftIdx<left.length;)data[i++]=left[leftIdx++];for(;rightIdx<right.length;)data[i++]=right[rightIdx++];return data}})(TextDocument$1||(TextDocument$1={}));let FullTextDocument$1=class{constructor(uri,languageId,version,content){this._uri=uri,this._languageId=languageId,this._version=version,this._content=content,this._lineOffsets=void 0}get uri(){return this._uri}get languageId(){return this._languageId}get version(){return this._version}getText(range){if(range){let start=this.offsetAt(range.start),end=this.offsetAt(range.end);return this._content.substring(start,end)}return this._content}update(event,version){this._content=event.text,this._version=version,this._lineOffsets=void 0}getLineOffsets(){if(this._lineOffsets===void 0){let lineOffsets=[],text=this._content,isLineStart=!0;for(let i=0;i<text.length;i++){isLineStart&&(lineOffsets.push(i),isLineStart=!1);let ch=text.charAt(i);isLineStart=ch==="\r"||ch===`
119
+ `,ch==="\r"&&i+1<text.length&&text.charAt(i+1)===`
120
+ `&&i++}isLineStart&&text.length>0&&lineOffsets.push(text.length),this._lineOffsets=lineOffsets}return this._lineOffsets}positionAt(offset){offset=Math.max(Math.min(offset,this._content.length),0);let lineOffsets=this.getLineOffsets(),low=0,high=lineOffsets.length;if(high===0)return Position.create(0,offset);for(;low<high;){let mid=Math.floor((low+high)/2);lineOffsets[mid]>offset?high=mid:low=mid+1}let line=low-1;return Position.create(line,offset-lineOffsets[line])}offsetAt(position){let lineOffsets=this.getLineOffsets();if(position.line>=lineOffsets.length)return this._content.length;if(position.line<0)return 0;let lineOffset=lineOffsets[position.line],nextLineOffset=position.line+1<lineOffsets.length?lineOffsets[position.line+1]:this._content.length;return Math.max(Math.min(lineOffset+position.character,nextLineOffset),lineOffset)}get lineCount(){return this.getLineOffsets().length}};var Is;(function(Is2){const toString2=Object.prototype.toString;function defined(value){return typeof value<"u"}Is2.defined=defined;function undefined$1(value){return typeof value>"u"}Is2.undefined=undefined$1;function boolean(value){return value===!0||value===!1}Is2.boolean=boolean;function string(value){return toString2.call(value)==="[object String]"}Is2.string=string;function number(value){return toString2.call(value)==="[object Number]"}Is2.number=number;function numberRange(value,min2,max){return toString2.call(value)==="[object Number]"&&min2<=value&&value<=max}Is2.numberRange=numberRange;function integer2(value){return toString2.call(value)==="[object Number]"&&-2147483648<=value&&value<=2147483647}Is2.integer=integer2;function uinteger2(value){return toString2.call(value)==="[object Number]"&&0<=value&&value<=2147483647}Is2.uinteger=uinteger2;function func(value){return toString2.call(value)==="[object Function]"}Is2.func=func;function objectLiteral(value){return value!==null&&typeof value=="object"}Is2.objectLiteral=objectLiteral;function typedArray(value,check){return Array.isArray(value)&&value.every(check)}Is2.typedArray=typedArray})(Is||(Is={}));const main$2=Object.freeze(Object.defineProperty({__proto__:null,get AnnotatedTextEdit(){return AnnotatedTextEdit},get ChangeAnnotation(){return ChangeAnnotation},get ChangeAnnotationIdentifier(){return ChangeAnnotationIdentifier},get CodeAction(){return CodeAction},get CodeActionContext(){return CodeActionContext},get CodeActionKind(){return CodeActionKind},get CodeActionTriggerKind(){return CodeActionTriggerKind},get CodeDescription(){return CodeDescription},get CodeLens(){return CodeLens},get Color(){return Color},get ColorInformation(){return ColorInformation},get ColorPresentation(){return ColorPresentation},get Command(){return Command},get CompletionItem(){return CompletionItem},get CompletionItemKind(){return CompletionItemKind},get CompletionItemLabelDetails(){return CompletionItemLabelDetails},get CompletionItemTag(){return CompletionItemTag},get CompletionList(){return CompletionList},get CreateFile(){return CreateFile},get DeleteFile(){return DeleteFile},get Diagnostic(){return Diagnostic},get DiagnosticRelatedInformation(){return DiagnosticRelatedInformation},get DiagnosticSeverity(){return DiagnosticSeverity},get DiagnosticTag(){return DiagnosticTag},get DocumentHighlight(){return DocumentHighlight},get DocumentHighlightKind(){return DocumentHighlightKind},get DocumentLink(){return DocumentLink},get DocumentSymbol(){return DocumentSymbol},get DocumentUri(){return DocumentUri},EOL,get FoldingRange(){return FoldingRange},get FoldingRangeKind(){return FoldingRangeKind},get FormattingOptions(){return FormattingOptions},get Hover(){return Hover},get InlayHint(){return InlayHint},get InlayHintKind(){return InlayHintKind},get InlayHintLabelPart(){return InlayHintLabelPart},get InlineCompletionContext(){return InlineCompletionContext},get InlineCompletionItem(){return InlineCompletionItem},get InlineCompletionList(){return InlineCompletionList},get InlineCompletionTriggerKind(){return InlineCompletionTriggerKind},get InlineValueContext(){return InlineValueContext},get InlineValueEvaluatableExpression(){return InlineValueEvaluatableExpression},get InlineValueText(){return InlineValueText},get InlineValueVariableLookup(){return InlineValueVariableLookup},get InsertReplaceEdit(){return InsertReplaceEdit},get InsertTextFormat(){return InsertTextFormat},get InsertTextMode(){return InsertTextMode},get Location(){return Location},get LocationLink(){return LocationLink},get MarkedString(){return MarkedString},get MarkupContent(){return MarkupContent},get MarkupKind(){return MarkupKind},get OptionalVersionedTextDocumentIdentifier(){return OptionalVersionedTextDocumentIdentifier},get ParameterInformation(){return ParameterInformation},get Position(){return Position},get Range(){return Range},get RenameFile(){return RenameFile},get SelectedCompletionInfo(){return SelectedCompletionInfo},get SelectionRange(){return SelectionRange},get SemanticTokenModifiers(){return SemanticTokenModifiers},get SemanticTokenTypes(){return SemanticTokenTypes},get SemanticTokens(){return SemanticTokens},get SignatureInformation(){return SignatureInformation},get StringValue(){return StringValue},get SymbolInformation(){return SymbolInformation},get SymbolKind(){return SymbolKind},get SymbolTag(){return SymbolTag},get TextDocument(){return TextDocument$1},get TextDocumentEdit(){return TextDocumentEdit},get TextDocumentIdentifier(){return TextDocumentIdentifier},get TextDocumentItem(){return TextDocumentItem},get TextEdit(){return TextEdit},get URI(){return URI$1},get VersionedTextDocumentIdentifier(){return VersionedTextDocumentIdentifier},WorkspaceChange,get WorkspaceEdit(){return WorkspaceEdit},get WorkspaceFolder(){return WorkspaceFolder},get WorkspaceSymbol(){return WorkspaceSymbol},get integer(){return integer},get uinteger(){return uinteger}},Symbol.toStringTag,{value:"Module"}));class CstNodeBuilder{constructor(){this.nodeStack=[]}get current(){return this.nodeStack[this.nodeStack.length-1]??this.rootNode}buildRootNode(input){return this.rootNode=new RootCstNodeImpl(input),this.rootNode.root=this.rootNode,this.nodeStack=[this.rootNode],this.rootNode}buildCompositeNode(feature){const compositeNode=new CompositeCstNodeImpl;return compositeNode.grammarSource=feature,compositeNode.root=this.rootNode,this.current.content.push(compositeNode),this.nodeStack.push(compositeNode),compositeNode}buildLeafNode(token,feature){const leafNode=new LeafCstNodeImpl(token.startOffset,token.image.length,tokenToRange(token),token.tokenType,!feature);return leafNode.grammarSource=feature,leafNode.root=this.rootNode,this.current.content.push(leafNode),leafNode}removeNode(node){const parent=node.container;if(parent){const index=parent.content.indexOf(node);index>=0&&parent.content.splice(index,1)}}addHiddenNodes(tokens){const nodes=[];for(const token of tokens){const leafNode=new LeafCstNodeImpl(token.startOffset,token.image.length,tokenToRange(token),token.tokenType,!0);leafNode.root=this.rootNode,nodes.push(leafNode)}let current=this.current,added=!1;if(current.content.length>0){current.content.push(...nodes);return}for(;current.container;){const index=current.container.content.indexOf(current);if(index>0){current.container.content.splice(index,0,...nodes),added=!0;break}current=current.container}added||this.rootNode.content.unshift(...nodes)}construct(item){const current=this.current;typeof item.$type=="string"&&!item.$infixName&&(this.current.astNode=item),item.$cstNode=current;const node=this.nodeStack.pop();(node==null?void 0:node.content.length)===0&&this.removeNode(node)}}class AbstractCstNode{get hidden(){return!1}get astNode(){var _a21,_b;const node=typeof((_a21=this._astNode)==null?void 0:_a21.$type)=="string"?this._astNode:(_b=this.container)==null?void 0:_b.astNode;if(!node)throw new Error("This node has no associated AST element");return node}set astNode(value){this._astNode=value}get text(){return this.root.fullText.substring(this.offset,this.end)}}class LeafCstNodeImpl extends AbstractCstNode{get offset(){return this._offset}get length(){return this._length}get end(){return this._offset+this._length}get hidden(){return this._hidden}get tokenType(){return this._tokenType}get range(){return this._range}constructor(offset,length,range,tokenType,hidden=!1){super(),this._hidden=hidden,this._offset=offset,this._tokenType=tokenType,this._length=length,this._range=range}}class CompositeCstNodeImpl extends AbstractCstNode{constructor(){super(...arguments),this.content=new CstNodeContainer(this)}get offset(){var _a21;return((_a21=this.firstNonHiddenNode)==null?void 0:_a21.offset)??0}get length(){return this.end-this.offset}get end(){var _a21;return((_a21=this.lastNonHiddenNode)==null?void 0:_a21.end)??0}get range(){const firstNode=this.firstNonHiddenNode,lastNode=this.lastNonHiddenNode;if(firstNode&&lastNode){if(this._rangeCache===void 0){const{range:firstRange}=firstNode,{range:lastRange}=lastNode;this._rangeCache={start:firstRange.start,end:lastRange.end.line<firstRange.start.line?firstRange.start:lastRange.end}}return this._rangeCache}else return{start:Position.create(0,0),end:Position.create(0,0)}}get firstNonHiddenNode(){for(const child of this.content)if(!child.hidden)return child;return this.content[0]}get lastNonHiddenNode(){for(let i=this.content.length-1;i>=0;i--){const child=this.content[i];if(!child.hidden)return child}return this.content[this.content.length-1]}}class CstNodeContainer extends Array{constructor(parent){super(),this.parent=parent,Object.setPrototypeOf(this,CstNodeContainer.prototype)}push(...items){return this.addParents(items),super.push(...items)}unshift(...items){return this.addParents(items),super.unshift(...items)}splice(start,count,...items){return this.addParents(items),super.splice(start,count,...items)}addParents(items){for(const item of items)item.container=this.parent}}class RootCstNodeImpl extends CompositeCstNodeImpl{get text(){return this._text.substring(this.offset,this.end)}get fullText(){return this._text}constructor(input){super(),this._text="",this._text=input??""}}const DatatypeSymbol=Symbol("Datatype");function isDataTypeNode(node){return node.$type===DatatypeSymbol}const ruleSuffix="​",withRuleSuffix=name=>name.endsWith(ruleSuffix)?name:name+ruleSuffix;class AbstractLangiumParser{constructor(services){var _a21;this._unorderedGroups=new Map,this.allRules=new Map,this.lexer=services.parser.Lexer;const tokens=this.lexer.definition,production=services.LanguageMetaData.mode==="production";(_a21=services.shared.profilers.LangiumProfiler)!=null&&_a21.isActive("parsing")?this.wrapper=new ProfilerWrapper(tokens,{...services.parser.ParserConfig,skipValidations:production,errorMessageProvider:services.parser.ParserErrorMessageProvider},services.shared.profilers.LangiumProfiler.createTask("parsing",services.LanguageMetaData.languageId)):this.wrapper=new ChevrotainWrapper(tokens,{...services.parser.ParserConfig,skipValidations:production,errorMessageProvider:services.parser.ParserErrorMessageProvider})}alternatives(idx,choices){this.wrapper.wrapOr(idx,choices)}optional(idx,callback){this.wrapper.wrapOption(idx,callback)}many(idx,callback){this.wrapper.wrapMany(idx,callback)}atLeastOne(idx,callback){this.wrapper.wrapAtLeastOne(idx,callback)}getRule(name){return this.allRules.get(name)}isRecording(){return this.wrapper.IS_RECORDING}get unorderedGroups(){return this._unorderedGroups}getRuleStack(){return this.wrapper.RULE_STACK}finalize(){this.wrapper.wrapSelfAnalysis()}}class LangiumParser extends AbstractLangiumParser{get current(){return this.stack[this.stack.length-1]}constructor(services){super(services),this.nodeBuilder=new CstNodeBuilder,this.stack=[],this.assignmentMap=new Map,this.operatorPrecedence=new Map,this.linker=services.references.Linker,this.converter=services.parser.ValueConverter,this.astReflection=services.shared.AstReflection}rule(rule,impl){const type=this.computeRuleType(rule);let infixName;isInfixRule(rule)&&(infixName=rule.name,this.registerPrecedenceMap(rule));const ruleMethod=this.wrapper.DEFINE_RULE(withRuleSuffix(rule.name),this.startImplementation(type,infixName,impl).bind(this));return this.allRules.set(rule.name,ruleMethod),isParserRule(rule)&&rule.entry&&(this.mainRule=ruleMethod),ruleMethod}registerPrecedenceMap(rule){const name=rule.name,map2=new Map;for(let i=0;i<rule.operators.precedences.length;i++){const precedence=rule.operators.precedences[i];for(const keyword of precedence.operators)map2.set(keyword.value,{precedence:i,rightAssoc:precedence.associativity==="right"})}this.operatorPrecedence.set(name,map2)}computeRuleType(rule){return isInfixRule(rule)?getTypeName(rule):rule.fragment?void 0:isDataTypeRule(rule)?DatatypeSymbol:getTypeName(rule)}parse(input,options={}){this.nodeBuilder.buildRootNode(input);const lexerResult=this.lexerResult=this.lexer.tokenize(input);this.wrapper.input=lexerResult.tokens;const ruleMethod=options.rule?this.allRules.get(options.rule):this.mainRule;if(!ruleMethod)throw new Error(options.rule?`No rule found with name '${options.rule}'`:"No main rule available.");const result=this.doParse(ruleMethod);return this.nodeBuilder.addHiddenNodes(lexerResult.hidden),this.unorderedGroups.clear(),this.lexerResult=void 0,linkContentToContainer(result,{deep:!0}),{value:result,lexerErrors:lexerResult.errors,lexerReport:lexerResult.report,parserErrors:this.wrapper.errors}}doParse(rule){let result=this.wrapper.rule(rule);if(this.stack.length>0&&(result=this.construct()),result===void 0)throw new Error("No result from parser");if(this.stack.length>0)throw new Error("Parser stack is not empty after parsing");return result}startImplementation($type,infixName,implementation){return args=>{const createNode=!this.isRecording()&&$type!==void 0;if(createNode){const node={$type};this.stack.push(node),$type===DatatypeSymbol?node.value="":infixName!==void 0&&(node.$infixName=infixName)}return implementation(args),createNode?this.construct():void 0}}extractHiddenTokens(token){const hiddenTokens=this.lexerResult.hidden;if(!hiddenTokens.length)return[];const offset=token.startOffset;for(let i=0;i<hiddenTokens.length;i++)if(hiddenTokens[i].startOffset>offset)return hiddenTokens.splice(0,i);return hiddenTokens.splice(0,hiddenTokens.length)}consume(idx,tokenType,feature){const token=this.wrapper.wrapConsume(idx,tokenType);if(!this.isRecording()&&this.isValidToken(token)){const hiddenTokens=this.extractHiddenTokens(token);this.nodeBuilder.addHiddenNodes(hiddenTokens);const leafNode=this.nodeBuilder.buildLeafNode(token,feature),{assignment,crossRef}=this.getAssignment(feature),current=this.current;if(assignment){const convertedValue=isKeyword(feature)?token.image:this.converter.convert(token.image,leafNode);this.assign(assignment.operator,assignment.feature,convertedValue,leafNode,crossRef)}else if(isDataTypeNode(current)){let text=token.image;isKeyword(feature)||(text=this.converter.convert(text,leafNode).toString()),current.value+=text}}}isValidToken(token){return!token.isInsertedInRecovery&&!isNaN(token.startOffset)&&typeof token.endOffset=="number"&&!isNaN(token.endOffset)}subrule(idx,rule,fragment,feature,args){let cstNode;!this.isRecording()&&!fragment&&(cstNode=this.nodeBuilder.buildCompositeNode(feature));let result;try{result=this.wrapper.wrapSubrule(idx,rule,args)}finally{this.isRecording()||(result===void 0&&!fragment&&(result=this.construct()),result!==void 0&&cstNode&&cstNode.length>0&&this.performSubruleAssignment(result,feature,cstNode))}}performSubruleAssignment(result,feature,cstNode){const{assignment,crossRef}=this.getAssignment(feature);if(assignment)this.assign(assignment.operator,assignment.feature,result,cstNode,crossRef);else if(!assignment){const current=this.current;if(isDataTypeNode(current))current.value+=result.toString();else if(typeof result=="object"&&result){const newItem=this.assignWithoutOverride(result,current);this.stack.pop(),this.stack.push(newItem)}}}action($type,action){if(!this.isRecording()){let last=this.current;if(action.feature&&action.operator){last=this.construct(),this.nodeBuilder.removeNode(last.$cstNode),this.nodeBuilder.buildCompositeNode(action).content.push(last.$cstNode);const newItem={$type};this.stack.push(newItem),this.assign(action.operator,action.feature,last,last.$cstNode)}else last.$type=$type}}construct(){if(this.isRecording())return;const obj=this.stack.pop();return this.nodeBuilder.construct(obj),"$infixName"in obj?this.constructInfix(obj,this.operatorPrecedence.get(obj.$infixName)):isDataTypeNode(obj)?this.converter.convert(obj.value,obj.$cstNode):(assignMandatoryProperties(this.astReflection,obj),obj)}constructInfix(obj,precedence){const parts=obj.parts;if(!Array.isArray(parts)||parts.length===0)return;const operators=obj.operators;if(!Array.isArray(operators)||parts.length<2)return parts[0];let lowestPrecedenceIdx=0,lowestPrecedenceValue=-1;for(let i=0;i<operators.length;i++){const operator=operators[i],opPrecedence=precedence.get(operator)??{precedence:1/0,rightAssoc:!1};opPrecedence.precedence>lowestPrecedenceValue?(lowestPrecedenceValue=opPrecedence.precedence,lowestPrecedenceIdx=i):opPrecedence.precedence===lowestPrecedenceValue&&(opPrecedence.rightAssoc||(lowestPrecedenceIdx=i))}const leftOperators=operators.slice(0,lowestPrecedenceIdx),rightOperators=operators.slice(lowestPrecedenceIdx+1),leftParts=parts.slice(0,lowestPrecedenceIdx+1),rightParts=parts.slice(lowestPrecedenceIdx+1),leftInfix={$infixName:obj.$infixName,$type:obj.$type,$cstNode:obj.$cstNode,parts:leftParts,operators:leftOperators},rightInfix={$infixName:obj.$infixName,$type:obj.$type,$cstNode:obj.$cstNode,parts:rightParts,operators:rightOperators},leftTree=this.constructInfix(leftInfix,precedence),rightTree=this.constructInfix(rightInfix,precedence);return{$type:obj.$type,$cstNode:obj.$cstNode,left:leftTree,operator:operators[lowestPrecedenceIdx],right:rightTree}}getAssignment(feature){if(!this.assignmentMap.has(feature)){const assignment=getContainerOfType(feature,isAssignment);this.assignmentMap.set(feature,{assignment,crossRef:assignment&&isCrossReference(assignment.terminal)?assignment.terminal.isMulti?"multi":"single":void 0})}return this.assignmentMap.get(feature)}assign(operator,feature,value,cstNode,crossRef){const obj=this.current;let item;switch(crossRef==="single"&&typeof value=="string"?item=this.linker.buildReference(obj,feature,cstNode,value):crossRef==="multi"&&typeof value=="string"?item=this.linker.buildMultiReference(obj,feature,cstNode,value):item=value,operator){case"=":{obj[feature]=item;break}case"?=":{obj[feature]=!0;break}case"+=":Array.isArray(obj[feature])||(obj[feature]=[]),obj[feature].push(item)}}assignWithoutOverride(target,source){for(const[name,existingValue]of Object.entries(source)){const newValue=target[name];newValue===void 0?target[name]=existingValue:Array.isArray(newValue)&&Array.isArray(existingValue)&&(existingValue.push(...newValue),target[name]=existingValue)}const targetCstNode=target.$cstNode;return targetCstNode&&(targetCstNode.astNode=void 0,target.$cstNode=void 0),target}get definitionErrors(){return this.wrapper.definitionErrors}}class AbstractParserErrorMessageProvider{buildMismatchTokenMessage(options){return defaultParserErrorProvider.buildMismatchTokenMessage(options)}buildNotAllInputParsedMessage(options){return defaultParserErrorProvider.buildNotAllInputParsedMessage(options)}buildNoViableAltMessage(options){return defaultParserErrorProvider.buildNoViableAltMessage(options)}buildEarlyExitMessage(options){return defaultParserErrorProvider.buildEarlyExitMessage(options)}}class LangiumParserErrorMessageProvider extends AbstractParserErrorMessageProvider{buildMismatchTokenMessage({expected,actual}){return`Expecting ${expected.LABEL?"`"+expected.LABEL+"`":expected.name.endsWith(":KW")?`keyword '${expected.name.substring(0,expected.name.length-3)}'`:`token of type '${expected.name}'`} but found \`${actual.image}\`.`}buildNotAllInputParsedMessage({firstRedundant}){return`Expecting end of file but found \`${firstRedundant.image}\`.`}}class LangiumCompletionParser extends AbstractLangiumParser{constructor(){super(...arguments),this.tokens=[],this.elementStack=[],this.lastElementStack=[],this.nextTokenIndex=0,this.stackSize=0}action(){}construct(){}parse(input){this.resetState();const tokens=this.lexer.tokenize(input,{mode:"partial"});return this.tokens=tokens.tokens,this.wrapper.input=[...this.tokens],this.mainRule.call(this.wrapper,{}),this.unorderedGroups.clear(),{tokens:this.tokens,elementStack:[...this.lastElementStack],tokenIndex:this.nextTokenIndex}}rule(rule,impl){const ruleMethod=this.wrapper.DEFINE_RULE(withRuleSuffix(rule.name),this.startImplementation(impl).bind(this));return this.allRules.set(rule.name,ruleMethod),rule.entry&&(this.mainRule=ruleMethod),ruleMethod}resetState(){this.elementStack=[],this.lastElementStack=[],this.nextTokenIndex=0,this.stackSize=0}startImplementation(implementation){return args=>{const size=this.keepStackSize();try{implementation(args)}finally{this.resetStackSize(size)}}}removeUnexpectedElements(){this.elementStack.splice(this.stackSize)}keepStackSize(){const size=this.elementStack.length;return this.stackSize=size,size}resetStackSize(size){this.removeUnexpectedElements(),this.stackSize=size}consume(idx,tokenType,feature){this.wrapper.wrapConsume(idx,tokenType),this.isRecording()||(this.lastElementStack=[...this.elementStack,feature],this.nextTokenIndex=this.currIdx+1)}subrule(idx,rule,fragment,feature,args){this.before(feature),this.wrapper.wrapSubrule(idx,rule,args),this.after(feature)}before(element){this.isRecording()||this.elementStack.push(element)}after(element){if(!this.isRecording()){const index=this.elementStack.lastIndexOf(element);index>=0&&this.elementStack.splice(index)}}get currIdx(){return this.wrapper.currIdx}}const defaultConfig={recoveryEnabled:!0,nodeLocationTracking:"full",skipValidations:!0,errorMessageProvider:new LangiumParserErrorMessageProvider};class ChevrotainWrapper extends EmbeddedActionsParser{constructor(tokens,config){const useDefaultLookahead=config&&"maxLookahead"in config;super(tokens,{...defaultConfig,lookaheadStrategy:useDefaultLookahead?new LLkLookaheadStrategy({maxLookahead:config.maxLookahead}):new LLStarLookaheadStrategy({logging:config.skipValidations?()=>{}:void 0}),...config})}get IS_RECORDING(){return this.RECORDING_PHASE}DEFINE_RULE(name,impl,config){return this.RULE(name,impl,config)}wrapSelfAnalysis(){this.performSelfAnalysis()}wrapConsume(idx,tokenType){return this.consume(idx,tokenType,void 0)}wrapSubrule(idx,rule,args){return this.subrule(idx,rule,{ARGS:[args]})}wrapOr(idx,choices){this.or(idx,choices)}wrapOption(idx,callback){this.option(idx,callback)}wrapMany(idx,callback){this.many(idx,callback)}wrapAtLeastOne(idx,callback){this.atLeastOne(idx,callback)}rule(rule){return rule.call(this,{})}}class ProfilerWrapper extends ChevrotainWrapper{constructor(tokens,config,task){super(tokens,config),this.task=task}rule(rule){this.task.start(),this.task.startSubTask(this.ruleName(rule));try{return super.rule(rule)}finally{this.task.stopSubTask(this.ruleName(rule)),this.task.stop()}}ruleName(rule){return rule.ruleName}subrule(idx,ruleToCall,options){this.task.startSubTask(this.ruleName(ruleToCall));try{return super.subrule(idx,ruleToCall,options)}finally{this.task.stopSubTask(this.ruleName(ruleToCall))}}}function createParser(grammar,parser,tokens){return buildRules({parser,tokens,ruleNames:new Map},grammar),parser}function buildRules(parserContext,grammar){const reachable=getAllReachableRules(grammar,!1),parserRules=stream(grammar.rules).filter(isParserRule).filter(rule=>reachable.has(rule));for(const rule of parserRules){const ctx={...parserContext,consume:1,optional:1,subrule:1,many:1,or:1};parserContext.parser.rule(rule,buildElement(ctx,rule.definition))}const infixRules=stream(grammar.rules).filter(isInfixRule).filter(rule=>reachable.has(rule));for(const rule of infixRules)parserContext.parser.rule(rule,buildInfixRule(parserContext,rule))}function buildInfixRule(ctx,rule){const expressionRule=rule.call.rule.ref;if(!expressionRule)throw new Error("Could not resolve reference to infix operator rule: "+rule.call.rule.$refText);if(isTerminalRule(expressionRule))throw new Error("Cannot use terminal rule in infix expression");const allKeywords=rule.operators.precedences.flatMap(e=>e.operators),outerGroup={$type:"Group",elements:[]},part1Assignment={$container:outerGroup,$type:"Assignment",feature:"parts",operator:"+=",terminal:rule.call},innerGroup={$container:outerGroup,$type:"Group",elements:[],cardinality:"*"};outerGroup.elements.push(part1Assignment,innerGroup);const operatorAssignment={$container:innerGroup,$type:"Assignment",feature:"operators",operator:"+=",terminal:{$type:"Alternatives",elements:allKeywords}},part2Assignment={...part1Assignment,$container:innerGroup};innerGroup.elements.push(operatorAssignment,part2Assignment);const orAlts=allKeywords.map(e=>ctx.tokens[e.value]).map((token,index)=>({ALT:()=>ctx.parser.consume(index,token,operatorAssignment)}));let subrule;return args=>{subrule??(subrule=getRule(ctx,expressionRule)),ctx.parser.subrule(0,subrule,!1,part1Assignment,args),ctx.parser.many(0,{DEF:()=>{ctx.parser.alternatives(0,orAlts),ctx.parser.subrule(1,subrule,!1,part2Assignment,args)}})}}function buildElement(ctx,element,ignoreGuard=!1){let method;if(isKeyword(element))method=buildKeyword(ctx,element);else if(isAction(element))method=buildAction(ctx,element);else if(isAssignment(element))method=buildElement(ctx,element.terminal);else if(isCrossReference(element))method=buildCrossReference(ctx,element);else if(isRuleCall(element))method=buildRuleCall(ctx,element);else if(isAlternatives(element))method=buildAlternatives(ctx,element);else if(isUnorderedGroup(element))method=buildUnorderedGroup(ctx,element);else if(isGroup(element))method=buildGroup(ctx,element);else if(isEndOfFile(element)){const idx=ctx.consume++;method=()=>ctx.parser.consume(idx,EOF,element)}else throw new ErrorWithLocation(element.$cstNode,`Unexpected element type: ${element.$type}`);return wrap(ctx,ignoreGuard?void 0:getGuardCondition(element),method,element.cardinality)}function buildAction(ctx,action){const actionType=getTypeName(action);return()=>ctx.parser.action(actionType,action)}function buildRuleCall(ctx,ruleCall){const rule=ruleCall.rule.ref;if(isAbstractParserRule(rule)){const idx=ctx.subrule++,fragment=isParserRule(rule)&&rule.fragment,predicate=ruleCall.arguments.length>0?buildRuleCallPredicate(rule,ruleCall.arguments):()=>({});let subrule;return args=>{subrule??(subrule=getRule(ctx,rule)),ctx.parser.subrule(idx,subrule,fragment,ruleCall,predicate(args))}}else if(isTerminalRule(rule)){const idx=ctx.consume++,method=getToken(ctx,rule.name);return()=>ctx.parser.consume(idx,method,ruleCall)}else if(rule)assertUnreachable();else throw new ErrorWithLocation(ruleCall.$cstNode,`Undefined rule: ${ruleCall.rule.$refText}`)}function buildRuleCallPredicate(rule,namedArgs){if(namedArgs.some(arg=>arg.calledByName)){const namedPredicates=namedArgs.map(arg=>{var _a21,_b;return{parameterName:(_b=(_a21=arg.parameter)==null?void 0:_a21.ref)==null?void 0:_b.name,predicate:buildPredicate(arg.value)}});return args=>{const ruleArgs={};for(const{parameterName,predicate}of namedPredicates)parameterName&&(ruleArgs[parameterName]=predicate(args));return ruleArgs}}else{const predicates=namedArgs.map(arg=>buildPredicate(arg.value));return args=>{const ruleArgs={};for(let i=0;i<predicates.length;i++)if(i<rule.parameters.length){const parameterName=rule.parameters[i].name,predicate=predicates[i];ruleArgs[parameterName]=predicate(args)}return ruleArgs}}}function buildPredicate(condition){if(isDisjunction(condition)){const left=buildPredicate(condition.left),right=buildPredicate(condition.right);return args=>left(args)||right(args)}else if(isConjunction(condition)){const left=buildPredicate(condition.left),right=buildPredicate(condition.right);return args=>left(args)&&right(args)}else if(isNegation(condition)){const value=buildPredicate(condition.value);return args=>!value(args)}else if(isParameterReference(condition)){const name=condition.parameter.ref.name;return args=>args!==void 0&&args[name]===!0}else if(isBooleanLiteral(condition)){const value=!!condition.true;return()=>value}assertUnreachable()}function buildAlternatives(ctx,alternatives){if(alternatives.elements.length===1)return buildElement(ctx,alternatives.elements[0]);{const methods=[];for(const element of alternatives.elements){const predicatedMethod={ALT:buildElement(ctx,element,!0)},guard=getGuardCondition(element);guard&&(predicatedMethod.GATE=buildPredicate(guard)),methods.push(predicatedMethod)}const idx=ctx.or++;return args=>ctx.parser.alternatives(idx,methods.map(method=>{const alt={ALT:()=>method.ALT(args)},gate=method.GATE;return gate&&(alt.GATE=()=>gate(args)),alt}))}}function buildUnorderedGroup(ctx,group){if(group.elements.length===1)return buildElement(ctx,group.elements[0]);const methods=[];for(const element of group.elements){const predicatedMethod={ALT:buildElement(ctx,element,!0)},guard=getGuardCondition(element);guard&&(predicatedMethod.GATE=buildPredicate(guard)),methods.push(predicatedMethod)}const orIdx=ctx.or++,idFunc=(groupIdx,lParser)=>{const stackId=lParser.getRuleStack().join("-");return`uGroup_${groupIdx}_${stackId}`},alternatives=args=>ctx.parser.alternatives(orIdx,methods.map((method,idx)=>{const alt={ALT:()=>!0},parser=ctx.parser;alt.ALT=()=>{if(method.ALT(args),!parser.isRecording()){const key=idFunc(orIdx,parser);parser.unorderedGroups.get(key)||parser.unorderedGroups.set(key,[]);const groupState=parser.unorderedGroups.get(key);typeof(groupState==null?void 0:groupState[idx])>"u"&&(groupState[idx]=!0)}};const gate=method.GATE;return gate?alt.GATE=()=>gate(args):alt.GATE=()=>{const trackedAlternatives=parser.unorderedGroups.get(idFunc(orIdx,parser));return!(trackedAlternatives!=null&&trackedAlternatives[idx])},alt})),wrapped=wrap(ctx,getGuardCondition(group),alternatives,"*");return args=>{wrapped(args),ctx.parser.isRecording()||ctx.parser.unorderedGroups.delete(idFunc(orIdx,ctx.parser))}}function buildGroup(ctx,group){const methods=group.elements.map(e=>buildElement(ctx,e));return args=>methods.forEach(method=>method(args))}function getGuardCondition(element){if(isGroup(element))return element.guardCondition}function buildCrossReference(ctx,crossRef,terminal=crossRef.terminal){if(terminal)if(isRuleCall(terminal)&&isParserRule(terminal.rule.ref)){const rule=terminal.rule.ref,idx=ctx.subrule++;let subrule;return args=>{subrule??(subrule=getRule(ctx,rule)),ctx.parser.subrule(idx,subrule,!1,crossRef,args)}}else if(isRuleCall(terminal)&&isTerminalRule(terminal.rule.ref)){const idx=ctx.consume++,terminalRule=getToken(ctx,terminal.rule.ref.name);return()=>ctx.parser.consume(idx,terminalRule,crossRef)}else if(isKeyword(terminal)){const idx=ctx.consume++,keyword=getToken(ctx,terminal.value);return()=>ctx.parser.consume(idx,keyword,crossRef)}else throw new Error("Could not build cross reference parser");else{if(!crossRef.type.ref)throw new Error("Could not resolve reference to type: "+crossRef.type.$refText);const assignment=findNameAssignment(crossRef.type.ref),assignTerminal=assignment==null?void 0:assignment.terminal;if(!assignTerminal)throw new Error("Could not find name assignment for type: "+getTypeName(crossRef.type.ref));return buildCrossReference(ctx,crossRef,assignTerminal)}}function buildKeyword(ctx,keyword){const idx=ctx.consume++,token=ctx.tokens[keyword.value];if(!token)throw new Error("Could not find token for keyword: "+keyword.value);return()=>ctx.parser.consume(idx,token,keyword)}function wrap(ctx,guard,method,cardinality){const gate=guard&&buildPredicate(guard);if(!cardinality)if(gate){const idx=ctx.or++;return args=>ctx.parser.alternatives(idx,[{ALT:()=>method(args),GATE:()=>gate(args)},{ALT:EMPTY_ALT(),GATE:()=>!gate(args)}])}else return method;if(cardinality==="*"){const idx=ctx.many++;return args=>ctx.parser.many(idx,{DEF:()=>method(args),GATE:gate?()=>gate(args):void 0})}else if(cardinality==="+"){const idx=ctx.many++;if(gate){const orIdx=ctx.or++;return args=>ctx.parser.alternatives(orIdx,[{ALT:()=>ctx.parser.atLeastOne(idx,{DEF:()=>method(args)}),GATE:()=>gate(args)},{ALT:EMPTY_ALT(),GATE:()=>!gate(args)}])}else return args=>ctx.parser.atLeastOne(idx,{DEF:()=>method(args)})}else if(cardinality==="?"){const idx=ctx.optional++;return args=>ctx.parser.optional(idx,{DEF:()=>method(args),GATE:gate?()=>gate(args):void 0})}else assertUnreachable()}function getRule(ctx,element){const name=getRuleName(ctx,element),rule=ctx.parser.getRule(name);if(!rule)throw new Error(`Rule "${name}" not found."`);return rule}function getRuleName(ctx,element){if(isAbstractParserRule(element))return element.name;if(ctx.ruleNames.has(element))return ctx.ruleNames.get(element);{let item=element,parent=item.$container,ruleName=element.$type;for(;!isParserRule(parent);)(isGroup(parent)||isAlternatives(parent)||isUnorderedGroup(parent))&&(ruleName=parent.elements.indexOf(item).toString()+":"+ruleName),item=parent,parent=parent.$container;return ruleName=parent.name+":"+ruleName,ctx.ruleNames.set(element,ruleName),ruleName}}function getToken(ctx,name){const token=ctx.tokens[name];if(!token)throw new Error(`Token "${name}" not found."`);return token}function createCompletionParser(services){const grammar=services.Grammar,lexer=services.parser.Lexer,parser=new LangiumCompletionParser(services);return createParser(grammar,parser,lexer.definition),parser.finalize(),parser}function createLangiumParser(services){const parser=prepareLangiumParser(services);return parser.finalize(),parser}function prepareLangiumParser(services){const grammar=services.Grammar,lexer=services.parser.Lexer,parser=new LangiumParser(services);return createParser(grammar,parser,lexer.definition)}class DefaultTokenBuilder{constructor(){this.diagnostics=[]}buildTokens(grammar,options){const reachableRules=stream(getAllReachableRules(grammar,!1)),terminalTokens=this.buildTerminalTokens(reachableRules),tokens=this.buildKeywordTokens(reachableRules,terminalTokens,options);return tokens.push(...terminalTokens),tokens}flushLexingReport(text){return{diagnostics:this.popDiagnostics()}}popDiagnostics(){const diagnostics=[...this.diagnostics];return this.diagnostics=[],diagnostics}buildTerminalTokens(rules){return rules.filter(isTerminalRule).filter(e=>!e.fragment).map(terminal=>this.buildTerminalToken(terminal)).toArray()}buildTerminalToken(terminal){const regex=terminalRegex(terminal),pattern=this.requiresCustomPattern(regex)?this.regexPatternFunction(regex):regex,tokenType={name:terminal.name,PATTERN:pattern};return typeof pattern=="function"&&(tokenType.LINE_BREAKS=!0),terminal.hidden&&(tokenType.GROUP=isWhitespace(regex)?Lexer.SKIPPED:"hidden"),tokenType}requiresCustomPattern(regex){return!!(regex.flags.includes("u")||regex.flags.includes("s"))}regexPatternFunction(regex){const stickyRegex=new RegExp(regex,regex.flags+"y");return(text,offset)=>(stickyRegex.lastIndex=offset,stickyRegex.exec(text))}buildKeywordTokens(rules,terminalTokens,options){return rules.filter(isAbstractParserRule).flatMap(rule=>streamAllContents(rule).filter(isKeyword)).distinct(e=>e.value).toArray().sort((a,b)=>b.value.length-a.value.length).map(keyword=>this.buildKeywordToken(keyword,terminalTokens,!!(options!=null&&options.caseInsensitive)))}buildKeywordToken(keyword,terminalTokens,caseInsensitive){const keywordPattern=this.buildKeywordPattern(keyword,caseInsensitive),tokenType={name:keyword.value,PATTERN:keywordPattern,LONGER_ALT:this.findLongerAlt(keyword,terminalTokens)};return typeof keywordPattern=="function"&&(tokenType.LINE_BREAKS=!0),tokenType}buildKeywordPattern(keyword,caseInsensitive){return caseInsensitive?new RegExp(escapeRegExp(keyword.value),"i"):keyword.value}findLongerAlt(keyword,terminalTokens){return terminalTokens.reduce((longerAlts,token)=>{const pattern=token==null?void 0:token.PATTERN;return pattern!=null&&pattern.source&&partialMatches("^"+pattern.source+"$",keyword.value)&&longerAlts.push(token),longerAlts},[])}}class DefaultValueConverter{convert(input,cstNode){let feature=cstNode.grammarSource;if(isCrossReference(feature)&&(feature=getCrossReferenceTerminal(feature)),isRuleCall(feature)){const rule=feature.rule.ref;if(!rule)throw new Error("This cst node was not parsed by a rule.");return this.runConverter(rule,input,cstNode)}return input}runConverter(rule,input,cstNode){var _a21;switch(rule.name.toUpperCase()){case"INT":return ValueConverter.convertInt(input);case"STRING":return ValueConverter.convertString(input);case"ID":return ValueConverter.convertID(input)}switch((_a21=getRuleType(rule))==null?void 0:_a21.toLowerCase()){case"number":return ValueConverter.convertNumber(input);case"boolean":return ValueConverter.convertBoolean(input);case"bigint":return ValueConverter.convertBigint(input);case"date":return ValueConverter.convertDate(input);default:return input}}}var ValueConverter;(function(ValueConverter2){function convertString(input){let result="";for(let i=1;i<input.length-1;i++){const c=input.charAt(i);if(c==="\\"){const c1=input.charAt(++i);result+=convertEscapeCharacter(c1)}else result+=c}return result}ValueConverter2.convertString=convertString;function convertEscapeCharacter(char){switch(char){case"b":return"\b";case"f":return"\f";case"n":return`
121
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"0":return"\0";default:return char}}function convertID(input){return input.charAt(0)==="^"?input.substring(1):input}ValueConverter2.convertID=convertID;function convertInt(input){return parseInt(input)}ValueConverter2.convertInt=convertInt;function convertBigint(input){return BigInt(input)}ValueConverter2.convertBigint=convertBigint;function convertDate(input){return new Date(input)}ValueConverter2.convertDate=convertDate;function convertNumber(input){return Number(input)}ValueConverter2.convertNumber=convertNumber;function convertBoolean(input){return input.toLowerCase()==="true"}ValueConverter2.convertBoolean=convertBoolean})(ValueConverter||(ValueConverter={}));var cancellation={},ral={},hasRequiredRal;function requireRal(){if(hasRequiredRal)return ral;hasRequiredRal=1,Object.defineProperty(ral,"__esModule",{value:!0});let _ral;function RAL(){if(_ral===void 0)throw new Error("No runtime abstraction layer installed");return _ral}return(function(RAL2){function install(ral2){if(ral2===void 0)throw new Error("No runtime abstraction layer provided");_ral=ral2}RAL2.install=install})(RAL||(RAL={})),ral.default=RAL,ral}var is$1={},hasRequiredIs$1;function requireIs$1(){if(hasRequiredIs$1)return is$1;hasRequiredIs$1=1,Object.defineProperty(is$1,"__esModule",{value:!0}),is$1.stringArray=is$1.array=is$1.func=is$1.error=is$1.number=is$1.string=is$1.boolean=void 0;function boolean(value){return value===!0||value===!1}is$1.boolean=boolean;function string(value){return typeof value=="string"||value instanceof String}is$1.string=string;function number(value){return typeof value=="number"||value instanceof Number}is$1.number=number;function error(value){return value instanceof Error}is$1.error=error;function func(value){return typeof value=="function"}is$1.func=func;function array(value){return Array.isArray(value)}is$1.array=array;function stringArray(value){return array(value)&&value.every(elem=>string(elem))}return is$1.stringArray=stringArray,is$1}var events={},hasRequiredEvents;function requireEvents(){if(hasRequiredEvents)return events;hasRequiredEvents=1,Object.defineProperty(events,"__esModule",{value:!0}),events.Emitter=events.Event=void 0;const ral_1=requireRal();var Event;(function(Event2){const _disposable={dispose(){}};Event2.None=function(){return _disposable}})(Event||(events.Event=Event={}));class CallbackList{add(callback,context=null,bucket){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(callback),this._contexts.push(context),Array.isArray(bucket)&&bucket.push({dispose:()=>this.remove(callback,context)})}remove(callback,context=null){if(!this._callbacks)return;let foundCallbackWithDifferentContext=!1;for(let i=0,len=this._callbacks.length;i<len;i++)if(this._callbacks[i]===callback)if(this._contexts[i]===context){this._callbacks.splice(i,1),this._contexts.splice(i,1);return}else foundCallbackWithDifferentContext=!0;if(foundCallbackWithDifferentContext)throw new Error("When adding a listener with a context, you should remove it with the same context")}invoke(...args){if(!this._callbacks)return[];const ret=[],callbacks=this._callbacks.slice(0),contexts=this._contexts.slice(0);for(let i=0,len=callbacks.length;i<len;i++)try{ret.push(callbacks[i].apply(contexts[i],args))}catch(e){(0,ral_1.default)().console.error(e)}return ret}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}}class Emitter{constructor(_options){this._options=_options}get event(){return this._event||(this._event=(listener,thisArgs,disposables)=>{this._callbacks||(this._callbacks=new CallbackList),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(listener,thisArgs);const result={dispose:()=>{this._callbacks&&(this._callbacks.remove(listener,thisArgs),result.dispose=Emitter._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(disposables)&&disposables.push(result),result}),this._event}fire(event){this._callbacks&&this._callbacks.invoke.call(this._callbacks,event)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}}return events.Emitter=Emitter,Emitter._noop=function(){},events}var hasRequiredCancellation;function requireCancellation(){if(hasRequiredCancellation)return cancellation;hasRequiredCancellation=1,Object.defineProperty(cancellation,"__esModule",{value:!0}),cancellation.CancellationTokenSource=cancellation.CancellationToken=void 0;const ral_1=requireRal(),Is2=requireIs$1(),events_1=requireEvents();var CancellationToken;(function(CancellationToken2){CancellationToken2.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:events_1.Event.None}),CancellationToken2.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:events_1.Event.None});function is2(value){const candidate=value;return candidate&&(candidate===CancellationToken2.None||candidate===CancellationToken2.Cancelled||Is2.boolean(candidate.isCancellationRequested)&&!!candidate.onCancellationRequested)}CancellationToken2.is=is2})(CancellationToken||(cancellation.CancellationToken=CancellationToken={}));const shortcutEvent=Object.freeze(function(callback,context){const handle=(0,ral_1.default)().timer.setTimeout(callback.bind(context),0);return{dispose(){handle.dispose()}}});class MutableToken{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?shortcutEvent:(this._emitter||(this._emitter=new events_1.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}}class CancellationTokenSource{get token(){return this._token||(this._token=new MutableToken),this._token}cancel(){this._token?this._token.cancel():this._token=CancellationToken.Cancelled}dispose(){this._token?this._token instanceof MutableToken&&this._token.dispose():this._token=CancellationToken.None}}return cancellation.CancellationTokenSource=CancellationTokenSource,cancellation}var cancellationExports=requireCancellation();function delayNextTick(){return new Promise(resolve=>{typeof setImmediate>"u"?setTimeout(resolve,0):setImmediate(resolve)})}let lastTick=0,globalInterruptionPeriod=10;function startCancelableOperation(){return lastTick=performance.now(),new cancellationExports.CancellationTokenSource}const OperationCancelled=Symbol("OperationCancelled");function isOperationCancelled(err){return err===OperationCancelled}async function interruptAndCheck(token){if(token===cancellationExports.CancellationToken.None)return;const current=performance.now();if(current-lastTick>=globalInterruptionPeriod&&(lastTick=current,await delayNextTick(),lastTick=performance.now()),token.isCancellationRequested)throw OperationCancelled}class Deferred{constructor(){this.promise=new Promise((resolve,reject)=>{this.resolve=arg=>(resolve(arg),this),this.reject=err=>(reject(err),this)})}}class FullTextDocument2{constructor(uri,languageId,version,content){this._uri=uri,this._languageId=languageId,this._version=version,this._content=content,this._lineOffsets=void 0}get uri(){return this._uri}get languageId(){return this._languageId}get version(){return this._version}getText(range){if(range){const start=this.offsetAt(range.start),end=this.offsetAt(range.end);return this._content.substring(start,end)}return this._content}update(changes,version){for(const change of changes)if(FullTextDocument2.isIncremental(change)){const range=getWellformedRange(change.range),startOffset=this.offsetAt(range.start),endOffset=this.offsetAt(range.end);this._content=this._content.substring(0,startOffset)+change.text+this._content.substring(endOffset,this._content.length);const startLine=Math.max(range.start.line,0),endLine=Math.max(range.end.line,0);let lineOffsets=this._lineOffsets;const addedLineOffsets=computeLineOffsets(change.text,!1,startOffset);if(endLine-startLine===addedLineOffsets.length)for(let i=0,len=addedLineOffsets.length;i<len;i++)lineOffsets[i+startLine+1]=addedLineOffsets[i];else addedLineOffsets.length<1e4?lineOffsets.splice(startLine+1,endLine-startLine,...addedLineOffsets):this._lineOffsets=lineOffsets=lineOffsets.slice(0,startLine+1).concat(addedLineOffsets,lineOffsets.slice(endLine+1));const diff=change.text.length-(endOffset-startOffset);if(diff!==0)for(let i=startLine+1+addedLineOffsets.length,len=lineOffsets.length;i<len;i++)lineOffsets[i]=lineOffsets[i]+diff}else if(FullTextDocument2.isFull(change))this._content=change.text,this._lineOffsets=void 0;else throw new Error("Unknown change event received");this._version=version}getLineOffsets(){return this._lineOffsets===void 0&&(this._lineOffsets=computeLineOffsets(this._content,!0)),this._lineOffsets}positionAt(offset){offset=Math.max(Math.min(offset,this._content.length),0);const lineOffsets=this.getLineOffsets();let low=0,high=lineOffsets.length;if(high===0)return{line:0,character:offset};for(;low<high;){const mid=Math.floor((low+high)/2);lineOffsets[mid]>offset?high=mid:low=mid+1}const line=low-1;return offset=this.ensureBeforeEOL(offset,lineOffsets[line]),{line,character:offset-lineOffsets[line]}}offsetAt(position){const lineOffsets=this.getLineOffsets();if(position.line>=lineOffsets.length)return this._content.length;if(position.line<0)return 0;const lineOffset=lineOffsets[position.line];if(position.character<=0)return lineOffset;const nextLineOffset=position.line+1<lineOffsets.length?lineOffsets[position.line+1]:this._content.length,offset=Math.min(lineOffset+position.character,nextLineOffset);return this.ensureBeforeEOL(offset,lineOffset)}ensureBeforeEOL(offset,lineOffset){for(;offset>lineOffset&&isEOL(this._content.charCodeAt(offset-1));)offset--;return offset}get lineCount(){return this.getLineOffsets().length}static isIncremental(event){const candidate=event;return candidate!=null&&typeof candidate.text=="string"&&candidate.range!==void 0&&(candidate.rangeLength===void 0||typeof candidate.rangeLength=="number")}static isFull(event){const candidate=event;return candidate!=null&&typeof candidate.text=="string"&&candidate.range===void 0&&candidate.rangeLength===void 0}}var TextDocument;(function(TextDocument2){function create(uri,languageId,version,content){return new FullTextDocument2(uri,languageId,version,content)}TextDocument2.create=create;function update(document,changes,version){if(document instanceof FullTextDocument2)return document.update(changes,version),document;throw new Error("TextDocument.update: document must be created by TextDocument.create")}TextDocument2.update=update;function applyEdits(document,edits){const text=document.getText(),sortedEdits=mergeSort(edits.map(getWellformedEdit),(a,b)=>{const diff=a.range.start.line-b.range.start.line;return diff===0?a.range.start.character-b.range.start.character:diff});let lastModifiedOffset=0;const spans=[];for(const e of sortedEdits){const startOffset=document.offsetAt(e.range.start);if(startOffset<lastModifiedOffset)throw new Error("Overlapping edit");startOffset>lastModifiedOffset&&spans.push(text.substring(lastModifiedOffset,startOffset)),e.newText.length&&spans.push(e.newText),lastModifiedOffset=document.offsetAt(e.range.end)}return spans.push(text.substr(lastModifiedOffset)),spans.join("")}TextDocument2.applyEdits=applyEdits})(TextDocument||(TextDocument={}));function mergeSort(data,compare){if(data.length<=1)return data;const p=data.length/2|0,left=data.slice(0,p),right=data.slice(p);mergeSort(left,compare),mergeSort(right,compare);let leftIdx=0,rightIdx=0,i=0;for(;leftIdx<left.length&&rightIdx<right.length;)compare(left[leftIdx],right[rightIdx])<=0?data[i++]=left[leftIdx++]:data[i++]=right[rightIdx++];for(;leftIdx<left.length;)data[i++]=left[leftIdx++];for(;rightIdx<right.length;)data[i++]=right[rightIdx++];return data}function computeLineOffsets(text,isAtLineStart,textOffset=0){const result=isAtLineStart?[textOffset]:[];for(let i=0;i<text.length;i++){const ch=text.charCodeAt(i);isEOL(ch)&&(ch===13&&i+1<text.length&&text.charCodeAt(i+1)===10&&i++,result.push(textOffset+i+1))}return result}function isEOL(char){return char===13||char===10}function getWellformedRange(range){const start=range.start,end=range.end;return start.line>end.line||start.line===end.line&&start.character>end.character?{start:end,end:start}:range}function getWellformedEdit(textEdit){const range=getWellformedRange(textEdit.range);return range!==textEdit.range?{newText:textEdit.newText,range}:textEdit}var LIB;(()=>{var t={975:t2=>{function e2(t3){if(typeof t3!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t3))}function r2(t3,e3){for(var r3,n3="",i2=0,o2=-1,s2=0,h2=0;h2<=t3.length;++h2){if(h2<t3.length)r3=t3.charCodeAt(h2);else{if(r3===47)break;r3=47}if(r3===47){if(!(o2===h2-1||s2===1))if(o2!==h2-1&&s2===2){if(n3.length<2||i2!==2||n3.charCodeAt(n3.length-1)!==46||n3.charCodeAt(n3.length-2)!==46){if(n3.length>2){var a2=n3.lastIndexOf("/");if(a2!==n3.length-1){a2===-1?(n3="",i2=0):i2=(n3=n3.slice(0,a2)).length-1-n3.lastIndexOf("/"),o2=h2,s2=0;continue}}else if(n3.length===2||n3.length===1){n3="",i2=0,o2=h2,s2=0;continue}}e3&&(n3.length>0?n3+="/..":n3="..",i2=2)}else n3.length>0?n3+="/"+t3.slice(o2+1,h2):n3=t3.slice(o2+1,h2),i2=h2-o2-1;o2=h2,s2=0}else r3===46&&s2!==-1?++s2:s2=-1}return n3}var n2={resolve:function(){for(var t3,n3="",i2=!1,o2=arguments.length-1;o2>=-1&&!i2;o2--){var s2;o2>=0?s2=arguments[o2]:(t3===void 0&&(t3=process.cwd()),s2=t3),e2(s2),s2.length!==0&&(n3=s2+"/"+n3,i2=s2.charCodeAt(0)===47)}return n3=r2(n3,!i2),i2?n3.length>0?"/"+n3:"/":n3.length>0?n3:"."},normalize:function(t3){if(e2(t3),t3.length===0)return".";var n3=t3.charCodeAt(0)===47,i2=t3.charCodeAt(t3.length-1)===47;return(t3=r2(t3,!n3)).length!==0||n3||(t3="."),t3.length>0&&i2&&(t3+="/"),n3?"/"+t3:t3},isAbsolute:function(t3){return e2(t3),t3.length>0&&t3.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var t3,r3=0;r3<arguments.length;++r3){var i2=arguments[r3];e2(i2),i2.length>0&&(t3===void 0?t3=i2:t3+="/"+i2)}return t3===void 0?".":n2.normalize(t3)},relative:function(t3,r3){if(e2(t3),e2(r3),t3===r3||(t3=n2.resolve(t3))===(r3=n2.resolve(r3)))return"";for(var i2=1;i2<t3.length&&t3.charCodeAt(i2)===47;++i2);for(var o2=t3.length,s2=o2-i2,h2=1;h2<r3.length&&r3.charCodeAt(h2)===47;++h2);for(var a2=r3.length-h2,c2=s2<a2?s2:a2,f2=-1,u2=0;u2<=c2;++u2){if(u2===c2){if(a2>c2){if(r3.charCodeAt(h2+u2)===47)return r3.slice(h2+u2+1);if(u2===0)return r3.slice(h2+u2)}else s2>c2&&(t3.charCodeAt(i2+u2)===47?f2=u2:u2===0&&(f2=0));break}var l2=t3.charCodeAt(i2+u2);if(l2!==r3.charCodeAt(h2+u2))break;l2===47&&(f2=u2)}var g2="";for(u2=i2+f2+1;u2<=o2;++u2)u2!==o2&&t3.charCodeAt(u2)!==47||(g2.length===0?g2+="..":g2+="/..");return g2.length>0?g2+r3.slice(h2+f2):(h2+=f2,r3.charCodeAt(h2)===47&&++h2,r3.slice(h2))},_makeLong:function(t3){return t3},dirname:function(t3){if(e2(t3),t3.length===0)return".";for(var r3=t3.charCodeAt(0),n3=r3===47,i2=-1,o2=!0,s2=t3.length-1;s2>=1;--s2)if((r3=t3.charCodeAt(s2))===47){if(!o2){i2=s2;break}}else o2=!1;return i2===-1?n3?"/":".":n3&&i2===1?"//":t3.slice(0,i2)},basename:function(t3,r3){if(r3!==void 0&&typeof r3!="string")throw new TypeError('"ext" argument must be a string');e2(t3);var n3,i2=0,o2=-1,s2=!0;if(r3!==void 0&&r3.length>0&&r3.length<=t3.length){if(r3.length===t3.length&&r3===t3)return"";var h2=r3.length-1,a2=-1;for(n3=t3.length-1;n3>=0;--n3){var c2=t3.charCodeAt(n3);if(c2===47){if(!s2){i2=n3+1;break}}else a2===-1&&(s2=!1,a2=n3+1),h2>=0&&(c2===r3.charCodeAt(h2)?--h2==-1&&(o2=n3):(h2=-1,o2=a2))}return i2===o2?o2=a2:o2===-1&&(o2=t3.length),t3.slice(i2,o2)}for(n3=t3.length-1;n3>=0;--n3)if(t3.charCodeAt(n3)===47){if(!s2){i2=n3+1;break}}else o2===-1&&(s2=!1,o2=n3+1);return o2===-1?"":t3.slice(i2,o2)},extname:function(t3){e2(t3);for(var r3=-1,n3=0,i2=-1,o2=!0,s2=0,h2=t3.length-1;h2>=0;--h2){var a2=t3.charCodeAt(h2);if(a2!==47)i2===-1&&(o2=!1,i2=h2+1),a2===46?r3===-1?r3=h2:s2!==1&&(s2=1):r3!==-1&&(s2=-1);else if(!o2){n3=h2+1;break}}return r3===-1||i2===-1||s2===0||s2===1&&r3===i2-1&&r3===n3+1?"":t3.slice(r3,i2)},format:function(t3){if(t3===null||typeof t3!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t3);return(function(t4,e3){var r3=e3.dir||e3.root,n3=e3.base||(e3.name||"")+(e3.ext||"");return r3?r3===e3.root?r3+n3:r3+"/"+n3:n3})(0,t3)},parse:function(t3){e2(t3);var r3={root:"",dir:"",base:"",ext:"",name:""};if(t3.length===0)return r3;var n3,i2=t3.charCodeAt(0),o2=i2===47;o2?(r3.root="/",n3=1):n3=0;for(var s2=-1,h2=0,a2=-1,c2=!0,f2=t3.length-1,u2=0;f2>=n3;--f2)if((i2=t3.charCodeAt(f2))!==47)a2===-1&&(c2=!1,a2=f2+1),i2===46?s2===-1?s2=f2:u2!==1&&(u2=1):s2!==-1&&(u2=-1);else if(!c2){h2=f2+1;break}return s2===-1||a2===-1||u2===0||u2===1&&s2===a2-1&&s2===h2+1?a2!==-1&&(r3.base=r3.name=h2===0&&o2?t3.slice(1,a2):t3.slice(h2,a2)):(h2===0&&o2?(r3.name=t3.slice(1,s2),r3.base=t3.slice(1,a2)):(r3.name=t3.slice(h2,s2),r3.base=t3.slice(h2,a2)),r3.ext=t3.slice(s2,a2)),h2>0?r3.dir=t3.slice(0,h2-1):o2&&(r3.dir="/"),r3},sep:"/",delimiter:":",win32:null,posix:null};n2.posix=n2,t2.exports=n2}},e={};function r(n2){var i2=e[n2];if(i2!==void 0)return i2.exports;var o2=e[n2]={exports:{}};return t[n2](o2,o2.exports,r),o2.exports}r.d=(t2,e2)=>{for(var n2 in e2)r.o(e2,n2)&&!r.o(t2,n2)&&Object.defineProperty(t2,n2,{enumerable:!0,get:e2[n2]})},r.o=(t2,e2)=>Object.prototype.hasOwnProperty.call(t2,e2),r.r=t2=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(t2,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t2,"__esModule",{value:!0})};var n={};let i;r.r(n),r.d(n,{URI:()=>l,Utils:()=>I}),typeof process=="object"?i=process.platform==="win32":typeof navigator=="object"&&(i=navigator.userAgent.indexOf("Windows")>=0);const o=/^\w[\w\d+.-]*$/,s=/^\//,h=/^\/\//;function a(t2,e2){if(!t2.scheme&&e2)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${t2.authority}", path: "${t2.path}", query: "${t2.query}", fragment: "${t2.fragment}"}`);if(t2.scheme&&!o.test(t2.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(t2.path){if(t2.authority){if(!s.test(t2.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(h.test(t2.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}const c="",f="/",u=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class l{constructor(t2,e2,r2,n2,i2,o2=!1){__publicField(this,"scheme");__publicField(this,"authority");__publicField(this,"path");__publicField(this,"query");__publicField(this,"fragment");typeof t2=="object"?(this.scheme=t2.scheme||c,this.authority=t2.authority||c,this.path=t2.path||c,this.query=t2.query||c,this.fragment=t2.fragment||c):(this.scheme=(function(t3,e3){return t3||e3?t3:"file"})(t2,o2),this.authority=e2||c,this.path=(function(t3,e3){switch(t3){case"https":case"http":case"file":e3?e3[0]!==f&&(e3=f+e3):e3=f}return e3})(this.scheme,r2||c),this.query=n2||c,this.fragment=i2||c,a(this,o2))}static isUri(t2){return t2 instanceof l||!!t2&&typeof t2.authority=="string"&&typeof t2.fragment=="string"&&typeof t2.path=="string"&&typeof t2.query=="string"&&typeof t2.scheme=="string"&&typeof t2.fsPath=="string"&&typeof t2.with=="function"&&typeof t2.toString=="function"}get fsPath(){return v(this)}with(t2){if(!t2)return this;let{scheme:e2,authority:r2,path:n2,query:i2,fragment:o2}=t2;return e2===void 0?e2=this.scheme:e2===null&&(e2=c),r2===void 0?r2=this.authority:r2===null&&(r2=c),n2===void 0?n2=this.path:n2===null&&(n2=c),i2===void 0?i2=this.query:i2===null&&(i2=c),o2===void 0?o2=this.fragment:o2===null&&(o2=c),e2===this.scheme&&r2===this.authority&&n2===this.path&&i2===this.query&&o2===this.fragment?this:new d(e2,r2,n2,i2,o2)}static parse(t2,e2=!1){const r2=u.exec(t2);return r2?new d(r2[2]||c,w(r2[4]||c),w(r2[5]||c),w(r2[7]||c),w(r2[9]||c),e2):new d(c,c,c,c,c)}static file(t2){let e2=c;if(i&&(t2=t2.replace(/\\/g,f)),t2[0]===f&&t2[1]===f){const r2=t2.indexOf(f,2);r2===-1?(e2=t2.substring(2),t2=f):(e2=t2.substring(2,r2),t2=t2.substring(r2)||f)}return new d("file",e2,t2,c,c)}static from(t2){const e2=new d(t2.scheme,t2.authority,t2.path,t2.query,t2.fragment);return a(e2,!0),e2}toString(t2=!1){return b(this,t2)}toJSON(){return this}static revive(t2){if(t2){if(t2 instanceof l)return t2;{const e2=new d(t2);return e2._formatted=t2.external,e2._fsPath=t2._sep===g?t2.fsPath:null,e2}}return t2}}const g=i?1:void 0;class d extends l{constructor(){super(...arguments);__publicField(this,"_formatted",null);__publicField(this,"_fsPath",null)}get fsPath(){return this._fsPath||(this._fsPath=v(this)),this._fsPath}toString(t2=!1){return t2?b(this,!0):(this._formatted||(this._formatted=b(this,!1)),this._formatted)}toJSON(){const t2={$mid:1};return this._fsPath&&(t2.fsPath=this._fsPath,t2._sep=g),this._formatted&&(t2.external=this._formatted),this.path&&(t2.path=this.path),this.scheme&&(t2.scheme=this.scheme),this.authority&&(t2.authority=this.authority),this.query&&(t2.query=this.query),this.fragment&&(t2.fragment=this.fragment),t2}}const p={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function m(t2,e2,r2){let n2,i2=-1;for(let o2=0;o2<t2.length;o2++){const s2=t2.charCodeAt(o2);if(s2>=97&&s2<=122||s2>=65&&s2<=90||s2>=48&&s2<=57||s2===45||s2===46||s2===95||s2===126||e2&&s2===47||r2&&s2===91||r2&&s2===93||r2&&s2===58)i2!==-1&&(n2+=encodeURIComponent(t2.substring(i2,o2)),i2=-1),n2!==void 0&&(n2+=t2.charAt(o2));else{n2===void 0&&(n2=t2.substr(0,o2));const e3=p[s2];e3!==void 0?(i2!==-1&&(n2+=encodeURIComponent(t2.substring(i2,o2)),i2=-1),n2+=e3):i2===-1&&(i2=o2)}}return i2!==-1&&(n2+=encodeURIComponent(t2.substring(i2))),n2!==void 0?n2:t2}function y(t2){let e2;for(let r2=0;r2<t2.length;r2++){const n2=t2.charCodeAt(r2);n2===35||n2===63?(e2===void 0&&(e2=t2.substr(0,r2)),e2+=p[n2]):e2!==void 0&&(e2+=t2[r2])}return e2!==void 0?e2:t2}function v(t2,e2){let r2;return r2=t2.authority&&t2.path.length>1&&t2.scheme==="file"?`//${t2.authority}${t2.path}`:t2.path.charCodeAt(0)===47&&(t2.path.charCodeAt(1)>=65&&t2.path.charCodeAt(1)<=90||t2.path.charCodeAt(1)>=97&&t2.path.charCodeAt(1)<=122)&&t2.path.charCodeAt(2)===58?t2.path[1].toLowerCase()+t2.path.substr(2):t2.path,i&&(r2=r2.replace(/\//g,"\\")),r2}function b(t2,e2){const r2=e2?y:m;let n2="",{scheme:i2,authority:o2,path:s2,query:h2,fragment:a2}=t2;if(i2&&(n2+=i2,n2+=":"),(o2||i2==="file")&&(n2+=f,n2+=f),o2){let t3=o2.indexOf("@");if(t3!==-1){const e3=o2.substr(0,t3);o2=o2.substr(t3+1),t3=e3.lastIndexOf(":"),t3===-1?n2+=r2(e3,!1,!1):(n2+=r2(e3.substr(0,t3),!1,!1),n2+=":",n2+=r2(e3.substr(t3+1),!1,!0)),n2+="@"}o2=o2.toLowerCase(),t3=o2.lastIndexOf(":"),t3===-1?n2+=r2(o2,!1,!0):(n2+=r2(o2.substr(0,t3),!1,!0),n2+=o2.substr(t3))}if(s2){if(s2.length>=3&&s2.charCodeAt(0)===47&&s2.charCodeAt(2)===58){const t3=s2.charCodeAt(1);t3>=65&&t3<=90&&(s2=`/${String.fromCharCode(t3+32)}:${s2.substr(3)}`)}else if(s2.length>=2&&s2.charCodeAt(1)===58){const t3=s2.charCodeAt(0);t3>=65&&t3<=90&&(s2=`${String.fromCharCode(t3+32)}:${s2.substr(2)}`)}n2+=r2(s2,!0,!1)}return h2&&(n2+="?",n2+=r2(h2,!1,!1)),a2&&(n2+="#",n2+=e2?a2:m(a2,!1,!1)),n2}function C(t2){try{return decodeURIComponent(t2)}catch{return t2.length>3?t2.substr(0,3)+C(t2.substr(3)):t2}}const A=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function w(t2){return t2.match(A)?t2.replace(A,(t3=>C(t3))):t2}var x=r(975);const P=x.posix||x,_="/";var I;(function(t2){t2.joinPath=function(t3,...e2){return t3.with({path:P.join(t3.path,...e2)})},t2.resolvePath=function(t3,...e2){let r2=t3.path,n2=!1;r2[0]!==_&&(r2=_+r2,n2=!0);let i2=P.resolve(r2,...e2);return n2&&i2[0]===_&&!t3.authority&&(i2=i2.substring(1)),t3.with({path:i2})},t2.dirname=function(t3){if(t3.path.length===0||t3.path===_)return t3;let e2=P.dirname(t3.path);return e2.length===1&&e2.charCodeAt(0)===46&&(e2=""),t3.with({path:e2})},t2.basename=function(t3){return P.basename(t3.path)},t2.extname=function(t3){return P.extname(t3.path)}})(I||(I={})),LIB=n})();const{URI,Utils}=LIB;var UriUtils;(function(UriUtils2){UriUtils2.basename=Utils.basename,UriUtils2.dirname=Utils.dirname,UriUtils2.extname=Utils.extname,UriUtils2.joinPath=Utils.joinPath,UriUtils2.resolvePath=Utils.resolvePath;const isWindows=typeof process=="object"&&(process==null?void 0:process.platform)==="win32";function equals(a,b){return(a==null?void 0:a.toString())===(b==null?void 0:b.toString())}UriUtils2.equals=equals;function relative(from,to){const fromPath=typeof from=="string"?URI.parse(from).path:from.path,toPath=typeof to=="string"?URI.parse(to).path:to.path,fromParts=fromPath.split("/").filter(e=>e.length>0),toParts=toPath.split("/").filter(e=>e.length>0);if(isWindows){const upperCaseDriveLetter=/^[A-Z]:$/;if(fromParts[0]&&upperCaseDriveLetter.test(fromParts[0])&&(fromParts[0]=fromParts[0].toLowerCase()),toParts[0]&&upperCaseDriveLetter.test(toParts[0])&&(toParts[0]=toParts[0].toLowerCase()),fromParts[0]!==toParts[0])return toPath.substring(1)}let i=0;for(;i<fromParts.length&&fromParts[i]===toParts[i];i++);const backPart="../".repeat(fromParts.length-i),toPart=toParts.slice(i).join("/");return backPart+toPart}UriUtils2.relative=relative;function normalize(uri){return URI.parse(uri.toString()).toString()}UriUtils2.normalize=normalize;function contains(parent,child){let parentPath=typeof parent=="string"?parent:parent.path,childPath=typeof child=="string"?child:child.path;return childPath.charAt(childPath.length-1)==="/"&&(childPath=childPath.slice(0,-1)),parentPath.charAt(parentPath.length-1)==="/"&&(parentPath=parentPath.slice(0,-1)),childPath===parentPath?!0:childPath.length<parentPath.length||childPath.charAt(parentPath.length)!=="/"?!1:childPath.startsWith(parentPath)}UriUtils2.contains=contains})(UriUtils||(UriUtils={}));class UriTrie{constructor(){this.root={name:"",children:new Map}}normalizeUri(uri){return UriUtils.normalize(uri)}clear(){this.root.children.clear()}insert(uri,element){const node=this.getNode(this.normalizeUri(uri),!0);node.element=element}delete(uri){const nodeToDelete=this.getNode(this.normalizeUri(uri),!1);nodeToDelete!=null&&nodeToDelete.parent&&nodeToDelete.parent.children.delete(nodeToDelete.name)}has(uri){var _a21;return((_a21=this.getNode(this.normalizeUri(uri),!1))==null?void 0:_a21.element)!==void 0}hasNode(uri){return this.getNode(this.normalizeUri(uri),!1)!==void 0}find(uri){var _a21;return(_a21=this.getNode(this.normalizeUri(uri),!1))==null?void 0:_a21.element}findNode(uri){const uriString=this.normalizeUri(uri),node=this.getNode(uriString,!1);if(node)return{name:node.name,uri:UriUtils.joinPath(URI.parse(uriString),node.name).toString(),element:node.element}}findChildren(uri){const uriString=this.normalizeUri(uri),node=this.getNode(uriString,!1);return node?Array.from(node.children.values()).map(child=>({name:child.name,uri:UriUtils.joinPath(URI.parse(uriString),child.name).toString(),element:child.element})):[]}all(){return this.collectValues(this.root)}findAll(prefix){const node=this.getNode(UriUtils.normalize(prefix),!1);return node?this.collectValues(node):[]}getNode(uri,create){const parts=uri.split("/");uri.charAt(uri.length-1)==="/"&&parts.pop();let current=this.root;for(const part of parts){let child=current.children.get(part);if(!child)if(create)child={name:part,children:new Map,parent:current},current.children.set(part,child);else return;current=child}return current}collectValues(node){const result=[];node.element&&result.push(node.element);for(const child of node.children.values())result.push(...this.collectValues(child));return result}}var DocumentState;(function(DocumentState2){DocumentState2[DocumentState2.Changed=0]="Changed",DocumentState2[DocumentState2.Parsed=1]="Parsed",DocumentState2[DocumentState2.IndexedContent=2]="IndexedContent",DocumentState2[DocumentState2.ComputedScopes=3]="ComputedScopes",DocumentState2[DocumentState2.Linked=4]="Linked",DocumentState2[DocumentState2.IndexedReferences=5]="IndexedReferences",DocumentState2[DocumentState2.Validated=6]="Validated"})(DocumentState||(DocumentState={}));class DefaultLangiumDocumentFactory{constructor(services){this.serviceRegistry=services.ServiceRegistry,this.textDocuments=services.workspace.TextDocuments,this.fileSystemProvider=services.workspace.FileSystemProvider}async fromUri(uri,cancellationToken=cancellationExports.CancellationToken.None){const content=await this.fileSystemProvider.readFile(uri);return this.createAsync(uri,content,cancellationToken)}fromTextDocument(textDocument,uri,token){return uri=uri??URI.parse(textDocument.uri),cancellationExports.CancellationToken.is(token)?this.createAsync(uri,textDocument,token):this.create(uri,textDocument,token)}fromString(text,uri,token){return cancellationExports.CancellationToken.is(token)?this.createAsync(uri,text,token):this.create(uri,text,token)}fromModel(model,uri){return this.create(uri,{$model:model})}create(uri,content,options){if(typeof content=="string"){const parseResult=this.parse(uri,content,options);return this.createLangiumDocument(parseResult,uri,void 0,content)}else if("$model"in content){const parseResult={value:content.$model,parserErrors:[],lexerErrors:[]};return this.createLangiumDocument(parseResult,uri)}else{const parseResult=this.parse(uri,content.getText(),options);return this.createLangiumDocument(parseResult,uri,content)}}async createAsync(uri,content,cancelToken){if(typeof content=="string"){const parseResult=await this.parseAsync(uri,content,cancelToken);return this.createLangiumDocument(parseResult,uri,void 0,content)}else{const parseResult=await this.parseAsync(uri,content.getText(),cancelToken);return this.createLangiumDocument(parseResult,uri,content)}}createLangiumDocument(parseResult,uri,textDocument,text){let document;if(textDocument)document={parseResult,uri,state:DocumentState.Parsed,references:[],textDocument};else{const textDocumentGetter=this.createTextDocumentGetter(uri,text);document={parseResult,uri,state:DocumentState.Parsed,references:[],get textDocument(){return textDocumentGetter()}}}return parseResult.value.$document=document,document}async update(document,cancellationToken){var _a21,_b;const oldText=(_a21=document.parseResult.value.$cstNode)==null?void 0:_a21.root.fullText,textDocument=(_b=this.textDocuments)==null?void 0:_b.get(document.uri.toString()),text=textDocument?textDocument.getText():await this.fileSystemProvider.readFile(document.uri);if(textDocument)Object.defineProperty(document,"textDocument",{value:textDocument});else{const textDocumentGetter=this.createTextDocumentGetter(document.uri,text);Object.defineProperty(document,"textDocument",{get:textDocumentGetter})}return oldText!==text&&(document.parseResult=await this.parseAsync(document.uri,text,cancellationToken),document.parseResult.value.$document=document),document.state=DocumentState.Parsed,document}parse(uri,text,options){return this.serviceRegistry.getServices(uri).parser.LangiumParser.parse(text,options)}parseAsync(uri,text,cancellationToken){return this.serviceRegistry.getServices(uri).parser.AsyncParser.parse(text,cancellationToken)}createTextDocumentGetter(uri,text){const serviceRegistry=this.serviceRegistry;let textDoc;return()=>textDoc??(textDoc=TextDocument.create(uri.toString(),serviceRegistry.getServices(uri).LanguageMetaData.languageId,0,text??""))}}class DefaultLangiumDocuments{constructor(services){this.documentTrie=new UriTrie,this.services=services,this.langiumDocumentFactory=services.workspace.LangiumDocumentFactory,this.documentBuilder=()=>services.workspace.DocumentBuilder}get all(){return stream(this.documentTrie.all())}addDocument(document){const uriString=document.uri.toString();if(this.documentTrie.has(uriString))throw new Error(`A document with the URI '${uriString}' is already present.`);this.documentTrie.insert(uriString,document)}getDocument(uri){const uriString=uri.toString();return this.documentTrie.find(uriString)}getDocuments(folder){const uriString=folder.toString();return this.documentTrie.findAll(uriString)}async getOrCreateDocument(uri,cancellationToken){let document=this.getDocument(uri);return document||(document=await this.langiumDocumentFactory.fromUri(uri,cancellationToken),this.addDocument(document),document)}createDocument(uri,text,cancellationToken){if(cancellationToken)return this.langiumDocumentFactory.fromString(text,uri,cancellationToken).then(document=>(this.addDocument(document),document));{const document=this.langiumDocumentFactory.fromString(text,uri);return this.addDocument(document),document}}hasDocument(uri){return this.documentTrie.has(uri.toString())}invalidateDocument(uri){const uriString=uri.toString(),langiumDoc=this.documentTrie.find(uriString);return langiumDoc&&this.documentBuilder().resetToState(langiumDoc,DocumentState.Changed),langiumDoc}deleteDocument(uri){const uriString=uri.toString(),langiumDoc=this.documentTrie.find(uriString);return langiumDoc&&(langiumDoc.state=DocumentState.Changed,this.documentTrie.delete(uriString)),langiumDoc}deleteDocuments(folder){const uriString=folder.toString(),langiumDocs=this.documentTrie.findAll(uriString);for(const langiumDoc of langiumDocs)langiumDoc.state=DocumentState.Changed;return this.documentTrie.delete(uriString),langiumDocs}}const RefResolving=Symbol("RefResolving");class DefaultLinker{constructor(services){this.reflection=services.shared.AstReflection,this.langiumDocuments=()=>services.shared.workspace.LangiumDocuments,this.scopeProvider=services.references.ScopeProvider,this.astNodeLocator=services.workspace.AstNodeLocator,this.profiler=services.shared.profilers.LangiumProfiler,this.languageId=services.LanguageMetaData.languageId}async link(document,cancelToken=cancellationExports.CancellationToken.None){var _a21;if((_a21=this.profiler)!=null&&_a21.isActive("linking")){const task=this.profiler.createTask("linking",this.languageId);task.start();try{for(const node of streamAst(document.parseResult.value))await interruptAndCheck(cancelToken),streamReferences(node).forEach(ref=>{const name=`${node.$type}:${ref.property}`;task.startSubTask(name);try{this.doLink(ref,document)}finally{task.stopSubTask(name)}})}finally{task.stop()}}else for(const node of streamAst(document.parseResult.value))await interruptAndCheck(cancelToken),streamReferences(node).forEach(ref=>this.doLink(ref,document))}doLink(refInfo,document){const ref=refInfo.reference;if("_ref"in ref&&ref._ref===void 0){ref._ref=RefResolving;try{const description=this.getCandidate(refInfo);if(isLinkingError(description))ref._ref=description;else{ref._nodeDescription=description;const linkedNode=this.loadAstNode(description);ref._ref=linkedNode??this.createLinkingError(refInfo,description)}}catch(err){console.error(`An error occurred while resolving reference to '${ref.$refText}':`,err);const errorMessage=err.message??String(err);ref._ref={info:refInfo,message:`An error occurred while resolving reference to '${ref.$refText}': ${errorMessage}`}}document.references.push(ref)}else if("_items"in ref&&ref._items===void 0){ref._items=RefResolving;try{const descriptions=this.getCandidates(refInfo),items=[];if(isLinkingError(descriptions))ref._linkingError=descriptions;else for(const description of descriptions){const linkedNode=this.loadAstNode(description);linkedNode&&items.push({ref:linkedNode,$nodeDescription:description})}ref._items=items}catch(err){ref._linkingError={info:refInfo,message:`An error occurred while resolving reference to '${ref.$refText}': ${err}`},ref._items=[]}document.references.push(ref)}}unlink(document){for(const ref of document.references)"_ref"in ref?(ref._ref=void 0,delete ref._nodeDescription):"_items"in ref&&(ref._items=void 0,delete ref._linkingError);document.references=[]}getCandidate(refInfo){return this.scopeProvider.getScope(refInfo).getElement(refInfo.reference.$refText)??this.createLinkingError(refInfo)}getCandidates(refInfo){const descriptions=this.scopeProvider.getScope(refInfo).getElements(refInfo.reference.$refText).distinct(desc=>`${desc.documentUri}#${desc.path}`).toArray();return descriptions.length>0?descriptions:this.createLinkingError(refInfo)}buildReference(node,property,refNode,refText){const linker=this,reference={$refNode:refNode,$refText:refText,_ref:void 0,get ref(){if(isAstNode(this._ref))return this._ref;if(isAstNodeDescription(this._nodeDescription)){const linkedNode=linker.loadAstNode(this._nodeDescription);this._ref=linkedNode??linker.createLinkingError({reference,container:node,property},this._nodeDescription)}else if(this._ref===void 0){this._ref=RefResolving;const document=findRootNode(node).$document,refData=linker.getLinkedNode({reference,container:node,property});if(refData.error&&document&&document.state<DocumentState.ComputedScopes)return this._ref=void 0;this._ref=refData.node??refData.error,this._nodeDescription=refData.descr,document==null||document.references.push(this)}else this._ref===RefResolving&&linker.throwCyclicReferenceError(node,property,refText);return isAstNode(this._ref)?this._ref:void 0},get $nodeDescription(){return this._nodeDescription},get error(){return isLinkingError(this._ref)?this._ref:void 0}};return reference}buildMultiReference(node,property,refNode,refText){const linker=this,reference={$refNode:refNode,$refText:refText,_items:void 0,get items(){if(Array.isArray(this._items))return this._items;if(this._items===void 0){this._items=RefResolving;const document=findRootNode(node).$document,descriptions=linker.getCandidates({reference,container:node,property}),items=[];if(isLinkingError(descriptions))this._linkingError=descriptions;else for(const description of descriptions){const linkedNode=linker.loadAstNode(description);linkedNode&&items.push({ref:linkedNode,$nodeDescription:description})}this._items=items,document==null||document.references.push(this)}else this._items===RefResolving&&linker.throwCyclicReferenceError(node,property,refText);return Array.isArray(this._items)?this._items:[]},get error(){if(this._linkingError)return this._linkingError;if(!(this.items.length>0))return this._linkingError=linker.createLinkingError({reference,container:node,property})}};return reference}throwCyclicReferenceError(node,property,refText){throw new Error(`Cyclic reference resolution detected: ${this.astNodeLocator.getAstNodePath(node)}/${property} (symbol '${refText}')`)}getLinkedNode(refInfo){try{const description=this.getCandidate(refInfo);if(isLinkingError(description))return{error:description};const linkedNode=this.loadAstNode(description);return linkedNode?{node:linkedNode,descr:description}:{descr:description,error:this.createLinkingError(refInfo,description)}}catch(err){console.error(`An error occurred while resolving reference to '${refInfo.reference.$refText}':`,err);const errorMessage=err.message??String(err);return{error:{info:refInfo,message:`An error occurred while resolving reference to '${refInfo.reference.$refText}': ${errorMessage}`}}}}loadAstNode(nodeDescription){if(nodeDescription.node)return nodeDescription.node;const doc=this.langiumDocuments().getDocument(nodeDescription.documentUri);if(doc)return this.astNodeLocator.getAstNode(doc.parseResult.value,nodeDescription.path)}createLinkingError(refInfo,targetDescription){const document=findRootNode(refInfo.container).$document;document&&document.state<DocumentState.ComputedScopes&&console.warn(`Attempted reference resolution before document reached ComputedScopes state (${document.uri}).`);const referenceType=this.reflection.getReferenceType(refInfo);return{info:refInfo,message:`Could not resolve reference to ${referenceType} named '${refInfo.reference.$refText}'.`,targetDescription}}}function isNamed(node){return typeof node.name=="string"}class DefaultNameProvider{getName(node){if(isNamed(node))return node.name}getNameNode(node){return findNodeForProperty(node.$cstNode,"name")}}class DefaultReferences{constructor(services){this.nameProvider=services.references.NameProvider,this.index=services.shared.workspace.IndexManager,this.nodeLocator=services.workspace.AstNodeLocator,this.documents=services.shared.workspace.LangiumDocuments,this.hasMultiReference=streamAst(services.Grammar).some(node=>isCrossReference(node)&&node.isMulti)}findDeclarations(sourceCstNode){if(sourceCstNode){const assignment=findAssignment(sourceCstNode),nodeElem=sourceCstNode.astNode;if(assignment&&nodeElem){const reference=nodeElem[assignment.feature];if(isReference(reference)||isMultiReference(reference))return getReferenceNodes(reference);if(Array.isArray(reference)){for(const ref of reference)if((isReference(ref)||isMultiReference(ref))&&ref.$refNode&&ref.$refNode.offset<=sourceCstNode.offset&&ref.$refNode.end>=sourceCstNode.end)return getReferenceNodes(ref)}}if(nodeElem){const nameNode=this.nameProvider.getNameNode(nodeElem);if(nameNode&&(nameNode===sourceCstNode||isChildNode(sourceCstNode,nameNode)))return this.getSelfNodes(nodeElem)}}return[]}getSelfNodes(node){if(this.hasMultiReference){const references=this.index.findAllReferences(node,this.nodeLocator.getAstNodePath(node)),headNode=this.getNodeFromReferenceDescription(references.head());if(headNode){for(const ref of streamReferences(headNode))if(isMultiReference(ref.reference)&&ref.reference.items.some(item=>item.ref===node))return ref.reference.items.map(item=>item.ref)}return[node]}else return[node]}getNodeFromReferenceDescription(ref){if(!ref)return;const doc=this.documents.getDocument(ref.sourceUri);if(doc)return this.nodeLocator.getAstNode(doc.parseResult.value,ref.sourcePath)}findDeclarationNodes(sourceCstNode){const astNodes=this.findDeclarations(sourceCstNode),cstNodes=[];for(const astNode of astNodes){const cstNode=this.nameProvider.getNameNode(astNode)??astNode.$cstNode;cstNode&&cstNodes.push(cstNode)}return cstNodes}findReferences(targetNode,options){const refs=[];options.includeDeclaration&&refs.push(...this.getSelfReferences(targetNode));let indexReferences=this.index.findAllReferences(targetNode,this.nodeLocator.getAstNodePath(targetNode));return options.documentUri&&(indexReferences=indexReferences.filter(ref=>UriUtils.equals(ref.sourceUri,options.documentUri))),refs.push(...indexReferences),stream(refs)}getSelfReferences(targetNode){const selfNodes=this.getSelfNodes(targetNode),references=[];for(const selfNode of selfNodes){const nameNode=this.nameProvider.getNameNode(selfNode);if(nameNode){const doc=getDocument(selfNode),path=this.nodeLocator.getAstNodePath(selfNode);references.push({sourceUri:doc.uri,sourcePath:path,targetUri:doc.uri,targetPath:path,segment:toDocumentSegment(nameNode),local:!0})}}return references}}class MultiMap{constructor(elements){if(this.map=new Map,elements)for(const[key,value]of elements)this.add(key,value)}get size(){return Reduction.sum(stream(this.map.values()).map(a=>a.length))}clear(){this.map.clear()}delete(key,value){if(value===void 0)return this.map.delete(key);{const values=this.map.get(key);if(values){const index=values.indexOf(value);if(index>=0)return values.length===1?this.map.delete(key):values.splice(index,1),!0}return!1}}get(key){return this.map.get(key)??[]}getStream(key){const values=this.map.get(key);return values?stream(values):EMPTY_STREAM}has(key,value){if(value===void 0)return this.map.has(key);{const values=this.map.get(key);return values?values.indexOf(value)>=0:!1}}add(key,value){return this.map.has(key)?this.map.get(key).push(value):this.map.set(key,[value]),this}addAll(key,values){return this.map.has(key)?this.map.get(key).push(...values):this.map.set(key,Array.from(values)),this}forEach(callbackfn){this.map.forEach((array,key)=>array.forEach(value=>callbackfn(value,key,this)))}[Symbol.iterator](){return this.entries().iterator()}entries(){return stream(this.map.entries()).flatMap(([key,array])=>array.map(value=>[key,value]))}keys(){return stream(this.map.keys())}values(){return stream(this.map.values()).flat()}entriesGroupedByKey(){return stream(this.map.entries())}}class BiMap{get size(){return this.map.size}constructor(elements){if(this.map=new Map,this.inverse=new Map,elements)for(const[key,value]of elements)this.set(key,value)}clear(){this.map.clear(),this.inverse.clear()}set(key,value){return this.map.set(key,value),this.inverse.set(value,key),this}get(key){return this.map.get(key)}getKey(value){return this.inverse.get(value)}delete(key){const value=this.map.get(key);return value!==void 0?(this.map.delete(key),this.inverse.delete(value),!0):!1}}class DefaultScopeComputation{constructor(services){this.nameProvider=services.references.NameProvider,this.descriptions=services.workspace.AstNodeDescriptionProvider}async collectExportedSymbols(document,cancelToken=cancellationExports.CancellationToken.None){return this.collectExportedSymbolsForNode(document.parseResult.value,document,void 0,cancelToken)}async collectExportedSymbolsForNode(parentNode,document,children=streamContents,cancelToken=cancellationExports.CancellationToken.None){const exports$1=[];this.addExportedSymbol(parentNode,exports$1,document);for(const node of children(parentNode))await interruptAndCheck(cancelToken),this.addExportedSymbol(node,exports$1,document);return exports$1}addExportedSymbol(node,exports$1,document){const name=this.nameProvider.getName(node);name&&exports$1.push(this.descriptions.createDescription(node,name,document))}async collectLocalSymbols(document,cancelToken=cancellationExports.CancellationToken.None){const rootNode=document.parseResult.value,symbols=new MultiMap;for(const node of streamAllContents(rootNode))await interruptAndCheck(cancelToken),this.addLocalSymbol(node,document,symbols);return symbols}addLocalSymbol(node,document,symbols){const container=node.$container;if(container){const name=this.nameProvider.getName(node);name&&symbols.add(container,this.descriptions.createDescription(node,name,document))}}}class StreamScope{constructor(elements,outerScope,options){this.elements=elements,this.outerScope=outerScope,this.caseInsensitive=(options==null?void 0:options.caseInsensitive)??!1,this.concatOuterScope=(options==null?void 0:options.concatOuterScope)??!0}getAllElements(){return this.outerScope?this.elements.concat(this.outerScope.getAllElements()):this.elements}getElement(name){const lowerCaseName=this.caseInsensitive?name.toLowerCase():name,local=this.caseInsensitive?this.elements.find(e=>e.name.toLowerCase()===lowerCaseName):this.elements.find(e=>e.name===name);if(local)return local;if(this.outerScope)return this.outerScope.getElement(name)}getElements(name){const lowerCaseName=this.caseInsensitive?name.toLowerCase():name,local=this.caseInsensitive?this.elements.filter(e=>e.name.toLowerCase()===lowerCaseName):this.elements.filter(e=>e.name===name);return(this.concatOuterScope||local.isEmpty())&&this.outerScope?local.concat(this.outerScope.getElements(name)):local}}class MultiMapScope{constructor(elements,outerScope,options){this.elements=new MultiMap,this.caseInsensitive=(options==null?void 0:options.caseInsensitive)??!1,this.concatOuterScope=(options==null?void 0:options.concatOuterScope)??!0;for(const element of elements){const name=this.caseInsensitive?element.name.toLowerCase():element.name;this.elements.add(name,element)}this.outerScope=outerScope}getElement(name){const localName=this.caseInsensitive?name.toLowerCase():name,local=this.elements.get(localName)[0];if(local)return local;if(this.outerScope)return this.outerScope.getElement(name)}getElements(name){const localName=this.caseInsensitive?name.toLowerCase():name,local=this.elements.get(localName);return(this.concatOuterScope||local.length===0)&&this.outerScope?stream(local).concat(this.outerScope.getElements(name)):stream(local)}getAllElements(){let elementStream=stream(this.elements.values());return this.outerScope&&(elementStream=elementStream.concat(this.outerScope.getAllElements())),elementStream}}class DisposableCache{constructor(){this.toDispose=[],this.isDisposed=!1}onDispose(disposable2){this.toDispose.push(disposable2)}dispose(){this.throwIfDisposed(),this.clear(),this.isDisposed=!0,this.toDispose.forEach(disposable2=>disposable2.dispose())}throwIfDisposed(){if(this.isDisposed)throw new Error("This cache has already been disposed")}}class SimpleCache extends DisposableCache{constructor(){super(...arguments),this.cache=new Map}has(key){return this.throwIfDisposed(),this.cache.has(key)}set(key,value){this.throwIfDisposed(),this.cache.set(key,value)}get(key,provider){if(this.throwIfDisposed(),this.cache.has(key))return this.cache.get(key);if(provider){const value=provider();return this.cache.set(key,value),value}else return}delete(key){return this.throwIfDisposed(),this.cache.delete(key)}clear(){this.throwIfDisposed(),this.cache.clear()}}class ContextCache extends DisposableCache{constructor(converter){super(),this.cache=new Map,this.converter=converter??(value=>value)}has(contextKey,key){return this.throwIfDisposed(),this.cacheForContext(contextKey).has(key)}set(contextKey,key,value){this.throwIfDisposed(),this.cacheForContext(contextKey).set(key,value)}get(contextKey,key,provider){this.throwIfDisposed();const contextCache=this.cacheForContext(contextKey);if(contextCache.has(key))return contextCache.get(key);if(provider){const value=provider();return contextCache.set(key,value),value}else return}delete(contextKey,key){return this.throwIfDisposed(),this.cacheForContext(contextKey).delete(key)}clear(contextKey){if(this.throwIfDisposed(),contextKey){const mapKey=this.converter(contextKey);this.cache.delete(mapKey)}else this.cache.clear()}cacheForContext(contextKey){const mapKey=this.converter(contextKey);let documentCache=this.cache.get(mapKey);return documentCache||(documentCache=new Map,this.cache.set(mapKey,documentCache)),documentCache}}class WorkspaceCache extends SimpleCache{constructor(sharedServices,state){super(),state?(this.toDispose.push(sharedServices.workspace.DocumentBuilder.onBuildPhase(state,()=>{this.clear()})),this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate((_changed,deleted)=>{deleted.length>0&&this.clear()}))):this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate(()=>{this.clear()}))}}class DefaultScopeProvider{constructor(services){this.reflection=services.shared.AstReflection,this.nameProvider=services.references.NameProvider,this.descriptions=services.workspace.AstNodeDescriptionProvider,this.indexManager=services.shared.workspace.IndexManager,this.globalScopeCache=new WorkspaceCache(services.shared)}getScope(context){const scopes=[],referenceType=this.reflection.getReferenceType(context),localSymbols=getDocument(context.container).localSymbols;if(localSymbols){let currentNode=context.container;do localSymbols.has(currentNode)&&scopes.push(localSymbols.getStream(currentNode).filter(desc=>this.reflection.isSubtype(desc.type,referenceType))),currentNode=currentNode.$container;while(currentNode)}let result=this.getGlobalScope(referenceType,context);for(let i=scopes.length-1;i>=0;i--)result=this.createScope(scopes[i],result);return result}createScope(elements,outerScope,options){return new StreamScope(stream(elements),outerScope,options)}createScopeForNodes(elements,outerScope,options){const s=stream(elements).map(e=>{const name=this.nameProvider.getName(e);if(name)return this.descriptions.createDescription(e,name)}).nonNullable();return new StreamScope(s,outerScope,options)}getGlobalScope(referenceType,_context){return this.globalScopeCache.get(referenceType,()=>new MultiMapScope(this.indexManager.allElements(referenceType)))}}function isAstNodeWithComment(node){return typeof node.$comment=="string"}function isIntermediateReference(obj){return typeof obj=="object"&&!!obj&&("$ref"in obj||"$error"in obj)}class DefaultJsonSerializer{constructor(services){this.ignoreProperties=new Set(["$container","$containerProperty","$containerIndex","$document","$cstNode"]),this.langiumDocuments=services.shared.workspace.LangiumDocuments,this.astNodeLocator=services.workspace.AstNodeLocator,this.nameProvider=services.references.NameProvider,this.commentProvider=services.documentation.CommentProvider}serialize(node,options){const serializeOptions=options??{},specificReplacer=options==null?void 0:options.replacer,defaultReplacer=(key,value)=>this.replacer(key,value,serializeOptions),replacer=specificReplacer?(key,value)=>specificReplacer(key,value,defaultReplacer):defaultReplacer;try{return this.currentDocument=getDocument(node),JSON.stringify(node,replacer,options==null?void 0:options.space)}finally{this.currentDocument=void 0}}deserialize(content,options){const deserializeOptions=options??{},root=JSON.parse(content);return this.linkNode(root,root,deserializeOptions),root}replacer(key,value,{refText,sourceText,textRegions,comments,uriConverter}){var _a21,_b,_c;if(!this.ignoreProperties.has(key))if(isReference(value)){const refValue=value.ref,$refText=refText?value.$refText:void 0;if(refValue){const targetDocument=getDocument(refValue);let targetUri="";this.currentDocument&&this.currentDocument!==targetDocument&&(uriConverter?targetUri=uriConverter(targetDocument.uri,refValue):targetUri=targetDocument.uri.toString());const targetPath=this.astNodeLocator.getAstNodePath(refValue);return{$ref:`${targetUri}#${targetPath}`,$refText}}else return{$error:((_a21=value.error)==null?void 0:_a21.message)??"Could not resolve reference",$refText}}else if(isMultiReference(value)){const $refText=refText?value.$refText:void 0,$refs=[];for(const item of value.items){const refValue=item.ref,targetDocument=getDocument(item.ref);let targetUri="";this.currentDocument&&this.currentDocument!==targetDocument&&(uriConverter?targetUri=uriConverter(targetDocument.uri,refValue):targetUri=targetDocument.uri.toString());const targetPath=this.astNodeLocator.getAstNodePath(refValue);$refs.push(`${targetUri}#${targetPath}`)}return{$refs,$refText}}else if(isAstNode(value)){let astNode;if(textRegions&&(astNode=this.addAstNodeRegionWithAssignmentsTo({...value}),(!key||value.$document)&&(astNode!=null&&astNode.$textRegion)&&(astNode.$textRegion.documentURI=(_b=this.currentDocument)==null?void 0:_b.uri.toString())),sourceText&&!key&&(astNode??(astNode={...value}),astNode.$sourceText=(_c=value.$cstNode)==null?void 0:_c.text),comments){astNode??(astNode={...value});const comment=this.commentProvider.getComment(value);comment&&(astNode.$comment=comment.replace(/\r/g,""))}return astNode??value}else return value}addAstNodeRegionWithAssignmentsTo(node){const createDocumentSegment=cstNode=>({offset:cstNode.offset,end:cstNode.end,length:cstNode.length,range:cstNode.range});if(node.$cstNode){const textRegion=node.$textRegion=createDocumentSegment(node.$cstNode),assignments=textRegion.assignments={};return Object.keys(node).filter(key=>!key.startsWith("$")).forEach(key=>{const propertyAssignments=findNodesForProperty(node.$cstNode,key).map(createDocumentSegment);propertyAssignments.length!==0&&(assignments[key]=propertyAssignments)}),node}}linkNode(node,root,options,container,containerProperty,containerIndex){for(const[propertyName,item]of Object.entries(node))if(Array.isArray(item))for(let index=0;index<item.length;index++){const element=item[index];isIntermediateReference(element)?item[index]=this.reviveReference(node,propertyName,root,element,options):isAstNode(element)&&this.linkNode(element,root,options,node,propertyName,index)}else isIntermediateReference(item)?node[propertyName]=this.reviveReference(node,propertyName,root,item,options):isAstNode(item)&&this.linkNode(item,root,options,node,propertyName);const mutable=node;mutable.$container=container,mutable.$containerProperty=containerProperty,mutable.$containerIndex=containerIndex}reviveReference(container,property,root,reference,options){let refText=reference.$refText,error=reference.$error,ref;if(reference.$ref){const refNode=this.getRefNode(root,reference.$ref,options.uriConverter);if(isAstNode(refNode))return refText||(refText=this.nameProvider.getName(refNode)),{$refText:refText??"",ref:refNode};error=refNode}else if(reference.$refs){const refs=[];for(const refUri of reference.$refs){const refNode=this.getRefNode(root,refUri,options.uriConverter);isAstNode(refNode)&&refs.push({ref:refNode})}if(refs.length===0)ref={$refText:refText??"",items:refs},error??(error="Could not resolve multi-reference");else return{$refText:refText??"",items:refs}}if(error)return ref??(ref={$refText:refText??"",ref:void 0}),ref.error={info:{container,property,reference:ref},message:error},ref}getRefNode(root,uri,uriConverter){try{const fragmentIndex=uri.indexOf("#");if(fragmentIndex===0){const node2=this.astNodeLocator.getAstNode(root,uri.substring(1));return node2||"Could not resolve path: "+uri}if(fragmentIndex<0){const documentUri2=uriConverter?uriConverter(uri):URI.parse(uri),document2=this.langiumDocuments.getDocument(documentUri2);return document2?document2.parseResult.value:"Could not find document for URI: "+uri}const documentUri=uriConverter?uriConverter(uri.substring(0,fragmentIndex)):URI.parse(uri.substring(0,fragmentIndex)),document=this.langiumDocuments.getDocument(documentUri);if(!document)return"Could not find document for URI: "+uri;if(fragmentIndex===uri.length-1)return document.parseResult.value;const node=this.astNodeLocator.getAstNode(document.parseResult.value,uri.substring(fragmentIndex+1));return node||"Could not resolve URI: "+uri}catch(err){return String(err)}}}class DefaultServiceRegistry{get map(){return this.fileExtensionMap}constructor(services){this.languageIdMap=new Map,this.fileExtensionMap=new Map,this.fileNameMap=new Map,this.textDocuments=services==null?void 0:services.workspace.TextDocuments}register(language){const data=language.LanguageMetaData;for(const ext of data.fileExtensions)this.fileExtensionMap.has(ext)&&console.warn(`The file extension ${ext} is used by multiple languages. It is now assigned to '${data.languageId}'.`),this.fileExtensionMap.set(ext,language);if(data.fileNames)for(const name of data.fileNames)this.fileNameMap.has(name)&&console.warn(`The file name ${name} is used by multiple languages. It is now assigned to '${data.languageId}'.`),this.fileNameMap.set(name,language);this.languageIdMap.set(data.languageId,language)}getServices(uri){var _a21,_b;if(this.languageIdMap.size===0)throw new Error("The service registry is empty. Use `register` to register the services of a language.");const languageId=(_b=(_a21=this.textDocuments)==null?void 0:_a21.get(uri))==null?void 0:_b.languageId;if(languageId!==void 0){const services2=this.languageIdMap.get(languageId);if(services2)return services2}const ext=UriUtils.extname(uri),name=UriUtils.basename(uri),services=this.fileNameMap.get(name)??this.fileExtensionMap.get(ext);if(!services)throw languageId?new Error(`The service registry contains no services for the extension '${ext}' for language '${languageId}'.`):new Error(`The service registry contains no services for the extension '${ext}'.`);return services}hasServices(uri){try{return this.getServices(uri),!0}catch{return!1}}get all(){return Array.from(this.languageIdMap.values())}}function diagnosticData(code){return{code}}var ValidationCategory;(function(ValidationCategory2){ValidationCategory2.defaults=["fast","slow","built-in"],ValidationCategory2.all=ValidationCategory2.defaults})(ValidationCategory||(ValidationCategory={}));class ValidationRegistry{constructor(services){this.entries=new MultiMap,this.knownCategories=new Set(ValidationCategory.defaults),this.entriesBefore=[],this.entriesAfter=[],this.reflection=services.shared.AstReflection}register(checksRecord,thisObj=this,category="fast"){if(category==="built-in")throw new Error("The 'built-in' category is reserved for lexer, parser, and linker errors.");this.knownCategories.add(category);for(const[type,ch]of Object.entries(checksRecord)){const callbacks=ch;if(Array.isArray(callbacks))for(const check of callbacks){const entry={check:this.wrapValidationException(check,thisObj),category};this.addEntry(type,entry)}else if(typeof callbacks=="function"){const entry={check:this.wrapValidationException(callbacks,thisObj),category};this.addEntry(type,entry)}else assertUnreachable()}}wrapValidationException(check,thisObj){return async(node,accept,cancelToken)=>{await this.handleException(()=>check.call(thisObj,node,accept,cancelToken),"An error occurred during validation",accept,node)}}async handleException(functionality,messageContext,accept,node){try{await functionality()}catch(err){if(isOperationCancelled(err))throw err;console.error(`${messageContext}:`,err),err instanceof Error&&err.stack&&console.error(err.stack);const messageDetails=err instanceof Error?err.message:String(err);accept("error",`${messageContext}: ${messageDetails}`,{node})}}addEntry(type,entry){if(type==="AstNode"){this.entries.add("AstNode",entry);return}for(const subtype of this.reflection.getAllSubTypes(type))this.entries.add(subtype,entry)}getChecks(type,categories){let checks=stream(this.entries.get(type)).concat(this.entries.get("AstNode"));return categories&&(checks=checks.filter(entry=>categories.includes(entry.category))),checks.map(entry=>entry.check)}registerBeforeDocument(checkBefore,thisObj=this){this.entriesBefore.push(this.wrapPreparationException(checkBefore,"An error occurred during set-up of the validation",thisObj))}registerAfterDocument(checkAfter,thisObj=this){this.entriesAfter.push(this.wrapPreparationException(checkAfter,"An error occurred during tear-down of the validation",thisObj))}wrapPreparationException(check,messageContext,thisObj){return async(rootNode,accept,categories,cancelToken)=>{await this.handleException(()=>check.call(thisObj,rootNode,accept,categories,cancelToken),messageContext,accept,rootNode)}}get checksBefore(){return this.entriesBefore}get checksAfter(){return this.entriesAfter}getAllValidationCategories(_document){return this.knownCategories}}const VALIDATE_EACH_NODE=Object.freeze({validateNode:!0,validateChildren:!0});class DefaultDocumentValidator{constructor(services){this.validationRegistry=services.validation.ValidationRegistry,this.metadata=services.LanguageMetaData,this.profiler=services.shared.profilers.LangiumProfiler,this.languageId=services.LanguageMetaData.languageId}async validateDocument(document,options={},cancelToken=cancellationExports.CancellationToken.None){const parseResult=document.parseResult,diagnostics=[];if(await interruptAndCheck(cancelToken),(!options.categories||options.categories.includes("built-in"))&&(this.processLexingErrors(parseResult,diagnostics,options),options.stopAfterLexingErrors&&diagnostics.some(d=>{var _a21;return((_a21=d.data)==null?void 0:_a21.code)===DocumentValidator.LexingError})||(this.processParsingErrors(parseResult,diagnostics,options),options.stopAfterParsingErrors&&diagnostics.some(d=>{var _a21;return((_a21=d.data)==null?void 0:_a21.code)===DocumentValidator.ParsingError}))||(this.processLinkingErrors(document,diagnostics,options),options.stopAfterLinkingErrors&&diagnostics.some(d=>{var _a21;return((_a21=d.data)==null?void 0:_a21.code)===DocumentValidator.LinkingError}))))return diagnostics;try{diagnostics.push(...await this.validateAst(parseResult.value,options,cancelToken))}catch(err){if(isOperationCancelled(err))throw err;console.error("An error occurred during validation:",err)}return await interruptAndCheck(cancelToken),diagnostics}processLexingErrors(parseResult,diagnostics,_options){var _a21;const lexerDiagnostics=[...parseResult.lexerErrors,...((_a21=parseResult.lexerReport)==null?void 0:_a21.diagnostics)??[]];for(const lexerDiagnostic of lexerDiagnostics){const severity=lexerDiagnostic.severity??"error",diagnostic={severity:toDiagnosticSeverity(severity),range:{start:{line:lexerDiagnostic.line-1,character:lexerDiagnostic.column-1},end:{line:lexerDiagnostic.line-1,character:lexerDiagnostic.column+lexerDiagnostic.length-1}},message:lexerDiagnostic.message,data:toDiagnosticData(severity),source:this.getSource()};diagnostics.push(diagnostic)}}processParsingErrors(parseResult,diagnostics,_options){for(const parserError of parseResult.parserErrors){let range;if(isNaN(parserError.token.startOffset)){if("previousToken"in parserError){const token=parserError.previousToken;if(isNaN(token.startOffset)){const position={line:0,character:0};range={start:position,end:position}}else{const position={line:token.endLine-1,character:token.endColumn};range={start:position,end:position}}}}else range=tokenToRange(parserError.token);if(range){const diagnostic={severity:toDiagnosticSeverity("error"),range,message:parserError.message,data:diagnosticData(DocumentValidator.ParsingError),source:this.getSource()};diagnostics.push(diagnostic)}}}processLinkingErrors(document,diagnostics,_options){var _a21;for(const reference of document.references){const linkingError=reference.error;if(linkingError){const info={node:linkingError.info.container,range:(_a21=reference.$refNode)==null?void 0:_a21.range,property:linkingError.info.property,index:linkingError.info.index,data:{code:DocumentValidator.LinkingError,containerType:linkingError.info.container.$type,property:linkingError.info.property,refText:linkingError.info.reference.$refText}};diagnostics.push(this.toDiagnostic("error",linkingError.message,info))}}}async validateAst(rootNode,options,cancelToken=cancellationExports.CancellationToken.None){const validationItems=[],acceptor=(severity,message,info)=>{validationItems.push(this.toDiagnostic(severity,message,info))};return await this.validateAstBefore(rootNode,options,acceptor,cancelToken),await this.validateAstNodes(rootNode,options,acceptor,cancelToken),await this.validateAstAfter(rootNode,options,acceptor,cancelToken),validationItems}async validateAstBefore(rootNode,options,acceptor,cancelToken=cancellationExports.CancellationToken.None){const checksBefore=this.validationRegistry.checksBefore;for(const checkBefore of checksBefore)await interruptAndCheck(cancelToken),await checkBefore(rootNode,acceptor,options.categories??[],cancelToken)}async validateAstNodes(rootNode,options,acceptor,cancelToken=cancellationExports.CancellationToken.None){var _a21;if((_a21=this.profiler)!=null&&_a21.isActive("validating")){const task=this.profiler.createTask("validating",this.languageId);task.start();try{const nodes=streamAst(rootNode).iterator();for(const node of nodes){task.startSubTask(node.$type);const nodeOptions=this.validateSingleNodeOptions(node,options);if(nodeOptions.validateNode)try{const checks=this.validationRegistry.getChecks(node.$type,options.categories);for(const check of checks)await check(node,acceptor,cancelToken)}finally{task.stopSubTask(node.$type)}nodeOptions.validateChildren||nodes.prune()}}finally{task.stop()}}else{const nodes=streamAst(rootNode).iterator();for(const node of nodes){await interruptAndCheck(cancelToken);const nodeOptions=this.validateSingleNodeOptions(node,options);if(nodeOptions.validateNode){const checks=this.validationRegistry.getChecks(node.$type,options.categories);for(const check of checks)await check(node,acceptor,cancelToken)}nodeOptions.validateChildren||nodes.prune()}}}validateSingleNodeOptions(_node,_options){return VALIDATE_EACH_NODE}async validateAstAfter(rootNode,options,acceptor,cancelToken=cancellationExports.CancellationToken.None){const checksAfter=this.validationRegistry.checksAfter;for(const checkAfter of checksAfter)await interruptAndCheck(cancelToken),await checkAfter(rootNode,acceptor,options.categories??[],cancelToken)}toDiagnostic(severity,message,info){return{message,range:getDiagnosticRange(info),severity:toDiagnosticSeverity(severity),code:info.code,codeDescription:info.codeDescription,tags:info.tags,relatedInformation:info.relatedInformation,data:info.data,source:this.getSource()}}getSource(){return this.metadata.languageId}}function getDiagnosticRange(info){if(info.range)return info.range;let cstNode;return typeof info.property=="string"?cstNode=findNodeForProperty(info.node.$cstNode,info.property,info.index):typeof info.keyword=="string"&&(cstNode=findNodeForKeyword(info.node.$cstNode,info.keyword,info.index)),cstNode??(cstNode=info.node.$cstNode),cstNode?cstNode.range:{start:{line:0,character:0},end:{line:0,character:0}}}function toDiagnosticSeverity(severity){switch(severity){case"error":return 1;case"warning":return 2;case"info":return 3;case"hint":return 4;default:throw new Error("Invalid diagnostic severity: "+severity)}}function toDiagnosticData(severity){switch(severity){case"error":return diagnosticData(DocumentValidator.LexingError);case"warning":return diagnosticData(DocumentValidator.LexingWarning);case"info":return diagnosticData(DocumentValidator.LexingInfo);case"hint":return diagnosticData(DocumentValidator.LexingHint);default:throw new Error("Invalid diagnostic severity: "+severity)}}var DocumentValidator;(function(DocumentValidator2){DocumentValidator2.LexingError="lexing-error",DocumentValidator2.LexingWarning="lexing-warning",DocumentValidator2.LexingInfo="lexing-info",DocumentValidator2.LexingHint="lexing-hint",DocumentValidator2.ParsingError="parsing-error",DocumentValidator2.LinkingError="linking-error"})(DocumentValidator||(DocumentValidator={}));class DefaultAstNodeDescriptionProvider{constructor(services){this.astNodeLocator=services.workspace.AstNodeLocator,this.nameProvider=services.references.NameProvider}createDescription(node,name,document){const doc=document??getDocument(node);name??(name=this.nameProvider.getName(node));const path=this.astNodeLocator.getAstNodePath(node);if(!name)throw new Error(`Node at path ${path} has no name.`);let nameNodeSegment;const nameSegmentGetter=()=>nameNodeSegment??(nameNodeSegment=toDocumentSegment(this.nameProvider.getNameNode(node)??node.$cstNode));return{node,name,get nameSegment(){return nameSegmentGetter()},selectionSegment:toDocumentSegment(node.$cstNode),type:node.$type,documentUri:doc.uri,path}}}class DefaultReferenceDescriptionProvider{constructor(services){this.nodeLocator=services.workspace.AstNodeLocator}async createDescriptions(document,cancelToken=cancellationExports.CancellationToken.None){const descr=[],rootNode=document.parseResult.value;for(const astNode of streamAst(rootNode))await interruptAndCheck(cancelToken),streamReferences(astNode).forEach(refInfo=>{refInfo.reference.error||descr.push(...this.createInfoDescriptions(refInfo))});return descr}createInfoDescriptions(refInfo){const reference=refInfo.reference;if(reference.error||!reference.$refNode)return[];let items=[];isReference(reference)&&reference.$nodeDescription?items=[reference.$nodeDescription]:isMultiReference(reference)&&(items=reference.items.map(e=>e.$nodeDescription).filter(e=>e!==void 0));const sourceUri=getDocument(refInfo.container).uri,sourcePath=this.nodeLocator.getAstNodePath(refInfo.container),descriptions=[],segment=toDocumentSegment(reference.$refNode);for(const item of items)descriptions.push({sourceUri,sourcePath,targetUri:item.documentUri,targetPath:item.path,segment,local:UriUtils.equals(item.documentUri,sourceUri)});return descriptions}}class DefaultAstNodeLocator{constructor(){this.segmentSeparator="/",this.indexSeparator="@"}getAstNodePath(node){if(node.$container){const containerPath=this.getAstNodePath(node.$container),newSegment=this.getPathSegment(node);return containerPath+this.segmentSeparator+newSegment}return""}getPathSegment({$containerProperty,$containerIndex}){if(!$containerProperty)throw new Error("Missing '$containerProperty' in AST node.");return $containerIndex!==void 0?$containerProperty+this.indexSeparator+$containerIndex:$containerProperty}getAstNode(node,path){return path.split(this.segmentSeparator).reduce((previousValue,currentValue)=>{if(!previousValue||currentValue.length===0)return previousValue;const propertyIndex=currentValue.indexOf(this.indexSeparator);if(propertyIndex>0){const property=currentValue.substring(0,propertyIndex),arrayIndex=parseInt(currentValue.substring(propertyIndex+1)),array=previousValue[property];return array==null?void 0:array[arrayIndex]}return previousValue[currentValue]},node)}}var eventsExports=requireEvents();class DefaultConfigurationProvider{constructor(services){this._ready=new Deferred,this.onConfigurationSectionUpdateEmitter=new eventsExports.Emitter,this.settings={},this.workspaceConfig=!1,this.serviceRegistry=services.ServiceRegistry}get ready(){return this._ready.promise}initialize(params){var _a21;this.workspaceConfig=((_a21=params.capabilities.workspace)==null?void 0:_a21.configuration)??!1}async initialized(params){if(this.workspaceConfig){if(params.register){const languages=this.serviceRegistry.all;params.register({section:languages.map(lang=>this.toSectionName(lang.LanguageMetaData.languageId))})}if(params.fetchConfiguration){const configToUpdate=this.serviceRegistry.all.map(lang=>({section:this.toSectionName(lang.LanguageMetaData.languageId)})),configs=await params.fetchConfiguration(configToUpdate);configToUpdate.forEach((conf,idx)=>{this.updateSectionConfiguration(conf.section,configs[idx])})}}this._ready.resolve()}updateConfiguration(change){typeof change.settings!="object"||change.settings===null||Object.entries(change.settings).forEach(([section,configuration])=>{this.updateSectionConfiguration(section,configuration),this.onConfigurationSectionUpdateEmitter.fire({section,configuration})})}updateSectionConfiguration(section,configuration){this.settings[section]=configuration}async getConfiguration(language,configuration){await this.ready;const sectionName=this.toSectionName(language);if(this.settings[sectionName])return this.settings[sectionName][configuration]}toSectionName(languageId){return`${languageId}`}get onConfigurationSectionUpdate(){return this.onConfigurationSectionUpdateEmitter.event}}var main$1={},main={},ril={},api$1={},messages$1={},hasRequiredMessages$1;function requireMessages$1(){if(hasRequiredMessages$1)return messages$1;hasRequiredMessages$1=1,Object.defineProperty(messages$1,"__esModule",{value:!0}),messages$1.Message=messages$1.NotificationType9=messages$1.NotificationType8=messages$1.NotificationType7=messages$1.NotificationType6=messages$1.NotificationType5=messages$1.NotificationType4=messages$1.NotificationType3=messages$1.NotificationType2=messages$1.NotificationType1=messages$1.NotificationType0=messages$1.NotificationType=messages$1.RequestType9=messages$1.RequestType8=messages$1.RequestType7=messages$1.RequestType6=messages$1.RequestType5=messages$1.RequestType4=messages$1.RequestType3=messages$1.RequestType2=messages$1.RequestType1=messages$1.RequestType=messages$1.RequestType0=messages$1.AbstractMessageSignature=messages$1.ParameterStructures=messages$1.ResponseError=messages$1.ErrorCodes=void 0;const is2=requireIs$1();var ErrorCodes;(function(ErrorCodes2){ErrorCodes2.ParseError=-32700,ErrorCodes2.InvalidRequest=-32600,ErrorCodes2.MethodNotFound=-32601,ErrorCodes2.InvalidParams=-32602,ErrorCodes2.InternalError=-32603,ErrorCodes2.jsonrpcReservedErrorRangeStart=-32099,ErrorCodes2.serverErrorStart=-32099,ErrorCodes2.MessageWriteError=-32099,ErrorCodes2.MessageReadError=-32098,ErrorCodes2.PendingResponseRejected=-32097,ErrorCodes2.ConnectionInactive=-32096,ErrorCodes2.ServerNotInitialized=-32002,ErrorCodes2.UnknownErrorCode=-32001,ErrorCodes2.jsonrpcReservedErrorRangeEnd=-32e3,ErrorCodes2.serverErrorEnd=-32e3})(ErrorCodes||(messages$1.ErrorCodes=ErrorCodes={}));class ResponseError extends Error{constructor(code,message,data){super(message),this.code=is2.number(code)?code:ErrorCodes.UnknownErrorCode,this.data=data,Object.setPrototypeOf(this,ResponseError.prototype)}toJson(){const result={code:this.code,message:this.message};return this.data!==void 0&&(result.data=this.data),result}}messages$1.ResponseError=ResponseError;class ParameterStructures{constructor(kind){this.kind=kind}static is(value){return value===ParameterStructures.auto||value===ParameterStructures.byName||value===ParameterStructures.byPosition}toString(){return this.kind}}messages$1.ParameterStructures=ParameterStructures,ParameterStructures.auto=new ParameterStructures("auto"),ParameterStructures.byPosition=new ParameterStructures("byPosition"),ParameterStructures.byName=new ParameterStructures("byName");class AbstractMessageSignature{constructor(method,numberOfParams){this.method=method,this.numberOfParams=numberOfParams}get parameterStructures(){return ParameterStructures.auto}}messages$1.AbstractMessageSignature=AbstractMessageSignature;class RequestType0 extends AbstractMessageSignature{constructor(method){super(method,0)}}messages$1.RequestType0=RequestType0;class RequestType extends AbstractMessageSignature{constructor(method,_parameterStructures=ParameterStructures.auto){super(method,1),this._parameterStructures=_parameterStructures}get parameterStructures(){return this._parameterStructures}}messages$1.RequestType=RequestType;class RequestType1 extends AbstractMessageSignature{constructor(method,_parameterStructures=ParameterStructures.auto){super(method,1),this._parameterStructures=_parameterStructures}get parameterStructures(){return this._parameterStructures}}messages$1.RequestType1=RequestType1;class RequestType2 extends AbstractMessageSignature{constructor(method){super(method,2)}}messages$1.RequestType2=RequestType2;class RequestType3 extends AbstractMessageSignature{constructor(method){super(method,3)}}messages$1.RequestType3=RequestType3;class RequestType4 extends AbstractMessageSignature{constructor(method){super(method,4)}}messages$1.RequestType4=RequestType4;class RequestType5 extends AbstractMessageSignature{constructor(method){super(method,5)}}messages$1.RequestType5=RequestType5;class RequestType6 extends AbstractMessageSignature{constructor(method){super(method,6)}}messages$1.RequestType6=RequestType6;class RequestType7 extends AbstractMessageSignature{constructor(method){super(method,7)}}messages$1.RequestType7=RequestType7;class RequestType8 extends AbstractMessageSignature{constructor(method){super(method,8)}}messages$1.RequestType8=RequestType8;class RequestType9 extends AbstractMessageSignature{constructor(method){super(method,9)}}messages$1.RequestType9=RequestType9;class NotificationType extends AbstractMessageSignature{constructor(method,_parameterStructures=ParameterStructures.auto){super(method,1),this._parameterStructures=_parameterStructures}get parameterStructures(){return this._parameterStructures}}messages$1.NotificationType=NotificationType;class NotificationType0 extends AbstractMessageSignature{constructor(method){super(method,0)}}messages$1.NotificationType0=NotificationType0;class NotificationType1 extends AbstractMessageSignature{constructor(method,_parameterStructures=ParameterStructures.auto){super(method,1),this._parameterStructures=_parameterStructures}get parameterStructures(){return this._parameterStructures}}messages$1.NotificationType1=NotificationType1;class NotificationType2 extends AbstractMessageSignature{constructor(method){super(method,2)}}messages$1.NotificationType2=NotificationType2;class NotificationType3 extends AbstractMessageSignature{constructor(method){super(method,3)}}messages$1.NotificationType3=NotificationType3;class NotificationType4 extends AbstractMessageSignature{constructor(method){super(method,4)}}messages$1.NotificationType4=NotificationType4;class NotificationType5 extends AbstractMessageSignature{constructor(method){super(method,5)}}messages$1.NotificationType5=NotificationType5;class NotificationType6 extends AbstractMessageSignature{constructor(method){super(method,6)}}messages$1.NotificationType6=NotificationType6;class NotificationType7 extends AbstractMessageSignature{constructor(method){super(method,7)}}messages$1.NotificationType7=NotificationType7;class NotificationType8 extends AbstractMessageSignature{constructor(method){super(method,8)}}messages$1.NotificationType8=NotificationType8;class NotificationType9 extends AbstractMessageSignature{constructor(method){super(method,9)}}messages$1.NotificationType9=NotificationType9;var Message;return(function(Message2){function isRequest(message){const candidate=message;return candidate&&is2.string(candidate.method)&&(is2.string(candidate.id)||is2.number(candidate.id))}Message2.isRequest=isRequest;function isNotification(message){const candidate=message;return candidate&&is2.string(candidate.method)&&message.id===void 0}Message2.isNotification=isNotification;function isResponse(message){const candidate=message;return candidate&&(candidate.result!==void 0||!!candidate.error)&&(is2.string(candidate.id)||is2.number(candidate.id)||candidate.id===null)}Message2.isResponse=isResponse})(Message||(messages$1.Message=Message={})),messages$1}var linkedMap={},hasRequiredLinkedMap;function requireLinkedMap(){if(hasRequiredLinkedMap)return linkedMap;hasRequiredLinkedMap=1;var _a21;Object.defineProperty(linkedMap,"__esModule",{value:!0}),linkedMap.LRUCache=linkedMap.LinkedMap=linkedMap.Touch=void 0;var Touch;(function(Touch2){Touch2.None=0,Touch2.First=1,Touch2.AsOld=Touch2.First,Touch2.Last=2,Touch2.AsNew=Touch2.Last})(Touch||(linkedMap.Touch=Touch={}));class LinkedMap{constructor(){this[_a21]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){var _a22;return(_a22=this._head)==null?void 0:_a22.value}get last(){var _a22;return(_a22=this._tail)==null?void 0:_a22.value}has(key){return this._map.has(key)}get(key,touch=Touch.None){const item=this._map.get(key);if(item)return touch!==Touch.None&&this.touch(item,touch),item.value}set(key,value,touch=Touch.None){let item=this._map.get(key);if(item)item.value=value,touch!==Touch.None&&this.touch(item,touch);else{switch(item={key,value,next:void 0,previous:void 0},touch){case Touch.None:this.addItemLast(item);break;case Touch.First:this.addItemFirst(item);break;case Touch.Last:this.addItemLast(item);break;default:this.addItemLast(item);break}this._map.set(key,item),this._size++}return this}delete(key){return!!this.remove(key)}remove(key){const item=this._map.get(key);if(item)return this._map.delete(key),this.removeItem(item),this._size--,item.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");const item=this._head;return this._map.delete(item.key),this.removeItem(item),this._size--,item.value}forEach(callbackfn,thisArg){const state=this._state;let current=this._head;for(;current;){if(thisArg?callbackfn.bind(thisArg)(current.value,current.key,this):callbackfn(current.value,current.key,this),this._state!==state)throw new Error("LinkedMap got modified during iteration.");current=current.next}}keys(){const state=this._state;let current=this._head;const iterator={[Symbol.iterator]:()=>iterator,next:()=>{if(this._state!==state)throw new Error("LinkedMap got modified during iteration.");if(current){const result={value:current.key,done:!1};return current=current.next,result}else return{value:void 0,done:!0}}};return iterator}values(){const state=this._state;let current=this._head;const iterator={[Symbol.iterator]:()=>iterator,next:()=>{if(this._state!==state)throw new Error("LinkedMap got modified during iteration.");if(current){const result={value:current.value,done:!1};return current=current.next,result}else return{value:void 0,done:!0}}};return iterator}entries(){const state=this._state;let current=this._head;const iterator={[Symbol.iterator]:()=>iterator,next:()=>{if(this._state!==state)throw new Error("LinkedMap got modified during iteration.");if(current){const result={value:[current.key,current.value],done:!1};return current=current.next,result}else return{value:void 0,done:!0}}};return iterator}[(_a21=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(newSize){if(newSize>=this.size)return;if(newSize===0){this.clear();return}let current=this._head,currentSize=this.size;for(;current&&currentSize>newSize;)this._map.delete(current.key),current=current.next,currentSize--;this._head=current,this._size=currentSize,current&&(current.previous=void 0),this._state++}addItemFirst(item){if(!this._head&&!this._tail)this._tail=item;else if(this._head)item.next=this._head,this._head.previous=item;else throw new Error("Invalid list");this._head=item,this._state++}addItemLast(item){if(!this._head&&!this._tail)this._head=item;else if(this._tail)item.previous=this._tail,this._tail.next=item;else throw new Error("Invalid list");this._tail=item,this._state++}removeItem(item){if(item===this._head&&item===this._tail)this._head=void 0,this._tail=void 0;else if(item===this._head){if(!item.next)throw new Error("Invalid list");item.next.previous=void 0,this._head=item.next}else if(item===this._tail){if(!item.previous)throw new Error("Invalid list");item.previous.next=void 0,this._tail=item.previous}else{const next=item.next,previous=item.previous;if(!next||!previous)throw new Error("Invalid list");next.previous=previous,previous.next=next}item.next=void 0,item.previous=void 0,this._state++}touch(item,touch){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(touch!==Touch.First&&touch!==Touch.Last)){if(touch===Touch.First){if(item===this._head)return;const next=item.next,previous=item.previous;item===this._tail?(previous.next=void 0,this._tail=previous):(next.previous=previous,previous.next=next),item.previous=void 0,item.next=this._head,this._head.previous=item,this._head=item,this._state++}else if(touch===Touch.Last){if(item===this._tail)return;const next=item.next,previous=item.previous;item===this._head?(next.previous=void 0,this._head=next):(next.previous=previous,previous.next=next),item.next=void 0,item.previous=this._tail,this._tail.next=item,this._tail=item,this._state++}}}toJSON(){const data=[];return this.forEach((value,key)=>{data.push([key,value])}),data}fromJSON(data){this.clear();for(const[key,value]of data)this.set(key,value)}}linkedMap.LinkedMap=LinkedMap;class LRUCache extends LinkedMap{constructor(limit,ratio=1){super(),this._limit=limit,this._ratio=Math.min(Math.max(0,ratio),1)}get limit(){return this._limit}set limit(limit){this._limit=limit,this.checkTrim()}get ratio(){return this._ratio}set ratio(ratio){this._ratio=Math.min(Math.max(0,ratio),1),this.checkTrim()}get(key,touch=Touch.AsNew){return super.get(key,touch)}peek(key){return super.get(key,Touch.None)}set(key,value){return super.set(key,value,Touch.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}}return linkedMap.LRUCache=LRUCache,linkedMap}var disposable={},hasRequiredDisposable;function requireDisposable(){if(hasRequiredDisposable)return disposable;hasRequiredDisposable=1,Object.defineProperty(disposable,"__esModule",{value:!0}),disposable.Disposable=void 0;var Disposable2;return(function(Disposable3){function create(func){return{dispose:func}}Disposable3.create=create})(Disposable2||(disposable.Disposable=Disposable2={})),disposable}var sharedArrayCancellation={},hasRequiredSharedArrayCancellation;function requireSharedArrayCancellation(){if(hasRequiredSharedArrayCancellation)return sharedArrayCancellation;hasRequiredSharedArrayCancellation=1,Object.defineProperty(sharedArrayCancellation,"__esModule",{value:!0}),sharedArrayCancellation.SharedArrayReceiverStrategy=sharedArrayCancellation.SharedArraySenderStrategy=void 0;const cancellation_1=requireCancellation();var CancellationState;(function(CancellationState2){CancellationState2.Continue=0,CancellationState2.Cancelled=1})(CancellationState||(CancellationState={}));class SharedArraySenderStrategy{constructor(){this.buffers=new Map}enableCancellation(request){if(request.id===null)return;const buffer=new SharedArrayBuffer(4),data=new Int32Array(buffer,0,1);data[0]=CancellationState.Continue,this.buffers.set(request.id,buffer),request.$cancellationData=buffer}async sendCancellation(_conn,id){const buffer=this.buffers.get(id);if(buffer===void 0)return;const data=new Int32Array(buffer,0,1);Atomics.store(data,0,CancellationState.Cancelled)}cleanup(id){this.buffers.delete(id)}dispose(){this.buffers.clear()}}sharedArrayCancellation.SharedArraySenderStrategy=SharedArraySenderStrategy;class SharedArrayBufferCancellationToken{constructor(buffer){this.data=new Int32Array(buffer,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===CancellationState.Cancelled}get onCancellationRequested(){throw new Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}}class SharedArrayBufferCancellationTokenSource{constructor(buffer){this.token=new SharedArrayBufferCancellationToken(buffer)}cancel(){}dispose(){}}class SharedArrayReceiverStrategy{constructor(){this.kind="request"}createCancellationTokenSource(request){const buffer=request.$cancellationData;return buffer===void 0?new cancellation_1.CancellationTokenSource:new SharedArrayBufferCancellationTokenSource(buffer)}}return sharedArrayCancellation.SharedArrayReceiverStrategy=SharedArrayReceiverStrategy,sharedArrayCancellation}var messageReader={},semaphore={},hasRequiredSemaphore;function requireSemaphore(){if(hasRequiredSemaphore)return semaphore;hasRequiredSemaphore=1,Object.defineProperty(semaphore,"__esModule",{value:!0}),semaphore.Semaphore=void 0;const ral_1=requireRal();class Semaphore{constructor(capacity=1){if(capacity<=0)throw new Error("Capacity must be greater than 0");this._capacity=capacity,this._active=0,this._waiting=[]}lock(thunk){return new Promise((resolve,reject)=>{this._waiting.push({thunk,resolve,reject}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,ral_1.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;const next=this._waiting.shift();if(this._active++,this._active>this._capacity)throw new Error("To many thunks active");try{const result=next.thunk();result instanceof Promise?result.then(value=>{this._active--,next.resolve(value),this.runNext()},err=>{this._active--,next.reject(err),this.runNext()}):(this._active--,next.resolve(result),this.runNext())}catch(err){this._active--,next.reject(err),this.runNext()}}}return semaphore.Semaphore=Semaphore,semaphore}var hasRequiredMessageReader;function requireMessageReader(){if(hasRequiredMessageReader)return messageReader;hasRequiredMessageReader=1,Object.defineProperty(messageReader,"__esModule",{value:!0}),messageReader.ReadableStreamMessageReader=messageReader.AbstractMessageReader=messageReader.MessageReader=void 0;const ral_1=requireRal(),Is2=requireIs$1(),events_1=requireEvents(),semaphore_1=requireSemaphore();var MessageReader;(function(MessageReader2){function is2(value){let candidate=value;return candidate&&Is2.func(candidate.listen)&&Is2.func(candidate.dispose)&&Is2.func(candidate.onError)&&Is2.func(candidate.onClose)&&Is2.func(candidate.onPartialMessage)}MessageReader2.is=is2})(MessageReader||(messageReader.MessageReader=MessageReader={}));class AbstractMessageReader{constructor(){this.errorEmitter=new events_1.Emitter,this.closeEmitter=new events_1.Emitter,this.partialMessageEmitter=new events_1.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(error){this.errorEmitter.fire(this.asError(error))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(info){this.partialMessageEmitter.fire(info)}asError(error){return error instanceof Error?error:new Error(`Reader received error. Reason: ${Is2.string(error.message)?error.message:"unknown"}`)}}messageReader.AbstractMessageReader=AbstractMessageReader;var ResolvedMessageReaderOptions;(function(ResolvedMessageReaderOptions2){function fromOptions(options){let charset,contentDecoder;const contentDecoders=new Map;let contentTypeDecoder;const contentTypeDecoders=new Map;if(options===void 0||typeof options=="string")charset=options??"utf-8";else{if(charset=options.charset??"utf-8",options.contentDecoder!==void 0&&(contentDecoder=options.contentDecoder,contentDecoders.set(contentDecoder.name,contentDecoder)),options.contentDecoders!==void 0)for(const decoder of options.contentDecoders)contentDecoders.set(decoder.name,decoder);if(options.contentTypeDecoder!==void 0&&(contentTypeDecoder=options.contentTypeDecoder,contentTypeDecoders.set(contentTypeDecoder.name,contentTypeDecoder)),options.contentTypeDecoders!==void 0)for(const decoder of options.contentTypeDecoders)contentTypeDecoders.set(decoder.name,decoder)}return contentTypeDecoder===void 0&&(contentTypeDecoder=(0,ral_1.default)().applicationJson.decoder,contentTypeDecoders.set(contentTypeDecoder.name,contentTypeDecoder)),{charset,contentDecoder,contentDecoders,contentTypeDecoder,contentTypeDecoders}}ResolvedMessageReaderOptions2.fromOptions=fromOptions})(ResolvedMessageReaderOptions||(ResolvedMessageReaderOptions={}));class ReadableStreamMessageReader extends AbstractMessageReader{constructor(readable,options){super(),this.readable=readable,this.options=ResolvedMessageReaderOptions.fromOptions(options),this.buffer=(0,ral_1.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new semaphore_1.Semaphore(1)}set partialMessageTimeout(timeout){this._partialMessageTimeout=timeout}get partialMessageTimeout(){return this._partialMessageTimeout}listen(callback){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=callback;const result=this.readable.onData(data=>{this.onData(data)});return this.readable.onError(error=>this.fireError(error)),this.readable.onClose(()=>this.fireClose()),result}onData(data){try{for(this.buffer.append(data);;){if(this.nextMessageLength===-1){const headers=this.buffer.tryReadHeaders(!0);if(!headers)return;const contentLength=headers.get("content-length");if(!contentLength){this.fireError(new Error(`Header must provide a Content-Length property.
122
+ ${JSON.stringify(Object.fromEntries(headers))}`));return}const length=parseInt(contentLength);if(isNaN(length)){this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`));return}this.nextMessageLength=length}const body=this.buffer.tryReadBody(this.nextMessageLength);if(body===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{const bytes=this.options.contentDecoder!==void 0?await this.options.contentDecoder.decode(body):body,message=await this.options.contentTypeDecoder.decode(bytes,this.options);this.callback(message)}).catch(error=>{this.fireError(error)})}}catch(error){this.fireError(error)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,ral_1.default)().timer.setTimeout((token,timeout)=>{this.partialMessageTimer=void 0,token===this.messageToken&&(this.firePartialMessage({messageToken:token,waitingTime:timeout}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}}return messageReader.ReadableStreamMessageReader=ReadableStreamMessageReader,messageReader}var messageWriter={},hasRequiredMessageWriter;function requireMessageWriter(){if(hasRequiredMessageWriter)return messageWriter;hasRequiredMessageWriter=1,Object.defineProperty(messageWriter,"__esModule",{value:!0}),messageWriter.WriteableStreamMessageWriter=messageWriter.AbstractMessageWriter=messageWriter.MessageWriter=void 0;const ral_1=requireRal(),Is2=requireIs$1(),semaphore_1=requireSemaphore(),events_1=requireEvents(),ContentLength="Content-Length: ",CRLF=`\r
123
+ `;var MessageWriter;(function(MessageWriter2){function is2(value){let candidate=value;return candidate&&Is2.func(candidate.dispose)&&Is2.func(candidate.onClose)&&Is2.func(candidate.onError)&&Is2.func(candidate.write)}MessageWriter2.is=is2})(MessageWriter||(messageWriter.MessageWriter=MessageWriter={}));class AbstractMessageWriter{constructor(){this.errorEmitter=new events_1.Emitter,this.closeEmitter=new events_1.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(error,message,count){this.errorEmitter.fire([this.asError(error),message,count])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(error){return error instanceof Error?error:new Error(`Writer received error. Reason: ${Is2.string(error.message)?error.message:"unknown"}`)}}messageWriter.AbstractMessageWriter=AbstractMessageWriter;var ResolvedMessageWriterOptions;(function(ResolvedMessageWriterOptions2){function fromOptions(options){return options===void 0||typeof options=="string"?{charset:options??"utf-8",contentTypeEncoder:(0,ral_1.default)().applicationJson.encoder}:{charset:options.charset??"utf-8",contentEncoder:options.contentEncoder,contentTypeEncoder:options.contentTypeEncoder??(0,ral_1.default)().applicationJson.encoder}}ResolvedMessageWriterOptions2.fromOptions=fromOptions})(ResolvedMessageWriterOptions||(ResolvedMessageWriterOptions={}));class WriteableStreamMessageWriter extends AbstractMessageWriter{constructor(writable,options){super(),this.writable=writable,this.options=ResolvedMessageWriterOptions.fromOptions(options),this.errorCount=0,this.writeSemaphore=new semaphore_1.Semaphore(1),this.writable.onError(error=>this.fireError(error)),this.writable.onClose(()=>this.fireClose())}async write(msg){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(msg,this.options).then(buffer=>this.options.contentEncoder!==void 0?this.options.contentEncoder.encode(buffer):buffer).then(buffer=>{const headers=[];return headers.push(ContentLength,buffer.byteLength.toString(),CRLF),headers.push(CRLF),this.doWrite(msg,headers,buffer)},error=>{throw this.fireError(error),error}))}async doWrite(msg,headers,data){try{return await this.writable.write(headers.join(""),"ascii"),this.writable.write(data)}catch(error){return this.handleError(error,msg),Promise.reject(error)}}handleError(error,msg){this.errorCount++,this.fireError(error,msg,this.errorCount)}end(){this.writable.end()}}return messageWriter.WriteableStreamMessageWriter=WriteableStreamMessageWriter,messageWriter}var messageBuffer={},hasRequiredMessageBuffer;function requireMessageBuffer(){if(hasRequiredMessageBuffer)return messageBuffer;hasRequiredMessageBuffer=1,Object.defineProperty(messageBuffer,"__esModule",{value:!0}),messageBuffer.AbstractMessageBuffer=void 0;const CR=13,LF=10,CRLF=`\r
124
+ `;class AbstractMessageBuffer{constructor(encoding="utf-8"){this._encoding=encoding,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(chunk){const toAppend=typeof chunk=="string"?this.fromString(chunk,this._encoding):chunk;this._chunks.push(toAppend),this._totalLength+=toAppend.byteLength}tryReadHeaders(lowerCaseKeys=!1){if(this._chunks.length===0)return;let state=0,chunkIndex=0,offset=0,chunkBytesRead=0;row:for(;chunkIndex<this._chunks.length;){const chunk=this._chunks[chunkIndex];for(offset=0;offset<chunk.length;){switch(chunk[offset]){case CR:switch(state){case 0:state=1;break;case 2:state=3;break;default:state=0}break;case LF:switch(state){case 1:state=2;break;case 3:state=4,offset++;break row;default:state=0}break;default:state=0}offset++}chunkBytesRead+=chunk.byteLength,chunkIndex++}if(state!==4)return;const buffer=this._read(chunkBytesRead+offset),result=new Map,headers=this.toString(buffer,"ascii").split(CRLF);if(headers.length<2)return result;for(let i=0;i<headers.length-2;i++){const header=headers[i],index=header.indexOf(":");if(index===-1)throw new Error(`Message header must separate key and value using ':'
125
+ ${header}`);const key=header.substr(0,index),value=header.substr(index+1).trim();result.set(lowerCaseKeys?key.toLowerCase():key,value)}return result}tryReadBody(length){if(!(this._totalLength<length))return this._read(length)}get numberOfBytes(){return this._totalLength}_read(byteCount){if(byteCount===0)return this.emptyBuffer();if(byteCount>this._totalLength)throw new Error("Cannot read so many bytes!");if(this._chunks[0].byteLength===byteCount){const chunk=this._chunks[0];return this._chunks.shift(),this._totalLength-=byteCount,this.asNative(chunk)}if(this._chunks[0].byteLength>byteCount){const chunk=this._chunks[0],result2=this.asNative(chunk,byteCount);return this._chunks[0]=chunk.slice(byteCount),this._totalLength-=byteCount,result2}const result=this.allocNative(byteCount);let resultOffset=0,chunkIndex=0;for(;byteCount>0;){const chunk=this._chunks[chunkIndex];if(chunk.byteLength>byteCount){const chunkPart=chunk.slice(0,byteCount);result.set(chunkPart,resultOffset),resultOffset+=byteCount,this._chunks[chunkIndex]=chunk.slice(byteCount),this._totalLength-=byteCount,byteCount-=byteCount}else result.set(chunk,resultOffset),resultOffset+=chunk.byteLength,this._chunks.shift(),this._totalLength-=chunk.byteLength,byteCount-=chunk.byteLength}return result}}return messageBuffer.AbstractMessageBuffer=AbstractMessageBuffer,messageBuffer}var connection$1={},hasRequiredConnection$1;function requireConnection$1(){return hasRequiredConnection$1||(hasRequiredConnection$1=1,(function(exports$1){Object.defineProperty(exports$1,"__esModule",{value:!0}),exports$1.createMessageConnection=exports$1.ConnectionOptions=exports$1.MessageStrategy=exports$1.CancellationStrategy=exports$1.CancellationSenderStrategy=exports$1.CancellationReceiverStrategy=exports$1.RequestCancellationReceiverStrategy=exports$1.IdCancellationReceiverStrategy=exports$1.ConnectionStrategy=exports$1.ConnectionError=exports$1.ConnectionErrors=exports$1.LogTraceNotification=exports$1.SetTraceNotification=exports$1.TraceFormat=exports$1.TraceValues=exports$1.Trace=exports$1.NullLogger=exports$1.ProgressType=exports$1.ProgressToken=void 0;const ral_1=requireRal(),Is2=requireIs$1(),messages_1=requireMessages$1(),linkedMap_1=requireLinkedMap(),events_1=requireEvents(),cancellation_1=requireCancellation();var CancelNotification;(function(CancelNotification2){CancelNotification2.type=new messages_1.NotificationType("$/cancelRequest")})(CancelNotification||(CancelNotification={}));var ProgressToken;(function(ProgressToken2){function is2(value){return typeof value=="string"||typeof value=="number"}ProgressToken2.is=is2})(ProgressToken||(exports$1.ProgressToken=ProgressToken={}));var ProgressNotification;(function(ProgressNotification2){ProgressNotification2.type=new messages_1.NotificationType("$/progress")})(ProgressNotification||(ProgressNotification={}));class ProgressType{constructor(){}}exports$1.ProgressType=ProgressType;var StarRequestHandler;(function(StarRequestHandler2){function is2(value){return Is2.func(value)}StarRequestHandler2.is=is2})(StarRequestHandler||(StarRequestHandler={})),exports$1.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}});var Trace;(function(Trace2){Trace2[Trace2.Off=0]="Off",Trace2[Trace2.Messages=1]="Messages",Trace2[Trace2.Compact=2]="Compact",Trace2[Trace2.Verbose=3]="Verbose"})(Trace||(exports$1.Trace=Trace={}));var TraceValues;(function(TraceValues2){TraceValues2.Off="off",TraceValues2.Messages="messages",TraceValues2.Compact="compact",TraceValues2.Verbose="verbose"})(TraceValues||(exports$1.TraceValues=TraceValues={})),(function(Trace2){function fromString(value){if(!Is2.string(value))return Trace2.Off;switch(value=value.toLowerCase(),value){case"off":return Trace2.Off;case"messages":return Trace2.Messages;case"compact":return Trace2.Compact;case"verbose":return Trace2.Verbose;default:return Trace2.Off}}Trace2.fromString=fromString;function toString2(value){switch(value){case Trace2.Off:return"off";case Trace2.Messages:return"messages";case Trace2.Compact:return"compact";case Trace2.Verbose:return"verbose";default:return"off"}}Trace2.toString=toString2})(Trace||(exports$1.Trace=Trace={}));var TraceFormat;(function(TraceFormat2){TraceFormat2.Text="text",TraceFormat2.JSON="json"})(TraceFormat||(exports$1.TraceFormat=TraceFormat={})),(function(TraceFormat2){function fromString(value){return Is2.string(value)?(value=value.toLowerCase(),value==="json"?TraceFormat2.JSON:TraceFormat2.Text):TraceFormat2.Text}TraceFormat2.fromString=fromString})(TraceFormat||(exports$1.TraceFormat=TraceFormat={}));var SetTraceNotification;(function(SetTraceNotification2){SetTraceNotification2.type=new messages_1.NotificationType("$/setTrace")})(SetTraceNotification||(exports$1.SetTraceNotification=SetTraceNotification={}));var LogTraceNotification;(function(LogTraceNotification2){LogTraceNotification2.type=new messages_1.NotificationType("$/logTrace")})(LogTraceNotification||(exports$1.LogTraceNotification=LogTraceNotification={}));var ConnectionErrors;(function(ConnectionErrors2){ConnectionErrors2[ConnectionErrors2.Closed=1]="Closed",ConnectionErrors2[ConnectionErrors2.Disposed=2]="Disposed",ConnectionErrors2[ConnectionErrors2.AlreadyListening=3]="AlreadyListening"})(ConnectionErrors||(exports$1.ConnectionErrors=ConnectionErrors={}));class ConnectionError extends Error{constructor(code,message){super(message),this.code=code,Object.setPrototypeOf(this,ConnectionError.prototype)}}exports$1.ConnectionError=ConnectionError;var ConnectionStrategy;(function(ConnectionStrategy2){function is2(value){const candidate=value;return candidate&&Is2.func(candidate.cancelUndispatched)}ConnectionStrategy2.is=is2})(ConnectionStrategy||(exports$1.ConnectionStrategy=ConnectionStrategy={}));var IdCancellationReceiverStrategy;(function(IdCancellationReceiverStrategy2){function is2(value){const candidate=value;return candidate&&(candidate.kind===void 0||candidate.kind==="id")&&Is2.func(candidate.createCancellationTokenSource)&&(candidate.dispose===void 0||Is2.func(candidate.dispose))}IdCancellationReceiverStrategy2.is=is2})(IdCancellationReceiverStrategy||(exports$1.IdCancellationReceiverStrategy=IdCancellationReceiverStrategy={}));var RequestCancellationReceiverStrategy;(function(RequestCancellationReceiverStrategy2){function is2(value){const candidate=value;return candidate&&candidate.kind==="request"&&Is2.func(candidate.createCancellationTokenSource)&&(candidate.dispose===void 0||Is2.func(candidate.dispose))}RequestCancellationReceiverStrategy2.is=is2})(RequestCancellationReceiverStrategy||(exports$1.RequestCancellationReceiverStrategy=RequestCancellationReceiverStrategy={}));var CancellationReceiverStrategy;(function(CancellationReceiverStrategy2){CancellationReceiverStrategy2.Message=Object.freeze({createCancellationTokenSource(_){return new cancellation_1.CancellationTokenSource}});function is2(value){return IdCancellationReceiverStrategy.is(value)||RequestCancellationReceiverStrategy.is(value)}CancellationReceiverStrategy2.is=is2})(CancellationReceiverStrategy||(exports$1.CancellationReceiverStrategy=CancellationReceiverStrategy={}));var CancellationSenderStrategy;(function(CancellationSenderStrategy2){CancellationSenderStrategy2.Message=Object.freeze({sendCancellation(conn,id){return conn.sendNotification(CancelNotification.type,{id})},cleanup(_){}});function is2(value){const candidate=value;return candidate&&Is2.func(candidate.sendCancellation)&&Is2.func(candidate.cleanup)}CancellationSenderStrategy2.is=is2})(CancellationSenderStrategy||(exports$1.CancellationSenderStrategy=CancellationSenderStrategy={}));var CancellationStrategy;(function(CancellationStrategy2){CancellationStrategy2.Message=Object.freeze({receiver:CancellationReceiverStrategy.Message,sender:CancellationSenderStrategy.Message});function is2(value){const candidate=value;return candidate&&CancellationReceiverStrategy.is(candidate.receiver)&&CancellationSenderStrategy.is(candidate.sender)}CancellationStrategy2.is=is2})(CancellationStrategy||(exports$1.CancellationStrategy=CancellationStrategy={}));var MessageStrategy;(function(MessageStrategy2){function is2(value){const candidate=value;return candidate&&Is2.func(candidate.handleMessage)}MessageStrategy2.is=is2})(MessageStrategy||(exports$1.MessageStrategy=MessageStrategy={}));var ConnectionOptions;(function(ConnectionOptions2){function is2(value){const candidate=value;return candidate&&(CancellationStrategy.is(candidate.cancellationStrategy)||ConnectionStrategy.is(candidate.connectionStrategy)||MessageStrategy.is(candidate.messageStrategy))}ConnectionOptions2.is=is2})(ConnectionOptions||(exports$1.ConnectionOptions=ConnectionOptions={}));var ConnectionState;(function(ConnectionState2){ConnectionState2[ConnectionState2.New=1]="New",ConnectionState2[ConnectionState2.Listening=2]="Listening",ConnectionState2[ConnectionState2.Closed=3]="Closed",ConnectionState2[ConnectionState2.Disposed=4]="Disposed"})(ConnectionState||(ConnectionState={}));function createMessageConnection(messageReader2,messageWriter2,_logger,options){const logger=_logger!==void 0?_logger:exports$1.NullLogger;let sequenceNumber=0,notificationSequenceNumber=0,unknownResponseSequenceNumber=0;const version="2.0";let starRequestHandler;const requestHandlers=new Map;let starNotificationHandler;const notificationHandlers=new Map,progressHandlers=new Map;let timer2,messageQueue=new linkedMap_1.LinkedMap,responsePromises=new Map,knownCanceledRequests=new Set,requestTokens=new Map,trace=Trace.Off,traceFormat=TraceFormat.Text,tracer,state=ConnectionState.New;const errorEmitter=new events_1.Emitter,closeEmitter=new events_1.Emitter,unhandledNotificationEmitter=new events_1.Emitter,unhandledProgressEmitter=new events_1.Emitter,disposeEmitter=new events_1.Emitter,cancellationStrategy=options&&options.cancellationStrategy?options.cancellationStrategy:CancellationStrategy.Message;function createRequestQueueKey(id){if(id===null)throw new Error("Can't send requests with id null since the response can't be correlated.");return"req-"+id.toString()}function createResponseQueueKey(id){return id===null?"res-unknown-"+(++unknownResponseSequenceNumber).toString():"res-"+id.toString()}function createNotificationQueueKey(){return"not-"+(++notificationSequenceNumber).toString()}function addMessageToQueue(queue,message){messages_1.Message.isRequest(message)?queue.set(createRequestQueueKey(message.id),message):messages_1.Message.isResponse(message)?queue.set(createResponseQueueKey(message.id),message):queue.set(createNotificationQueueKey(),message)}function cancelUndispatched(_message){}function isListening(){return state===ConnectionState.Listening}function isClosed(){return state===ConnectionState.Closed}function isDisposed(){return state===ConnectionState.Disposed}function closeHandler(){(state===ConnectionState.New||state===ConnectionState.Listening)&&(state=ConnectionState.Closed,closeEmitter.fire(void 0))}function readErrorHandler(error){errorEmitter.fire([error,void 0,void 0])}function writeErrorHandler(data){errorEmitter.fire(data)}messageReader2.onClose(closeHandler),messageReader2.onError(readErrorHandler),messageWriter2.onClose(closeHandler),messageWriter2.onError(writeErrorHandler);function triggerMessageQueue(){timer2||messageQueue.size===0||(timer2=(0,ral_1.default)().timer.setImmediate(()=>{timer2=void 0,processMessageQueue()}))}function handleMessage(message){messages_1.Message.isRequest(message)?handleRequest(message):messages_1.Message.isNotification(message)?handleNotification(message):messages_1.Message.isResponse(message)?handleResponse(message):handleInvalidMessage(message)}function processMessageQueue(){if(messageQueue.size===0)return;const message=messageQueue.shift();try{const messageStrategy=options==null?void 0:options.messageStrategy;MessageStrategy.is(messageStrategy)?messageStrategy.handleMessage(message,handleMessage):handleMessage(message)}finally{triggerMessageQueue()}}const callback=message=>{try{if(messages_1.Message.isNotification(message)&&message.method===CancelNotification.type.method){const cancelId=message.params.id,key=createRequestQueueKey(cancelId),toCancel=messageQueue.get(key);if(messages_1.Message.isRequest(toCancel)){const strategy=options==null?void 0:options.connectionStrategy,response=strategy&&strategy.cancelUndispatched?strategy.cancelUndispatched(toCancel,cancelUndispatched):void 0;if(response&&(response.error!==void 0||response.result!==void 0)){messageQueue.delete(key),requestTokens.delete(cancelId),response.id=toCancel.id,traceSendingResponse(response,message.method,Date.now()),messageWriter2.write(response).catch(()=>logger.error("Sending response for canceled message failed."));return}}const cancellationToken=requestTokens.get(cancelId);if(cancellationToken!==void 0){cancellationToken.cancel(),traceReceivedNotification(message);return}else knownCanceledRequests.add(cancelId)}addMessageToQueue(messageQueue,message)}finally{triggerMessageQueue()}};function handleRequest(requestMessage){if(isDisposed())return;function reply(resultOrError,method,startTime2){const message={jsonrpc:version,id:requestMessage.id};resultOrError instanceof messages_1.ResponseError?message.error=resultOrError.toJson():message.result=resultOrError===void 0?null:resultOrError,traceSendingResponse(message,method,startTime2),messageWriter2.write(message).catch(()=>logger.error("Sending response failed."))}function replyError(error,method,startTime2){const message={jsonrpc:version,id:requestMessage.id,error:error.toJson()};traceSendingResponse(message,method,startTime2),messageWriter2.write(message).catch(()=>logger.error("Sending response failed."))}function replySuccess(result,method,startTime2){result===void 0&&(result=null);const message={jsonrpc:version,id:requestMessage.id,result};traceSendingResponse(message,method,startTime2),messageWriter2.write(message).catch(()=>logger.error("Sending response failed."))}traceReceivedRequest(requestMessage);const element=requestHandlers.get(requestMessage.method);let type,requestHandler;element&&(type=element.type,requestHandler=element.handler);const startTime=Date.now();if(requestHandler||starRequestHandler){const tokenKey=requestMessage.id??String(Date.now()),cancellationSource=IdCancellationReceiverStrategy.is(cancellationStrategy.receiver)?cancellationStrategy.receiver.createCancellationTokenSource(tokenKey):cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);requestMessage.id!==null&&knownCanceledRequests.has(requestMessage.id)&&cancellationSource.cancel(),requestMessage.id!==null&&requestTokens.set(tokenKey,cancellationSource);try{let handlerResult;if(requestHandler)if(requestMessage.params===void 0){if(type!==void 0&&type.numberOfParams!==0){replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams,`Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`),requestMessage.method,startTime);return}handlerResult=requestHandler(cancellationSource.token)}else if(Array.isArray(requestMessage.params)){if(type!==void 0&&type.parameterStructures===messages_1.ParameterStructures.byName){replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams,`Request ${requestMessage.method} defines parameters by name but received parameters by position`),requestMessage.method,startTime);return}handlerResult=requestHandler(...requestMessage.params,cancellationSource.token)}else{if(type!==void 0&&type.parameterStructures===messages_1.ParameterStructures.byPosition){replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams,`Request ${requestMessage.method} defines parameters by position but received parameters by name`),requestMessage.method,startTime);return}handlerResult=requestHandler(requestMessage.params,cancellationSource.token)}else starRequestHandler&&(handlerResult=starRequestHandler(requestMessage.method,requestMessage.params,cancellationSource.token));const promise=handlerResult;handlerResult?promise.then?promise.then(resultOrError=>{requestTokens.delete(tokenKey),reply(resultOrError,requestMessage.method,startTime)},error=>{requestTokens.delete(tokenKey),error instanceof messages_1.ResponseError?replyError(error,requestMessage.method,startTime):error&&Is2.string(error.message)?replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError,`Request ${requestMessage.method} failed with message: ${error.message}`),requestMessage.method,startTime):replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError,`Request ${requestMessage.method} failed unexpectedly without providing any details.`),requestMessage.method,startTime)}):(requestTokens.delete(tokenKey),reply(handlerResult,requestMessage.method,startTime)):(requestTokens.delete(tokenKey),replySuccess(handlerResult,requestMessage.method,startTime))}catch(error){requestTokens.delete(tokenKey),error instanceof messages_1.ResponseError?reply(error,requestMessage.method,startTime):error&&Is2.string(error.message)?replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError,`Request ${requestMessage.method} failed with message: ${error.message}`),requestMessage.method,startTime):replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError,`Request ${requestMessage.method} failed unexpectedly without providing any details.`),requestMessage.method,startTime)}}else replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound,`Unhandled method ${requestMessage.method}`),requestMessage.method,startTime)}function handleResponse(responseMessage){if(!isDisposed())if(responseMessage.id===null)responseMessage.error?logger.error(`Received response message without id: Error is:
126
+ ${JSON.stringify(responseMessage.error,void 0,4)}`):logger.error("Received response message without id. No further error information provided.");else{const key=responseMessage.id,responsePromise=responsePromises.get(key);if(traceReceivedResponse(responseMessage,responsePromise),responsePromise!==void 0){responsePromises.delete(key);try{if(responseMessage.error){const error=responseMessage.error;responsePromise.reject(new messages_1.ResponseError(error.code,error.message,error.data))}else if(responseMessage.result!==void 0)responsePromise.resolve(responseMessage.result);else throw new Error("Should never happen.")}catch(error){error.message?logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`):logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`)}}}}function handleNotification(message){if(isDisposed())return;let type,notificationHandler;if(message.method===CancelNotification.type.method){const cancelId=message.params.id;knownCanceledRequests.delete(cancelId),traceReceivedNotification(message);return}else{const element=notificationHandlers.get(message.method);element&&(notificationHandler=element.handler,type=element.type)}if(notificationHandler||starNotificationHandler)try{if(traceReceivedNotification(message),notificationHandler)if(message.params===void 0)type!==void 0&&type.numberOfParams!==0&&type.parameterStructures!==messages_1.ParameterStructures.byName&&logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`),notificationHandler();else if(Array.isArray(message.params)){const params=message.params;message.method===ProgressNotification.type.method&&params.length===2&&ProgressToken.is(params[0])?notificationHandler({token:params[0],value:params[1]}):(type!==void 0&&(type.parameterStructures===messages_1.ParameterStructures.byName&&logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`),type.numberOfParams!==message.params.length&&logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`)),notificationHandler(...params))}else type!==void 0&&type.parameterStructures===messages_1.ParameterStructures.byPosition&&logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`),notificationHandler(message.params);else starNotificationHandler&&starNotificationHandler(message.method,message.params)}catch(error){error.message?logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`):logger.error(`Notification handler '${message.method}' failed unexpectedly.`)}else unhandledNotificationEmitter.fire(message)}function handleInvalidMessage(message){if(!message){logger.error("Received empty message.");return}logger.error(`Received message which is neither a response nor a notification message:
127
+ ${JSON.stringify(message,null,4)}`);const responseMessage=message;if(Is2.string(responseMessage.id)||Is2.number(responseMessage.id)){const key=responseMessage.id,responseHandler=responsePromises.get(key);responseHandler&&responseHandler.reject(new Error("The received response has neither a result nor an error property."))}}function stringifyTrace(params){if(params!=null)switch(trace){case Trace.Verbose:return JSON.stringify(params,null,4);case Trace.Compact:return JSON.stringify(params);default:return}}function traceSendingRequest(message){if(!(trace===Trace.Off||!tracer))if(traceFormat===TraceFormat.Text){let data;(trace===Trace.Verbose||trace===Trace.Compact)&&message.params&&(data=`Params: ${stringifyTrace(message.params)}
128
+
129
+ `),tracer.log(`Sending request '${message.method} - (${message.id})'.`,data)}else logLSPMessage("send-request",message)}function traceSendingNotification(message){if(!(trace===Trace.Off||!tracer))if(traceFormat===TraceFormat.Text){let data;(trace===Trace.Verbose||trace===Trace.Compact)&&(message.params?data=`Params: ${stringifyTrace(message.params)}
130
+
131
+ `:data=`No parameters provided.
132
+
133
+ `),tracer.log(`Sending notification '${message.method}'.`,data)}else logLSPMessage("send-notification",message)}function traceSendingResponse(message,method,startTime){if(!(trace===Trace.Off||!tracer))if(traceFormat===TraceFormat.Text){let data;(trace===Trace.Verbose||trace===Trace.Compact)&&(message.error&&message.error.data?data=`Error data: ${stringifyTrace(message.error.data)}
134
+
135
+ `:message.result?data=`Result: ${stringifyTrace(message.result)}
136
+
137
+ `:message.error===void 0&&(data=`No result returned.
138
+
139
+ `)),tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now()-startTime}ms`,data)}else logLSPMessage("send-response",message)}function traceReceivedRequest(message){if(!(trace===Trace.Off||!tracer))if(traceFormat===TraceFormat.Text){let data;(trace===Trace.Verbose||trace===Trace.Compact)&&message.params&&(data=`Params: ${stringifyTrace(message.params)}
140
+
141
+ `),tracer.log(`Received request '${message.method} - (${message.id})'.`,data)}else logLSPMessage("receive-request",message)}function traceReceivedNotification(message){if(!(trace===Trace.Off||!tracer||message.method===LogTraceNotification.type.method))if(traceFormat===TraceFormat.Text){let data;(trace===Trace.Verbose||trace===Trace.Compact)&&(message.params?data=`Params: ${stringifyTrace(message.params)}
142
+
143
+ `:data=`No parameters provided.
144
+
145
+ `),tracer.log(`Received notification '${message.method}'.`,data)}else logLSPMessage("receive-notification",message)}function traceReceivedResponse(message,responsePromise){if(!(trace===Trace.Off||!tracer))if(traceFormat===TraceFormat.Text){let data;if((trace===Trace.Verbose||trace===Trace.Compact)&&(message.error&&message.error.data?data=`Error data: ${stringifyTrace(message.error.data)}
146
+
147
+ `:message.result?data=`Result: ${stringifyTrace(message.result)}
148
+
149
+ `:message.error===void 0&&(data=`No result returned.
150
+
151
+ `)),responsePromise){const error=message.error?` Request failed: ${message.error.message} (${message.error.code}).`:"";tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now()-responsePromise.timerStart}ms.${error}`,data)}else tracer.log(`Received response ${message.id} without active response promise.`,data)}else logLSPMessage("receive-response",message)}function logLSPMessage(type,message){if(!tracer||trace===Trace.Off)return;const lspMessage={isLSPMessage:!0,type,message,timestamp:Date.now()};tracer.log(lspMessage)}function throwIfClosedOrDisposed(){if(isClosed())throw new ConnectionError(ConnectionErrors.Closed,"Connection is closed.");if(isDisposed())throw new ConnectionError(ConnectionErrors.Disposed,"Connection is disposed.")}function throwIfListening(){if(isListening())throw new ConnectionError(ConnectionErrors.AlreadyListening,"Connection is already listening")}function throwIfNotListening(){if(!isListening())throw new Error("Call listen() first.")}function undefinedToNull(param){return param===void 0?null:param}function nullToUndefined(param){if(param!==null)return param}function isNamedParam(param){return param!=null&&!Array.isArray(param)&&typeof param=="object"}function computeSingleParam(parameterStructures,param){switch(parameterStructures){case messages_1.ParameterStructures.auto:return isNamedParam(param)?nullToUndefined(param):[undefinedToNull(param)];case messages_1.ParameterStructures.byName:if(!isNamedParam(param))throw new Error("Received parameters by name but param is not an object literal.");return nullToUndefined(param);case messages_1.ParameterStructures.byPosition:return[undefinedToNull(param)];default:throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`)}}function computeMessageParams(type,params){let result;const numberOfParams=type.numberOfParams;switch(numberOfParams){case 0:result=void 0;break;case 1:result=computeSingleParam(type.parameterStructures,params[0]);break;default:result=[];for(let i=0;i<params.length&&i<numberOfParams;i++)result.push(undefinedToNull(params[i]));if(params.length<numberOfParams)for(let i=params.length;i<numberOfParams;i++)result.push(null);break}return result}const connection2={sendNotification:(type,...args)=>{throwIfClosedOrDisposed();let method,messageParams;if(Is2.string(type)){method=type;const first2=args[0];let paramStart=0,parameterStructures=messages_1.ParameterStructures.auto;messages_1.ParameterStructures.is(first2)&&(paramStart=1,parameterStructures=first2);let paramEnd=args.length;const numberOfParams=paramEnd-paramStart;switch(numberOfParams){case 0:messageParams=void 0;break;case 1:messageParams=computeSingleParam(parameterStructures,args[paramStart]);break;default:if(parameterStructures===messages_1.ParameterStructures.byName)throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);messageParams=args.slice(paramStart,paramEnd).map(value=>undefinedToNull(value));break}}else{const params=args;method=type.method,messageParams=computeMessageParams(type,params)}const notificationMessage={jsonrpc:version,method,params:messageParams};return traceSendingNotification(notificationMessage),messageWriter2.write(notificationMessage).catch(error=>{throw logger.error("Sending notification failed."),error})},onNotification:(type,handler)=>{throwIfClosedOrDisposed();let method;return Is2.func(type)?starNotificationHandler=type:handler&&(Is2.string(type)?(method=type,notificationHandlers.set(type,{type:void 0,handler})):(method=type.method,notificationHandlers.set(type.method,{type,handler}))),{dispose:()=>{method!==void 0?notificationHandlers.delete(method):starNotificationHandler=void 0}}},onProgress:(_type,token,handler)=>{if(progressHandlers.has(token))throw new Error(`Progress handler for token ${token} already registered`);return progressHandlers.set(token,handler),{dispose:()=>{progressHandlers.delete(token)}}},sendProgress:(_type,token,value)=>connection2.sendNotification(ProgressNotification.type,{token,value}),onUnhandledProgress:unhandledProgressEmitter.event,sendRequest:(type,...args)=>{throwIfClosedOrDisposed(),throwIfNotListening();let method,messageParams,token;if(Is2.string(type)){method=type;const first2=args[0],last=args[args.length-1];let paramStart=0,parameterStructures=messages_1.ParameterStructures.auto;messages_1.ParameterStructures.is(first2)&&(paramStart=1,parameterStructures=first2);let paramEnd=args.length;cancellation_1.CancellationToken.is(last)&&(paramEnd=paramEnd-1,token=last);const numberOfParams=paramEnd-paramStart;switch(numberOfParams){case 0:messageParams=void 0;break;case 1:messageParams=computeSingleParam(parameterStructures,args[paramStart]);break;default:if(parameterStructures===messages_1.ParameterStructures.byName)throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);messageParams=args.slice(paramStart,paramEnd).map(value=>undefinedToNull(value));break}}else{const params=args;method=type.method,messageParams=computeMessageParams(type,params);const numberOfParams=type.numberOfParams;token=cancellation_1.CancellationToken.is(params[numberOfParams])?params[numberOfParams]:void 0}const id=sequenceNumber++;let disposable2;token&&(disposable2=token.onCancellationRequested(()=>{const p=cancellationStrategy.sender.sendCancellation(connection2,id);return p===void 0?(logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`),Promise.resolve()):p.catch(()=>{logger.log(`Sending cancellation messages for id ${id} failed`)})}));const requestMessage={jsonrpc:version,id,method,params:messageParams};return traceSendingRequest(requestMessage),typeof cancellationStrategy.sender.enableCancellation=="function"&&cancellationStrategy.sender.enableCancellation(requestMessage),new Promise(async(resolve,reject)=>{const resolveWithCleanup=r=>{resolve(r),cancellationStrategy.sender.cleanup(id),disposable2==null||disposable2.dispose()},rejectWithCleanup=r=>{reject(r),cancellationStrategy.sender.cleanup(id),disposable2==null||disposable2.dispose()},responsePromise={method,timerStart:Date.now(),resolve:resolveWithCleanup,reject:rejectWithCleanup};try{await messageWriter2.write(requestMessage),responsePromises.set(id,responsePromise)}catch(error){throw logger.error("Sending request failed."),responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError,error.message?error.message:"Unknown reason")),error}})},onRequest:(type,handler)=>{throwIfClosedOrDisposed();let method=null;return StarRequestHandler.is(type)?(method=void 0,starRequestHandler=type):Is2.string(type)?(method=null,handler!==void 0&&(method=type,requestHandlers.set(type,{handler,type:void 0}))):handler!==void 0&&(method=type.method,requestHandlers.set(type.method,{type,handler})),{dispose:()=>{method!==null&&(method!==void 0?requestHandlers.delete(method):starRequestHandler=void 0)}}},hasPendingResponse:()=>responsePromises.size>0,trace:async(_value,_tracer,sendNotificationOrTraceOptions)=>{let _sendNotification=!1,_traceFormat=TraceFormat.Text;sendNotificationOrTraceOptions!==void 0&&(Is2.boolean(sendNotificationOrTraceOptions)?_sendNotification=sendNotificationOrTraceOptions:(_sendNotification=sendNotificationOrTraceOptions.sendNotification||!1,_traceFormat=sendNotificationOrTraceOptions.traceFormat||TraceFormat.Text)),trace=_value,traceFormat=_traceFormat,trace===Trace.Off?tracer=void 0:tracer=_tracer,_sendNotification&&!isClosed()&&!isDisposed()&&await connection2.sendNotification(SetTraceNotification.type,{value:Trace.toString(_value)})},onError:errorEmitter.event,onClose:closeEmitter.event,onUnhandledNotification:unhandledNotificationEmitter.event,onDispose:disposeEmitter.event,end:()=>{messageWriter2.end()},dispose:()=>{if(isDisposed())return;state=ConnectionState.Disposed,disposeEmitter.fire(void 0);const error=new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(const promise of responsePromises.values())promise.reject(error);responsePromises=new Map,requestTokens=new Map,knownCanceledRequests=new Set,messageQueue=new linkedMap_1.LinkedMap,Is2.func(messageWriter2.dispose)&&messageWriter2.dispose(),Is2.func(messageReader2.dispose)&&messageReader2.dispose()},listen:()=>{throwIfClosedOrDisposed(),throwIfListening(),state=ConnectionState.Listening,messageReader2.listen(callback)},inspect:()=>{(0,ral_1.default)().console.log("inspect")}};return connection2.onNotification(LogTraceNotification.type,params=>{if(trace===Trace.Off||!tracer)return;const verbose=trace===Trace.Verbose||trace===Trace.Compact;tracer.log(params.message,verbose?params.verbose:void 0)}),connection2.onNotification(ProgressNotification.type,params=>{const handler=progressHandlers.get(params.token);handler?handler(params.value):unhandledProgressEmitter.fire(params)}),connection2}exports$1.createMessageConnection=createMessageConnection})(connection$1)),connection$1}var hasRequiredApi$1;function requireApi$1(){return hasRequiredApi$1||(hasRequiredApi$1=1,(function(exports$1){Object.defineProperty(exports$1,"__esModule",{value:!0}),exports$1.ProgressType=exports$1.ProgressToken=exports$1.createMessageConnection=exports$1.NullLogger=exports$1.ConnectionOptions=exports$1.ConnectionStrategy=exports$1.AbstractMessageBuffer=exports$1.WriteableStreamMessageWriter=exports$1.AbstractMessageWriter=exports$1.MessageWriter=exports$1.ReadableStreamMessageReader=exports$1.AbstractMessageReader=exports$1.MessageReader=exports$1.SharedArrayReceiverStrategy=exports$1.SharedArraySenderStrategy=exports$1.CancellationToken=exports$1.CancellationTokenSource=exports$1.Emitter=exports$1.Event=exports$1.Disposable=exports$1.LRUCache=exports$1.Touch=exports$1.LinkedMap=exports$1.ParameterStructures=exports$1.NotificationType9=exports$1.NotificationType8=exports$1.NotificationType7=exports$1.NotificationType6=exports$1.NotificationType5=exports$1.NotificationType4=exports$1.NotificationType3=exports$1.NotificationType2=exports$1.NotificationType1=exports$1.NotificationType0=exports$1.NotificationType=exports$1.ErrorCodes=exports$1.ResponseError=exports$1.RequestType9=exports$1.RequestType8=exports$1.RequestType7=exports$1.RequestType6=exports$1.RequestType5=exports$1.RequestType4=exports$1.RequestType3=exports$1.RequestType2=exports$1.RequestType1=exports$1.RequestType0=exports$1.RequestType=exports$1.Message=exports$1.RAL=void 0,exports$1.MessageStrategy=exports$1.CancellationStrategy=exports$1.CancellationSenderStrategy=exports$1.CancellationReceiverStrategy=exports$1.ConnectionError=exports$1.ConnectionErrors=exports$1.LogTraceNotification=exports$1.SetTraceNotification=exports$1.TraceFormat=exports$1.TraceValues=exports$1.Trace=void 0;const messages_1=requireMessages$1();Object.defineProperty(exports$1,"Message",{enumerable:!0,get:function(){return messages_1.Message}}),Object.defineProperty(exports$1,"RequestType",{enumerable:!0,get:function(){return messages_1.RequestType}}),Object.defineProperty(exports$1,"RequestType0",{enumerable:!0,get:function(){return messages_1.RequestType0}}),Object.defineProperty(exports$1,"RequestType1",{enumerable:!0,get:function(){return messages_1.RequestType1}}),Object.defineProperty(exports$1,"RequestType2",{enumerable:!0,get:function(){return messages_1.RequestType2}}),Object.defineProperty(exports$1,"RequestType3",{enumerable:!0,get:function(){return messages_1.RequestType3}}),Object.defineProperty(exports$1,"RequestType4",{enumerable:!0,get:function(){return messages_1.RequestType4}}),Object.defineProperty(exports$1,"RequestType5",{enumerable:!0,get:function(){return messages_1.RequestType5}}),Object.defineProperty(exports$1,"RequestType6",{enumerable:!0,get:function(){return messages_1.RequestType6}}),Object.defineProperty(exports$1,"RequestType7",{enumerable:!0,get:function(){return messages_1.RequestType7}}),Object.defineProperty(exports$1,"RequestType8",{enumerable:!0,get:function(){return messages_1.RequestType8}}),Object.defineProperty(exports$1,"RequestType9",{enumerable:!0,get:function(){return messages_1.RequestType9}}),Object.defineProperty(exports$1,"ResponseError",{enumerable:!0,get:function(){return messages_1.ResponseError}}),Object.defineProperty(exports$1,"ErrorCodes",{enumerable:!0,get:function(){return messages_1.ErrorCodes}}),Object.defineProperty(exports$1,"NotificationType",{enumerable:!0,get:function(){return messages_1.NotificationType}}),Object.defineProperty(exports$1,"NotificationType0",{enumerable:!0,get:function(){return messages_1.NotificationType0}}),Object.defineProperty(exports$1,"NotificationType1",{enumerable:!0,get:function(){return messages_1.NotificationType1}}),Object.defineProperty(exports$1,"NotificationType2",{enumerable:!0,get:function(){return messages_1.NotificationType2}}),Object.defineProperty(exports$1,"NotificationType3",{enumerable:!0,get:function(){return messages_1.NotificationType3}}),Object.defineProperty(exports$1,"NotificationType4",{enumerable:!0,get:function(){return messages_1.NotificationType4}}),Object.defineProperty(exports$1,"NotificationType5",{enumerable:!0,get:function(){return messages_1.NotificationType5}}),Object.defineProperty(exports$1,"NotificationType6",{enumerable:!0,get:function(){return messages_1.NotificationType6}}),Object.defineProperty(exports$1,"NotificationType7",{enumerable:!0,get:function(){return messages_1.NotificationType7}}),Object.defineProperty(exports$1,"NotificationType8",{enumerable:!0,get:function(){return messages_1.NotificationType8}}),Object.defineProperty(exports$1,"NotificationType9",{enumerable:!0,get:function(){return messages_1.NotificationType9}}),Object.defineProperty(exports$1,"ParameterStructures",{enumerable:!0,get:function(){return messages_1.ParameterStructures}});const linkedMap_1=requireLinkedMap();Object.defineProperty(exports$1,"LinkedMap",{enumerable:!0,get:function(){return linkedMap_1.LinkedMap}}),Object.defineProperty(exports$1,"LRUCache",{enumerable:!0,get:function(){return linkedMap_1.LRUCache}}),Object.defineProperty(exports$1,"Touch",{enumerable:!0,get:function(){return linkedMap_1.Touch}});const disposable_1=requireDisposable();Object.defineProperty(exports$1,"Disposable",{enumerable:!0,get:function(){return disposable_1.Disposable}});const events_1=requireEvents();Object.defineProperty(exports$1,"Event",{enumerable:!0,get:function(){return events_1.Event}}),Object.defineProperty(exports$1,"Emitter",{enumerable:!0,get:function(){return events_1.Emitter}});const cancellation_1=requireCancellation();Object.defineProperty(exports$1,"CancellationTokenSource",{enumerable:!0,get:function(){return cancellation_1.CancellationTokenSource}}),Object.defineProperty(exports$1,"CancellationToken",{enumerable:!0,get:function(){return cancellation_1.CancellationToken}});const sharedArrayCancellation_1=requireSharedArrayCancellation();Object.defineProperty(exports$1,"SharedArraySenderStrategy",{enumerable:!0,get:function(){return sharedArrayCancellation_1.SharedArraySenderStrategy}}),Object.defineProperty(exports$1,"SharedArrayReceiverStrategy",{enumerable:!0,get:function(){return sharedArrayCancellation_1.SharedArrayReceiverStrategy}});const messageReader_1=requireMessageReader();Object.defineProperty(exports$1,"MessageReader",{enumerable:!0,get:function(){return messageReader_1.MessageReader}}),Object.defineProperty(exports$1,"AbstractMessageReader",{enumerable:!0,get:function(){return messageReader_1.AbstractMessageReader}}),Object.defineProperty(exports$1,"ReadableStreamMessageReader",{enumerable:!0,get:function(){return messageReader_1.ReadableStreamMessageReader}});const messageWriter_1=requireMessageWriter();Object.defineProperty(exports$1,"MessageWriter",{enumerable:!0,get:function(){return messageWriter_1.MessageWriter}}),Object.defineProperty(exports$1,"AbstractMessageWriter",{enumerable:!0,get:function(){return messageWriter_1.AbstractMessageWriter}}),Object.defineProperty(exports$1,"WriteableStreamMessageWriter",{enumerable:!0,get:function(){return messageWriter_1.WriteableStreamMessageWriter}});const messageBuffer_1=requireMessageBuffer();Object.defineProperty(exports$1,"AbstractMessageBuffer",{enumerable:!0,get:function(){return messageBuffer_1.AbstractMessageBuffer}});const connection_1=requireConnection$1();Object.defineProperty(exports$1,"ConnectionStrategy",{enumerable:!0,get:function(){return connection_1.ConnectionStrategy}}),Object.defineProperty(exports$1,"ConnectionOptions",{enumerable:!0,get:function(){return connection_1.ConnectionOptions}}),Object.defineProperty(exports$1,"NullLogger",{enumerable:!0,get:function(){return connection_1.NullLogger}}),Object.defineProperty(exports$1,"createMessageConnection",{enumerable:!0,get:function(){return connection_1.createMessageConnection}}),Object.defineProperty(exports$1,"ProgressToken",{enumerable:!0,get:function(){return connection_1.ProgressToken}}),Object.defineProperty(exports$1,"ProgressType",{enumerable:!0,get:function(){return connection_1.ProgressType}}),Object.defineProperty(exports$1,"Trace",{enumerable:!0,get:function(){return connection_1.Trace}}),Object.defineProperty(exports$1,"TraceValues",{enumerable:!0,get:function(){return connection_1.TraceValues}}),Object.defineProperty(exports$1,"TraceFormat",{enumerable:!0,get:function(){return connection_1.TraceFormat}}),Object.defineProperty(exports$1,"SetTraceNotification",{enumerable:!0,get:function(){return connection_1.SetTraceNotification}}),Object.defineProperty(exports$1,"LogTraceNotification",{enumerable:!0,get:function(){return connection_1.LogTraceNotification}}),Object.defineProperty(exports$1,"ConnectionErrors",{enumerable:!0,get:function(){return connection_1.ConnectionErrors}}),Object.defineProperty(exports$1,"ConnectionError",{enumerable:!0,get:function(){return connection_1.ConnectionError}}),Object.defineProperty(exports$1,"CancellationReceiverStrategy",{enumerable:!0,get:function(){return connection_1.CancellationReceiverStrategy}}),Object.defineProperty(exports$1,"CancellationSenderStrategy",{enumerable:!0,get:function(){return connection_1.CancellationSenderStrategy}}),Object.defineProperty(exports$1,"CancellationStrategy",{enumerable:!0,get:function(){return connection_1.CancellationStrategy}}),Object.defineProperty(exports$1,"MessageStrategy",{enumerable:!0,get:function(){return connection_1.MessageStrategy}});const ral_1=requireRal();exports$1.RAL=ral_1.default})(api$1)),api$1}var hasRequiredRil;function requireRil(){if(hasRequiredRil)return ril;hasRequiredRil=1,Object.defineProperty(ril,"__esModule",{value:!0});const api_1=requireApi$1();class MessageBuffer extends api_1.AbstractMessageBuffer{constructor(encoding="utf-8"){super(encoding),this.asciiDecoder=new TextDecoder("ascii")}emptyBuffer(){return MessageBuffer.emptyBuffer}fromString(value,_encoding){return new TextEncoder().encode(value)}toString(value,encoding){return encoding==="ascii"?this.asciiDecoder.decode(value):new TextDecoder(encoding).decode(value)}asNative(buffer,length){return length===void 0?buffer:buffer.slice(0,length)}allocNative(length){return new Uint8Array(length)}}MessageBuffer.emptyBuffer=new Uint8Array(0);class ReadableStreamWrapper{constructor(socket){this.socket=socket,this._onData=new api_1.Emitter,this._messageListener=event=>{event.data.arrayBuffer().then(buffer=>{this._onData.fire(new Uint8Array(buffer))},()=>{(0,api_1.RAL)().console.error("Converting blob to array buffer failed.")})},this.socket.addEventListener("message",this._messageListener)}onClose(listener){return this.socket.addEventListener("close",listener),api_1.Disposable.create(()=>this.socket.removeEventListener("close",listener))}onError(listener){return this.socket.addEventListener("error",listener),api_1.Disposable.create(()=>this.socket.removeEventListener("error",listener))}onEnd(listener){return this.socket.addEventListener("end",listener),api_1.Disposable.create(()=>this.socket.removeEventListener("end",listener))}onData(listener){return this._onData.event(listener)}}class WritableStreamWrapper{constructor(socket){this.socket=socket}onClose(listener){return this.socket.addEventListener("close",listener),api_1.Disposable.create(()=>this.socket.removeEventListener("close",listener))}onError(listener){return this.socket.addEventListener("error",listener),api_1.Disposable.create(()=>this.socket.removeEventListener("error",listener))}onEnd(listener){return this.socket.addEventListener("end",listener),api_1.Disposable.create(()=>this.socket.removeEventListener("end",listener))}write(data,encoding){if(typeof data=="string"){if(encoding!==void 0&&encoding!=="utf-8")throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${encoding}`);this.socket.send(data)}else this.socket.send(data);return Promise.resolve()}end(){this.socket.close()}}const _textEncoder=new TextEncoder,_ril=Object.freeze({messageBuffer:Object.freeze({create:encoding=>new MessageBuffer(encoding)}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:(msg,options)=>{if(options.charset!=="utf-8")throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${options.charset}`);return Promise.resolve(_textEncoder.encode(JSON.stringify(msg,void 0,0)))}}),decoder:Object.freeze({name:"application/json",decode:(buffer,options)=>{if(!(buffer instanceof Uint8Array))throw new Error("In a Browser environments only Uint8Arrays are supported.");return Promise.resolve(JSON.parse(new TextDecoder(options.charset).decode(buffer)))}})}),stream:Object.freeze({asReadableStream:socket=>new ReadableStreamWrapper(socket),asWritableStream:socket=>new WritableStreamWrapper(socket)}),console,timer:Object.freeze({setTimeout(callback,ms,...args){const handle=setTimeout(callback,ms,...args);return{dispose:()=>clearTimeout(handle)}},setImmediate(callback,...args){const handle=setTimeout(callback,0,...args);return{dispose:()=>clearTimeout(handle)}},setInterval(callback,ms,...args){const handle=setInterval(callback,ms,...args);return{dispose:()=>clearInterval(handle)}}})});function RIL(){return _ril}return(function(RIL2){function install(){api_1.RAL.install(_ril)}RIL2.install=install})(RIL||(RIL={})),ril.default=RIL,ril}var hasRequiredMain$1;function requireMain$1(){return hasRequiredMain$1||(hasRequiredMain$1=1,(function(exports$1){var __createBinding=main&&main.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=main&&main.__exportStar||function(m,exports$12){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports$12,p)&&__createBinding(exports$12,m,p)};Object.defineProperty(exports$1,"__esModule",{value:!0}),exports$1.createMessageConnection=exports$1.BrowserMessageWriter=exports$1.BrowserMessageReader=void 0,requireRil().default.install();const api_1=requireApi$1();__exportStar(requireApi$1(),exports$1);class BrowserMessageReader extends api_1.AbstractMessageReader{constructor(port){super(),this._onData=new api_1.Emitter,this._messageListener=event=>{this._onData.fire(event.data)},port.addEventListener("error",event=>this.fireError(event)),port.onmessage=this._messageListener}listen(callback){return this._onData.event(callback)}}exports$1.BrowserMessageReader=BrowserMessageReader;class BrowserMessageWriter extends api_1.AbstractMessageWriter{constructor(port){super(),this.port=port,this.errorCount=0,port.addEventListener("error",event=>this.fireError(event))}write(msg){try{return this.port.postMessage(msg),Promise.resolve()}catch(error){return this.handleError(error,msg),Promise.reject(error)}}handleError(error,msg){this.errorCount++,this.fireError(error,msg,this.errorCount)}end(){}}exports$1.BrowserMessageWriter=BrowserMessageWriter;function createMessageConnection(reader,writer,logger,options){return logger===void 0&&(logger=api_1.NullLogger),api_1.ConnectionStrategy.is(options)&&(options={connectionStrategy:options}),(0,api_1.createMessageConnection)(reader,writer,logger,options)}exports$1.createMessageConnection=createMessageConnection})(main)),main}var browser,hasRequiredBrowser;function requireBrowser(){return hasRequiredBrowser||(hasRequiredBrowser=1,browser=requireMain$1()),browser}var api={};const require$$1=getAugmentedNamespace(main$2);var messages={},hasRequiredMessages;function requireMessages(){if(hasRequiredMessages)return messages;hasRequiredMessages=1,Object.defineProperty(messages,"__esModule",{value:!0}),messages.ProtocolNotificationType=messages.ProtocolNotificationType0=messages.ProtocolRequestType=messages.ProtocolRequestType0=messages.RegistrationType=messages.MessageDirection=void 0;const vscode_jsonrpc_1=requireMain$1();var MessageDirection;(function(MessageDirection2){MessageDirection2.clientToServer="clientToServer",MessageDirection2.serverToClient="serverToClient",MessageDirection2.both="both"})(MessageDirection||(messages.MessageDirection=MessageDirection={}));class RegistrationType{constructor(method){this.method=method}}messages.RegistrationType=RegistrationType;class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0{constructor(method){super(method)}}messages.ProtocolRequestType0=ProtocolRequestType0;class ProtocolRequestType extends vscode_jsonrpc_1.RequestType{constructor(method){super(method,vscode_jsonrpc_1.ParameterStructures.byName)}}messages.ProtocolRequestType=ProtocolRequestType;class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0{constructor(method){super(method)}}messages.ProtocolNotificationType0=ProtocolNotificationType0;class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType{constructor(method){super(method,vscode_jsonrpc_1.ParameterStructures.byName)}}return messages.ProtocolNotificationType=ProtocolNotificationType,messages}var protocol={},is={},hasRequiredIs;function requireIs(){if(hasRequiredIs)return is;hasRequiredIs=1,Object.defineProperty(is,"__esModule",{value:!0}),is.objectLiteral=is.typedArray=is.stringArray=is.array=is.func=is.error=is.number=is.string=is.boolean=void 0;function boolean(value){return value===!0||value===!1}is.boolean=boolean;function string(value){return typeof value=="string"||value instanceof String}is.string=string;function number(value){return typeof value=="number"||value instanceof Number}is.number=number;function error(value){return value instanceof Error}is.error=error;function func(value){return typeof value=="function"}is.func=func;function array(value){return Array.isArray(value)}is.array=array;function stringArray(value){return array(value)&&value.every(elem=>string(elem))}is.stringArray=stringArray;function typedArray(value,check){return Array.isArray(value)&&value.every(check)}is.typedArray=typedArray;function objectLiteral(value){return value!==null&&typeof value=="object"}return is.objectLiteral=objectLiteral,is}var protocol_implementation={},hasRequiredProtocol_implementation;function requireProtocol_implementation(){if(hasRequiredProtocol_implementation)return protocol_implementation;hasRequiredProtocol_implementation=1,Object.defineProperty(protocol_implementation,"__esModule",{value:!0}),protocol_implementation.ImplementationRequest=void 0;const messages_1=requireMessages();var ImplementationRequest;return(function(ImplementationRequest2){ImplementationRequest2.method="textDocument/implementation",ImplementationRequest2.messageDirection=messages_1.MessageDirection.clientToServer,ImplementationRequest2.type=new messages_1.ProtocolRequestType(ImplementationRequest2.method)})(ImplementationRequest||(protocol_implementation.ImplementationRequest=ImplementationRequest={})),protocol_implementation}var protocol_typeDefinition={},hasRequiredProtocol_typeDefinition;function requireProtocol_typeDefinition(){if(hasRequiredProtocol_typeDefinition)return protocol_typeDefinition;hasRequiredProtocol_typeDefinition=1,Object.defineProperty(protocol_typeDefinition,"__esModule",{value:!0}),protocol_typeDefinition.TypeDefinitionRequest=void 0;const messages_1=requireMessages();var TypeDefinitionRequest;return(function(TypeDefinitionRequest2){TypeDefinitionRequest2.method="textDocument/typeDefinition",TypeDefinitionRequest2.messageDirection=messages_1.MessageDirection.clientToServer,TypeDefinitionRequest2.type=new messages_1.ProtocolRequestType(TypeDefinitionRequest2.method)})(TypeDefinitionRequest||(protocol_typeDefinition.TypeDefinitionRequest=TypeDefinitionRequest={})),protocol_typeDefinition}var protocol_workspaceFolder={},hasRequiredProtocol_workspaceFolder;function requireProtocol_workspaceFolder(){if(hasRequiredProtocol_workspaceFolder)return protocol_workspaceFolder;hasRequiredProtocol_workspaceFolder=1,Object.defineProperty(protocol_workspaceFolder,"__esModule",{value:!0}),protocol_workspaceFolder.DidChangeWorkspaceFoldersNotification=protocol_workspaceFolder.WorkspaceFoldersRequest=void 0;const messages_1=requireMessages();var WorkspaceFoldersRequest;(function(WorkspaceFoldersRequest2){WorkspaceFoldersRequest2.method="workspace/workspaceFolders",WorkspaceFoldersRequest2.messageDirection=messages_1.MessageDirection.serverToClient,WorkspaceFoldersRequest2.type=new messages_1.ProtocolRequestType0(WorkspaceFoldersRequest2.method)})(WorkspaceFoldersRequest||(protocol_workspaceFolder.WorkspaceFoldersRequest=WorkspaceFoldersRequest={}));var DidChangeWorkspaceFoldersNotification;return(function(DidChangeWorkspaceFoldersNotification2){DidChangeWorkspaceFoldersNotification2.method="workspace/didChangeWorkspaceFolders",DidChangeWorkspaceFoldersNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidChangeWorkspaceFoldersNotification2.type=new messages_1.ProtocolNotificationType(DidChangeWorkspaceFoldersNotification2.method)})(DidChangeWorkspaceFoldersNotification||(protocol_workspaceFolder.DidChangeWorkspaceFoldersNotification=DidChangeWorkspaceFoldersNotification={})),protocol_workspaceFolder}var protocol_configuration={},hasRequiredProtocol_configuration;function requireProtocol_configuration(){if(hasRequiredProtocol_configuration)return protocol_configuration;hasRequiredProtocol_configuration=1,Object.defineProperty(protocol_configuration,"__esModule",{value:!0}),protocol_configuration.ConfigurationRequest=void 0;const messages_1=requireMessages();var ConfigurationRequest;return(function(ConfigurationRequest2){ConfigurationRequest2.method="workspace/configuration",ConfigurationRequest2.messageDirection=messages_1.MessageDirection.serverToClient,ConfigurationRequest2.type=new messages_1.ProtocolRequestType(ConfigurationRequest2.method)})(ConfigurationRequest||(protocol_configuration.ConfigurationRequest=ConfigurationRequest={})),protocol_configuration}var protocol_colorProvider={},hasRequiredProtocol_colorProvider;function requireProtocol_colorProvider(){if(hasRequiredProtocol_colorProvider)return protocol_colorProvider;hasRequiredProtocol_colorProvider=1,Object.defineProperty(protocol_colorProvider,"__esModule",{value:!0}),protocol_colorProvider.ColorPresentationRequest=protocol_colorProvider.DocumentColorRequest=void 0;const messages_1=requireMessages();var DocumentColorRequest;(function(DocumentColorRequest2){DocumentColorRequest2.method="textDocument/documentColor",DocumentColorRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DocumentColorRequest2.type=new messages_1.ProtocolRequestType(DocumentColorRequest2.method)})(DocumentColorRequest||(protocol_colorProvider.DocumentColorRequest=DocumentColorRequest={}));var ColorPresentationRequest;return(function(ColorPresentationRequest2){ColorPresentationRequest2.method="textDocument/colorPresentation",ColorPresentationRequest2.messageDirection=messages_1.MessageDirection.clientToServer,ColorPresentationRequest2.type=new messages_1.ProtocolRequestType(ColorPresentationRequest2.method)})(ColorPresentationRequest||(protocol_colorProvider.ColorPresentationRequest=ColorPresentationRequest={})),protocol_colorProvider}var protocol_foldingRange={},hasRequiredProtocol_foldingRange;function requireProtocol_foldingRange(){if(hasRequiredProtocol_foldingRange)return protocol_foldingRange;hasRequiredProtocol_foldingRange=1,Object.defineProperty(protocol_foldingRange,"__esModule",{value:!0}),protocol_foldingRange.FoldingRangeRefreshRequest=protocol_foldingRange.FoldingRangeRequest=void 0;const messages_1=requireMessages();var FoldingRangeRequest;(function(FoldingRangeRequest2){FoldingRangeRequest2.method="textDocument/foldingRange",FoldingRangeRequest2.messageDirection=messages_1.MessageDirection.clientToServer,FoldingRangeRequest2.type=new messages_1.ProtocolRequestType(FoldingRangeRequest2.method)})(FoldingRangeRequest||(protocol_foldingRange.FoldingRangeRequest=FoldingRangeRequest={}));var FoldingRangeRefreshRequest;return(function(FoldingRangeRefreshRequest2){FoldingRangeRefreshRequest2.method="workspace/foldingRange/refresh",FoldingRangeRefreshRequest2.messageDirection=messages_1.MessageDirection.serverToClient,FoldingRangeRefreshRequest2.type=new messages_1.ProtocolRequestType0(FoldingRangeRefreshRequest2.method)})(FoldingRangeRefreshRequest||(protocol_foldingRange.FoldingRangeRefreshRequest=FoldingRangeRefreshRequest={})),protocol_foldingRange}var protocol_declaration={},hasRequiredProtocol_declaration;function requireProtocol_declaration(){if(hasRequiredProtocol_declaration)return protocol_declaration;hasRequiredProtocol_declaration=1,Object.defineProperty(protocol_declaration,"__esModule",{value:!0}),protocol_declaration.DeclarationRequest=void 0;const messages_1=requireMessages();var DeclarationRequest;return(function(DeclarationRequest2){DeclarationRequest2.method="textDocument/declaration",DeclarationRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DeclarationRequest2.type=new messages_1.ProtocolRequestType(DeclarationRequest2.method)})(DeclarationRequest||(protocol_declaration.DeclarationRequest=DeclarationRequest={})),protocol_declaration}var protocol_selectionRange={},hasRequiredProtocol_selectionRange;function requireProtocol_selectionRange(){if(hasRequiredProtocol_selectionRange)return protocol_selectionRange;hasRequiredProtocol_selectionRange=1,Object.defineProperty(protocol_selectionRange,"__esModule",{value:!0}),protocol_selectionRange.SelectionRangeRequest=void 0;const messages_1=requireMessages();var SelectionRangeRequest;return(function(SelectionRangeRequest2){SelectionRangeRequest2.method="textDocument/selectionRange",SelectionRangeRequest2.messageDirection=messages_1.MessageDirection.clientToServer,SelectionRangeRequest2.type=new messages_1.ProtocolRequestType(SelectionRangeRequest2.method)})(SelectionRangeRequest||(protocol_selectionRange.SelectionRangeRequest=SelectionRangeRequest={})),protocol_selectionRange}var protocol_progress={},hasRequiredProtocol_progress;function requireProtocol_progress(){if(hasRequiredProtocol_progress)return protocol_progress;hasRequiredProtocol_progress=1,Object.defineProperty(protocol_progress,"__esModule",{value:!0}),protocol_progress.WorkDoneProgressCancelNotification=protocol_progress.WorkDoneProgressCreateRequest=protocol_progress.WorkDoneProgress=void 0;const vscode_jsonrpc_1=requireMain$1(),messages_1=requireMessages();var WorkDoneProgress;(function(WorkDoneProgress2){WorkDoneProgress2.type=new vscode_jsonrpc_1.ProgressType;function is2(value){return value===WorkDoneProgress2.type}WorkDoneProgress2.is=is2})(WorkDoneProgress||(protocol_progress.WorkDoneProgress=WorkDoneProgress={}));var WorkDoneProgressCreateRequest;(function(WorkDoneProgressCreateRequest2){WorkDoneProgressCreateRequest2.method="window/workDoneProgress/create",WorkDoneProgressCreateRequest2.messageDirection=messages_1.MessageDirection.serverToClient,WorkDoneProgressCreateRequest2.type=new messages_1.ProtocolRequestType(WorkDoneProgressCreateRequest2.method)})(WorkDoneProgressCreateRequest||(protocol_progress.WorkDoneProgressCreateRequest=WorkDoneProgressCreateRequest={}));var WorkDoneProgressCancelNotification;return(function(WorkDoneProgressCancelNotification2){WorkDoneProgressCancelNotification2.method="window/workDoneProgress/cancel",WorkDoneProgressCancelNotification2.messageDirection=messages_1.MessageDirection.clientToServer,WorkDoneProgressCancelNotification2.type=new messages_1.ProtocolNotificationType(WorkDoneProgressCancelNotification2.method)})(WorkDoneProgressCancelNotification||(protocol_progress.WorkDoneProgressCancelNotification=WorkDoneProgressCancelNotification={})),protocol_progress}var protocol_callHierarchy={},hasRequiredProtocol_callHierarchy;function requireProtocol_callHierarchy(){if(hasRequiredProtocol_callHierarchy)return protocol_callHierarchy;hasRequiredProtocol_callHierarchy=1,Object.defineProperty(protocol_callHierarchy,"__esModule",{value:!0}),protocol_callHierarchy.CallHierarchyOutgoingCallsRequest=protocol_callHierarchy.CallHierarchyIncomingCallsRequest=protocol_callHierarchy.CallHierarchyPrepareRequest=void 0;const messages_1=requireMessages();var CallHierarchyPrepareRequest;(function(CallHierarchyPrepareRequest2){CallHierarchyPrepareRequest2.method="textDocument/prepareCallHierarchy",CallHierarchyPrepareRequest2.messageDirection=messages_1.MessageDirection.clientToServer,CallHierarchyPrepareRequest2.type=new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest2.method)})(CallHierarchyPrepareRequest||(protocol_callHierarchy.CallHierarchyPrepareRequest=CallHierarchyPrepareRequest={}));var CallHierarchyIncomingCallsRequest;(function(CallHierarchyIncomingCallsRequest2){CallHierarchyIncomingCallsRequest2.method="callHierarchy/incomingCalls",CallHierarchyIncomingCallsRequest2.messageDirection=messages_1.MessageDirection.clientToServer,CallHierarchyIncomingCallsRequest2.type=new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest2.method)})(CallHierarchyIncomingCallsRequest||(protocol_callHierarchy.CallHierarchyIncomingCallsRequest=CallHierarchyIncomingCallsRequest={}));var CallHierarchyOutgoingCallsRequest;return(function(CallHierarchyOutgoingCallsRequest2){CallHierarchyOutgoingCallsRequest2.method="callHierarchy/outgoingCalls",CallHierarchyOutgoingCallsRequest2.messageDirection=messages_1.MessageDirection.clientToServer,CallHierarchyOutgoingCallsRequest2.type=new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest2.method)})(CallHierarchyOutgoingCallsRequest||(protocol_callHierarchy.CallHierarchyOutgoingCallsRequest=CallHierarchyOutgoingCallsRequest={})),protocol_callHierarchy}var protocol_semanticTokens={},hasRequiredProtocol_semanticTokens;function requireProtocol_semanticTokens(){if(hasRequiredProtocol_semanticTokens)return protocol_semanticTokens;hasRequiredProtocol_semanticTokens=1,Object.defineProperty(protocol_semanticTokens,"__esModule",{value:!0}),protocol_semanticTokens.SemanticTokensRefreshRequest=protocol_semanticTokens.SemanticTokensRangeRequest=protocol_semanticTokens.SemanticTokensDeltaRequest=protocol_semanticTokens.SemanticTokensRequest=protocol_semanticTokens.SemanticTokensRegistrationType=protocol_semanticTokens.TokenFormat=void 0;const messages_1=requireMessages();var TokenFormat;(function(TokenFormat2){TokenFormat2.Relative="relative"})(TokenFormat||(protocol_semanticTokens.TokenFormat=TokenFormat={}));var SemanticTokensRegistrationType;(function(SemanticTokensRegistrationType2){SemanticTokensRegistrationType2.method="textDocument/semanticTokens",SemanticTokensRegistrationType2.type=new messages_1.RegistrationType(SemanticTokensRegistrationType2.method)})(SemanticTokensRegistrationType||(protocol_semanticTokens.SemanticTokensRegistrationType=SemanticTokensRegistrationType={}));var SemanticTokensRequest;(function(SemanticTokensRequest2){SemanticTokensRequest2.method="textDocument/semanticTokens/full",SemanticTokensRequest2.messageDirection=messages_1.MessageDirection.clientToServer,SemanticTokensRequest2.type=new messages_1.ProtocolRequestType(SemanticTokensRequest2.method),SemanticTokensRequest2.registrationMethod=SemanticTokensRegistrationType.method})(SemanticTokensRequest||(protocol_semanticTokens.SemanticTokensRequest=SemanticTokensRequest={}));var SemanticTokensDeltaRequest;(function(SemanticTokensDeltaRequest2){SemanticTokensDeltaRequest2.method="textDocument/semanticTokens/full/delta",SemanticTokensDeltaRequest2.messageDirection=messages_1.MessageDirection.clientToServer,SemanticTokensDeltaRequest2.type=new messages_1.ProtocolRequestType(SemanticTokensDeltaRequest2.method),SemanticTokensDeltaRequest2.registrationMethod=SemanticTokensRegistrationType.method})(SemanticTokensDeltaRequest||(protocol_semanticTokens.SemanticTokensDeltaRequest=SemanticTokensDeltaRequest={}));var SemanticTokensRangeRequest;(function(SemanticTokensRangeRequest2){SemanticTokensRangeRequest2.method="textDocument/semanticTokens/range",SemanticTokensRangeRequest2.messageDirection=messages_1.MessageDirection.clientToServer,SemanticTokensRangeRequest2.type=new messages_1.ProtocolRequestType(SemanticTokensRangeRequest2.method),SemanticTokensRangeRequest2.registrationMethod=SemanticTokensRegistrationType.method})(SemanticTokensRangeRequest||(protocol_semanticTokens.SemanticTokensRangeRequest=SemanticTokensRangeRequest={}));var SemanticTokensRefreshRequest;return(function(SemanticTokensRefreshRequest2){SemanticTokensRefreshRequest2.method="workspace/semanticTokens/refresh",SemanticTokensRefreshRequest2.messageDirection=messages_1.MessageDirection.serverToClient,SemanticTokensRefreshRequest2.type=new messages_1.ProtocolRequestType0(SemanticTokensRefreshRequest2.method)})(SemanticTokensRefreshRequest||(protocol_semanticTokens.SemanticTokensRefreshRequest=SemanticTokensRefreshRequest={})),protocol_semanticTokens}var protocol_showDocument={},hasRequiredProtocol_showDocument;function requireProtocol_showDocument(){if(hasRequiredProtocol_showDocument)return protocol_showDocument;hasRequiredProtocol_showDocument=1,Object.defineProperty(protocol_showDocument,"__esModule",{value:!0}),protocol_showDocument.ShowDocumentRequest=void 0;const messages_1=requireMessages();var ShowDocumentRequest;return(function(ShowDocumentRequest2){ShowDocumentRequest2.method="window/showDocument",ShowDocumentRequest2.messageDirection=messages_1.MessageDirection.serverToClient,ShowDocumentRequest2.type=new messages_1.ProtocolRequestType(ShowDocumentRequest2.method)})(ShowDocumentRequest||(protocol_showDocument.ShowDocumentRequest=ShowDocumentRequest={})),protocol_showDocument}var protocol_linkedEditingRange={},hasRequiredProtocol_linkedEditingRange;function requireProtocol_linkedEditingRange(){if(hasRequiredProtocol_linkedEditingRange)return protocol_linkedEditingRange;hasRequiredProtocol_linkedEditingRange=1,Object.defineProperty(protocol_linkedEditingRange,"__esModule",{value:!0}),protocol_linkedEditingRange.LinkedEditingRangeRequest=void 0;const messages_1=requireMessages();var LinkedEditingRangeRequest;return(function(LinkedEditingRangeRequest2){LinkedEditingRangeRequest2.method="textDocument/linkedEditingRange",LinkedEditingRangeRequest2.messageDirection=messages_1.MessageDirection.clientToServer,LinkedEditingRangeRequest2.type=new messages_1.ProtocolRequestType(LinkedEditingRangeRequest2.method)})(LinkedEditingRangeRequest||(protocol_linkedEditingRange.LinkedEditingRangeRequest=LinkedEditingRangeRequest={})),protocol_linkedEditingRange}var protocol_fileOperations={},hasRequiredProtocol_fileOperations;function requireProtocol_fileOperations(){if(hasRequiredProtocol_fileOperations)return protocol_fileOperations;hasRequiredProtocol_fileOperations=1,Object.defineProperty(protocol_fileOperations,"__esModule",{value:!0}),protocol_fileOperations.WillDeleteFilesRequest=protocol_fileOperations.DidDeleteFilesNotification=protocol_fileOperations.DidRenameFilesNotification=protocol_fileOperations.WillRenameFilesRequest=protocol_fileOperations.DidCreateFilesNotification=protocol_fileOperations.WillCreateFilesRequest=protocol_fileOperations.FileOperationPatternKind=void 0;const messages_1=requireMessages();var FileOperationPatternKind;(function(FileOperationPatternKind2){FileOperationPatternKind2.file="file",FileOperationPatternKind2.folder="folder"})(FileOperationPatternKind||(protocol_fileOperations.FileOperationPatternKind=FileOperationPatternKind={}));var WillCreateFilesRequest;(function(WillCreateFilesRequest2){WillCreateFilesRequest2.method="workspace/willCreateFiles",WillCreateFilesRequest2.messageDirection=messages_1.MessageDirection.clientToServer,WillCreateFilesRequest2.type=new messages_1.ProtocolRequestType(WillCreateFilesRequest2.method)})(WillCreateFilesRequest||(protocol_fileOperations.WillCreateFilesRequest=WillCreateFilesRequest={}));var DidCreateFilesNotification;(function(DidCreateFilesNotification2){DidCreateFilesNotification2.method="workspace/didCreateFiles",DidCreateFilesNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidCreateFilesNotification2.type=new messages_1.ProtocolNotificationType(DidCreateFilesNotification2.method)})(DidCreateFilesNotification||(protocol_fileOperations.DidCreateFilesNotification=DidCreateFilesNotification={}));var WillRenameFilesRequest;(function(WillRenameFilesRequest2){WillRenameFilesRequest2.method="workspace/willRenameFiles",WillRenameFilesRequest2.messageDirection=messages_1.MessageDirection.clientToServer,WillRenameFilesRequest2.type=new messages_1.ProtocolRequestType(WillRenameFilesRequest2.method)})(WillRenameFilesRequest||(protocol_fileOperations.WillRenameFilesRequest=WillRenameFilesRequest={}));var DidRenameFilesNotification;(function(DidRenameFilesNotification2){DidRenameFilesNotification2.method="workspace/didRenameFiles",DidRenameFilesNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidRenameFilesNotification2.type=new messages_1.ProtocolNotificationType(DidRenameFilesNotification2.method)})(DidRenameFilesNotification||(protocol_fileOperations.DidRenameFilesNotification=DidRenameFilesNotification={}));var DidDeleteFilesNotification;(function(DidDeleteFilesNotification2){DidDeleteFilesNotification2.method="workspace/didDeleteFiles",DidDeleteFilesNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidDeleteFilesNotification2.type=new messages_1.ProtocolNotificationType(DidDeleteFilesNotification2.method)})(DidDeleteFilesNotification||(protocol_fileOperations.DidDeleteFilesNotification=DidDeleteFilesNotification={}));var WillDeleteFilesRequest;return(function(WillDeleteFilesRequest2){WillDeleteFilesRequest2.method="workspace/willDeleteFiles",WillDeleteFilesRequest2.messageDirection=messages_1.MessageDirection.clientToServer,WillDeleteFilesRequest2.type=new messages_1.ProtocolRequestType(WillDeleteFilesRequest2.method)})(WillDeleteFilesRequest||(protocol_fileOperations.WillDeleteFilesRequest=WillDeleteFilesRequest={})),protocol_fileOperations}var protocol_moniker={},hasRequiredProtocol_moniker;function requireProtocol_moniker(){if(hasRequiredProtocol_moniker)return protocol_moniker;hasRequiredProtocol_moniker=1,Object.defineProperty(protocol_moniker,"__esModule",{value:!0}),protocol_moniker.MonikerRequest=protocol_moniker.MonikerKind=protocol_moniker.UniquenessLevel=void 0;const messages_1=requireMessages();var UniquenessLevel;(function(UniquenessLevel2){UniquenessLevel2.document="document",UniquenessLevel2.project="project",UniquenessLevel2.group="group",UniquenessLevel2.scheme="scheme",UniquenessLevel2.global="global"})(UniquenessLevel||(protocol_moniker.UniquenessLevel=UniquenessLevel={}));var MonikerKind;(function(MonikerKind2){MonikerKind2.$import="import",MonikerKind2.$export="export",MonikerKind2.local="local"})(MonikerKind||(protocol_moniker.MonikerKind=MonikerKind={}));var MonikerRequest;return(function(MonikerRequest2){MonikerRequest2.method="textDocument/moniker",MonikerRequest2.messageDirection=messages_1.MessageDirection.clientToServer,MonikerRequest2.type=new messages_1.ProtocolRequestType(MonikerRequest2.method)})(MonikerRequest||(protocol_moniker.MonikerRequest=MonikerRequest={})),protocol_moniker}var protocol_typeHierarchy={},hasRequiredProtocol_typeHierarchy;function requireProtocol_typeHierarchy(){if(hasRequiredProtocol_typeHierarchy)return protocol_typeHierarchy;hasRequiredProtocol_typeHierarchy=1,Object.defineProperty(protocol_typeHierarchy,"__esModule",{value:!0}),protocol_typeHierarchy.TypeHierarchySubtypesRequest=protocol_typeHierarchy.TypeHierarchySupertypesRequest=protocol_typeHierarchy.TypeHierarchyPrepareRequest=void 0;const messages_1=requireMessages();var TypeHierarchyPrepareRequest;(function(TypeHierarchyPrepareRequest2){TypeHierarchyPrepareRequest2.method="textDocument/prepareTypeHierarchy",TypeHierarchyPrepareRequest2.messageDirection=messages_1.MessageDirection.clientToServer,TypeHierarchyPrepareRequest2.type=new messages_1.ProtocolRequestType(TypeHierarchyPrepareRequest2.method)})(TypeHierarchyPrepareRequest||(protocol_typeHierarchy.TypeHierarchyPrepareRequest=TypeHierarchyPrepareRequest={}));var TypeHierarchySupertypesRequest;(function(TypeHierarchySupertypesRequest2){TypeHierarchySupertypesRequest2.method="typeHierarchy/supertypes",TypeHierarchySupertypesRequest2.messageDirection=messages_1.MessageDirection.clientToServer,TypeHierarchySupertypesRequest2.type=new messages_1.ProtocolRequestType(TypeHierarchySupertypesRequest2.method)})(TypeHierarchySupertypesRequest||(protocol_typeHierarchy.TypeHierarchySupertypesRequest=TypeHierarchySupertypesRequest={}));var TypeHierarchySubtypesRequest;return(function(TypeHierarchySubtypesRequest2){TypeHierarchySubtypesRequest2.method="typeHierarchy/subtypes",TypeHierarchySubtypesRequest2.messageDirection=messages_1.MessageDirection.clientToServer,TypeHierarchySubtypesRequest2.type=new messages_1.ProtocolRequestType(TypeHierarchySubtypesRequest2.method)})(TypeHierarchySubtypesRequest||(protocol_typeHierarchy.TypeHierarchySubtypesRequest=TypeHierarchySubtypesRequest={})),protocol_typeHierarchy}var protocol_inlineValue={},hasRequiredProtocol_inlineValue;function requireProtocol_inlineValue(){if(hasRequiredProtocol_inlineValue)return protocol_inlineValue;hasRequiredProtocol_inlineValue=1,Object.defineProperty(protocol_inlineValue,"__esModule",{value:!0}),protocol_inlineValue.InlineValueRefreshRequest=protocol_inlineValue.InlineValueRequest=void 0;const messages_1=requireMessages();var InlineValueRequest;(function(InlineValueRequest2){InlineValueRequest2.method="textDocument/inlineValue",InlineValueRequest2.messageDirection=messages_1.MessageDirection.clientToServer,InlineValueRequest2.type=new messages_1.ProtocolRequestType(InlineValueRequest2.method)})(InlineValueRequest||(protocol_inlineValue.InlineValueRequest=InlineValueRequest={}));var InlineValueRefreshRequest;return(function(InlineValueRefreshRequest2){InlineValueRefreshRequest2.method="workspace/inlineValue/refresh",InlineValueRefreshRequest2.messageDirection=messages_1.MessageDirection.serverToClient,InlineValueRefreshRequest2.type=new messages_1.ProtocolRequestType0(InlineValueRefreshRequest2.method)})(InlineValueRefreshRequest||(protocol_inlineValue.InlineValueRefreshRequest=InlineValueRefreshRequest={})),protocol_inlineValue}var protocol_inlayHint={},hasRequiredProtocol_inlayHint;function requireProtocol_inlayHint(){if(hasRequiredProtocol_inlayHint)return protocol_inlayHint;hasRequiredProtocol_inlayHint=1,Object.defineProperty(protocol_inlayHint,"__esModule",{value:!0}),protocol_inlayHint.InlayHintRefreshRequest=protocol_inlayHint.InlayHintResolveRequest=protocol_inlayHint.InlayHintRequest=void 0;const messages_1=requireMessages();var InlayHintRequest;(function(InlayHintRequest2){InlayHintRequest2.method="textDocument/inlayHint",InlayHintRequest2.messageDirection=messages_1.MessageDirection.clientToServer,InlayHintRequest2.type=new messages_1.ProtocolRequestType(InlayHintRequest2.method)})(InlayHintRequest||(protocol_inlayHint.InlayHintRequest=InlayHintRequest={}));var InlayHintResolveRequest;(function(InlayHintResolveRequest2){InlayHintResolveRequest2.method="inlayHint/resolve",InlayHintResolveRequest2.messageDirection=messages_1.MessageDirection.clientToServer,InlayHintResolveRequest2.type=new messages_1.ProtocolRequestType(InlayHintResolveRequest2.method)})(InlayHintResolveRequest||(protocol_inlayHint.InlayHintResolveRequest=InlayHintResolveRequest={}));var InlayHintRefreshRequest;return(function(InlayHintRefreshRequest2){InlayHintRefreshRequest2.method="workspace/inlayHint/refresh",InlayHintRefreshRequest2.messageDirection=messages_1.MessageDirection.serverToClient,InlayHintRefreshRequest2.type=new messages_1.ProtocolRequestType0(InlayHintRefreshRequest2.method)})(InlayHintRefreshRequest||(protocol_inlayHint.InlayHintRefreshRequest=InlayHintRefreshRequest={})),protocol_inlayHint}var protocol_diagnostic={},hasRequiredProtocol_diagnostic;function requireProtocol_diagnostic(){if(hasRequiredProtocol_diagnostic)return protocol_diagnostic;hasRequiredProtocol_diagnostic=1,Object.defineProperty(protocol_diagnostic,"__esModule",{value:!0}),protocol_diagnostic.DiagnosticRefreshRequest=protocol_diagnostic.WorkspaceDiagnosticRequest=protocol_diagnostic.DocumentDiagnosticRequest=protocol_diagnostic.DocumentDiagnosticReportKind=protocol_diagnostic.DiagnosticServerCancellationData=void 0;const vscode_jsonrpc_1=requireMain$1(),Is2=requireIs(),messages_1=requireMessages();var DiagnosticServerCancellationData;(function(DiagnosticServerCancellationData2){function is2(value){const candidate=value;return candidate&&Is2.boolean(candidate.retriggerRequest)}DiagnosticServerCancellationData2.is=is2})(DiagnosticServerCancellationData||(protocol_diagnostic.DiagnosticServerCancellationData=DiagnosticServerCancellationData={}));var DocumentDiagnosticReportKind;(function(DocumentDiagnosticReportKind2){DocumentDiagnosticReportKind2.Full="full",DocumentDiagnosticReportKind2.Unchanged="unchanged"})(DocumentDiagnosticReportKind||(protocol_diagnostic.DocumentDiagnosticReportKind=DocumentDiagnosticReportKind={}));var DocumentDiagnosticRequest;(function(DocumentDiagnosticRequest2){DocumentDiagnosticRequest2.method="textDocument/diagnostic",DocumentDiagnosticRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DocumentDiagnosticRequest2.type=new messages_1.ProtocolRequestType(DocumentDiagnosticRequest2.method),DocumentDiagnosticRequest2.partialResult=new vscode_jsonrpc_1.ProgressType})(DocumentDiagnosticRequest||(protocol_diagnostic.DocumentDiagnosticRequest=DocumentDiagnosticRequest={}));var WorkspaceDiagnosticRequest;(function(WorkspaceDiagnosticRequest2){WorkspaceDiagnosticRequest2.method="workspace/diagnostic",WorkspaceDiagnosticRequest2.messageDirection=messages_1.MessageDirection.clientToServer,WorkspaceDiagnosticRequest2.type=new messages_1.ProtocolRequestType(WorkspaceDiagnosticRequest2.method),WorkspaceDiagnosticRequest2.partialResult=new vscode_jsonrpc_1.ProgressType})(WorkspaceDiagnosticRequest||(protocol_diagnostic.WorkspaceDiagnosticRequest=WorkspaceDiagnosticRequest={}));var DiagnosticRefreshRequest;return(function(DiagnosticRefreshRequest2){DiagnosticRefreshRequest2.method="workspace/diagnostic/refresh",DiagnosticRefreshRequest2.messageDirection=messages_1.MessageDirection.serverToClient,DiagnosticRefreshRequest2.type=new messages_1.ProtocolRequestType0(DiagnosticRefreshRequest2.method)})(DiagnosticRefreshRequest||(protocol_diagnostic.DiagnosticRefreshRequest=DiagnosticRefreshRequest={})),protocol_diagnostic}var protocol_notebook={},hasRequiredProtocol_notebook;function requireProtocol_notebook(){if(hasRequiredProtocol_notebook)return protocol_notebook;hasRequiredProtocol_notebook=1,Object.defineProperty(protocol_notebook,"__esModule",{value:!0}),protocol_notebook.DidCloseNotebookDocumentNotification=protocol_notebook.DidSaveNotebookDocumentNotification=protocol_notebook.DidChangeNotebookDocumentNotification=protocol_notebook.NotebookCellArrayChange=protocol_notebook.DidOpenNotebookDocumentNotification=protocol_notebook.NotebookDocumentSyncRegistrationType=protocol_notebook.NotebookDocument=protocol_notebook.NotebookCell=protocol_notebook.ExecutionSummary=protocol_notebook.NotebookCellKind=void 0;const vscode_languageserver_types_1=require$$1,Is2=requireIs(),messages_1=requireMessages();var NotebookCellKind;(function(NotebookCellKind2){NotebookCellKind2.Markup=1,NotebookCellKind2.Code=2;function is2(value){return value===1||value===2}NotebookCellKind2.is=is2})(NotebookCellKind||(protocol_notebook.NotebookCellKind=NotebookCellKind={}));var ExecutionSummary;(function(ExecutionSummary2){function create(executionOrder,success){const result={executionOrder};return(success===!0||success===!1)&&(result.success=success),result}ExecutionSummary2.create=create;function is2(value){const candidate=value;return Is2.objectLiteral(candidate)&&vscode_languageserver_types_1.uinteger.is(candidate.executionOrder)&&(candidate.success===void 0||Is2.boolean(candidate.success))}ExecutionSummary2.is=is2;function equals(one,other){return one===other?!0:one==null||other===null||other===void 0?!1:one.executionOrder===other.executionOrder&&one.success===other.success}ExecutionSummary2.equals=equals})(ExecutionSummary||(protocol_notebook.ExecutionSummary=ExecutionSummary={}));var NotebookCell;(function(NotebookCell2){function create(kind,document){return{kind,document}}NotebookCell2.create=create;function is2(value){const candidate=value;return Is2.objectLiteral(candidate)&&NotebookCellKind.is(candidate.kind)&&vscode_languageserver_types_1.DocumentUri.is(candidate.document)&&(candidate.metadata===void 0||Is2.objectLiteral(candidate.metadata))}NotebookCell2.is=is2;function diff(one,two){const result=new Set;return one.document!==two.document&&result.add("document"),one.kind!==two.kind&&result.add("kind"),one.executionSummary!==two.executionSummary&&result.add("executionSummary"),(one.metadata!==void 0||two.metadata!==void 0)&&!equalsMetadata(one.metadata,two.metadata)&&result.add("metadata"),(one.executionSummary!==void 0||two.executionSummary!==void 0)&&!ExecutionSummary.equals(one.executionSummary,two.executionSummary)&&result.add("executionSummary"),result}NotebookCell2.diff=diff;function equalsMetadata(one,other){if(one===other)return!0;if(one==null||other===null||other===void 0||typeof one!=typeof other||typeof one!="object")return!1;const oneArray=Array.isArray(one),otherArray=Array.isArray(other);if(oneArray!==otherArray)return!1;if(oneArray&&otherArray){if(one.length!==other.length)return!1;for(let i=0;i<one.length;i++)if(!equalsMetadata(one[i],other[i]))return!1}if(Is2.objectLiteral(one)&&Is2.objectLiteral(other)){const oneKeys=Object.keys(one),otherKeys=Object.keys(other);if(oneKeys.length!==otherKeys.length||(oneKeys.sort(),otherKeys.sort(),!equalsMetadata(oneKeys,otherKeys)))return!1;for(let i=0;i<oneKeys.length;i++){const prop=oneKeys[i];if(!equalsMetadata(one[prop],other[prop]))return!1}}return!0}})(NotebookCell||(protocol_notebook.NotebookCell=NotebookCell={}));var NotebookDocument;(function(NotebookDocument2){function create(uri,notebookType,version,cells){return{uri,notebookType,version,cells}}NotebookDocument2.create=create;function is2(value){const candidate=value;return Is2.objectLiteral(candidate)&&Is2.string(candidate.uri)&&vscode_languageserver_types_1.integer.is(candidate.version)&&Is2.typedArray(candidate.cells,NotebookCell.is)}NotebookDocument2.is=is2})(NotebookDocument||(protocol_notebook.NotebookDocument=NotebookDocument={}));var NotebookDocumentSyncRegistrationType;(function(NotebookDocumentSyncRegistrationType2){NotebookDocumentSyncRegistrationType2.method="notebookDocument/sync",NotebookDocumentSyncRegistrationType2.messageDirection=messages_1.MessageDirection.clientToServer,NotebookDocumentSyncRegistrationType2.type=new messages_1.RegistrationType(NotebookDocumentSyncRegistrationType2.method)})(NotebookDocumentSyncRegistrationType||(protocol_notebook.NotebookDocumentSyncRegistrationType=NotebookDocumentSyncRegistrationType={}));var DidOpenNotebookDocumentNotification;(function(DidOpenNotebookDocumentNotification2){DidOpenNotebookDocumentNotification2.method="notebookDocument/didOpen",DidOpenNotebookDocumentNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidOpenNotebookDocumentNotification2.type=new messages_1.ProtocolNotificationType(DidOpenNotebookDocumentNotification2.method),DidOpenNotebookDocumentNotification2.registrationMethod=NotebookDocumentSyncRegistrationType.method})(DidOpenNotebookDocumentNotification||(protocol_notebook.DidOpenNotebookDocumentNotification=DidOpenNotebookDocumentNotification={}));var NotebookCellArrayChange;(function(NotebookCellArrayChange2){function is2(value){const candidate=value;return Is2.objectLiteral(candidate)&&vscode_languageserver_types_1.uinteger.is(candidate.start)&&vscode_languageserver_types_1.uinteger.is(candidate.deleteCount)&&(candidate.cells===void 0||Is2.typedArray(candidate.cells,NotebookCell.is))}NotebookCellArrayChange2.is=is2;function create(start,deleteCount,cells){const result={start,deleteCount};return cells!==void 0&&(result.cells=cells),result}NotebookCellArrayChange2.create=create})(NotebookCellArrayChange||(protocol_notebook.NotebookCellArrayChange=NotebookCellArrayChange={}));var DidChangeNotebookDocumentNotification;(function(DidChangeNotebookDocumentNotification2){DidChangeNotebookDocumentNotification2.method="notebookDocument/didChange",DidChangeNotebookDocumentNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidChangeNotebookDocumentNotification2.type=new messages_1.ProtocolNotificationType(DidChangeNotebookDocumentNotification2.method),DidChangeNotebookDocumentNotification2.registrationMethod=NotebookDocumentSyncRegistrationType.method})(DidChangeNotebookDocumentNotification||(protocol_notebook.DidChangeNotebookDocumentNotification=DidChangeNotebookDocumentNotification={}));var DidSaveNotebookDocumentNotification;(function(DidSaveNotebookDocumentNotification2){DidSaveNotebookDocumentNotification2.method="notebookDocument/didSave",DidSaveNotebookDocumentNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidSaveNotebookDocumentNotification2.type=new messages_1.ProtocolNotificationType(DidSaveNotebookDocumentNotification2.method),DidSaveNotebookDocumentNotification2.registrationMethod=NotebookDocumentSyncRegistrationType.method})(DidSaveNotebookDocumentNotification||(protocol_notebook.DidSaveNotebookDocumentNotification=DidSaveNotebookDocumentNotification={}));var DidCloseNotebookDocumentNotification;return(function(DidCloseNotebookDocumentNotification2){DidCloseNotebookDocumentNotification2.method="notebookDocument/didClose",DidCloseNotebookDocumentNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidCloseNotebookDocumentNotification2.type=new messages_1.ProtocolNotificationType(DidCloseNotebookDocumentNotification2.method),DidCloseNotebookDocumentNotification2.registrationMethod=NotebookDocumentSyncRegistrationType.method})(DidCloseNotebookDocumentNotification||(protocol_notebook.DidCloseNotebookDocumentNotification=DidCloseNotebookDocumentNotification={})),protocol_notebook}var protocol_inlineCompletion={},hasRequiredProtocol_inlineCompletion;function requireProtocol_inlineCompletion(){if(hasRequiredProtocol_inlineCompletion)return protocol_inlineCompletion;hasRequiredProtocol_inlineCompletion=1,Object.defineProperty(protocol_inlineCompletion,"__esModule",{value:!0}),protocol_inlineCompletion.InlineCompletionRequest=void 0;const messages_1=requireMessages();var InlineCompletionRequest;return(function(InlineCompletionRequest2){InlineCompletionRequest2.method="textDocument/inlineCompletion",InlineCompletionRequest2.messageDirection=messages_1.MessageDirection.clientToServer,InlineCompletionRequest2.type=new messages_1.ProtocolRequestType(InlineCompletionRequest2.method)})(InlineCompletionRequest||(protocol_inlineCompletion.InlineCompletionRequest=InlineCompletionRequest={})),protocol_inlineCompletion}var hasRequiredProtocol;function requireProtocol(){return hasRequiredProtocol||(hasRequiredProtocol=1,(function(exports$1){Object.defineProperty(exports$1,"__esModule",{value:!0}),exports$1.WorkspaceSymbolRequest=exports$1.CodeActionResolveRequest=exports$1.CodeActionRequest=exports$1.DocumentSymbolRequest=exports$1.DocumentHighlightRequest=exports$1.ReferencesRequest=exports$1.DefinitionRequest=exports$1.SignatureHelpRequest=exports$1.SignatureHelpTriggerKind=exports$1.HoverRequest=exports$1.CompletionResolveRequest=exports$1.CompletionRequest=exports$1.CompletionTriggerKind=exports$1.PublishDiagnosticsNotification=exports$1.WatchKind=exports$1.RelativePattern=exports$1.FileChangeType=exports$1.DidChangeWatchedFilesNotification=exports$1.WillSaveTextDocumentWaitUntilRequest=exports$1.WillSaveTextDocumentNotification=exports$1.TextDocumentSaveReason=exports$1.DidSaveTextDocumentNotification=exports$1.DidCloseTextDocumentNotification=exports$1.DidChangeTextDocumentNotification=exports$1.TextDocumentContentChangeEvent=exports$1.DidOpenTextDocumentNotification=exports$1.TextDocumentSyncKind=exports$1.TelemetryEventNotification=exports$1.LogMessageNotification=exports$1.ShowMessageRequest=exports$1.ShowMessageNotification=exports$1.MessageType=exports$1.DidChangeConfigurationNotification=exports$1.ExitNotification=exports$1.ShutdownRequest=exports$1.InitializedNotification=exports$1.InitializeErrorCodes=exports$1.InitializeRequest=exports$1.WorkDoneProgressOptions=exports$1.TextDocumentRegistrationOptions=exports$1.StaticRegistrationOptions=exports$1.PositionEncodingKind=exports$1.FailureHandlingKind=exports$1.ResourceOperationKind=exports$1.UnregistrationRequest=exports$1.RegistrationRequest=exports$1.DocumentSelector=exports$1.NotebookCellTextDocumentFilter=exports$1.NotebookDocumentFilter=exports$1.TextDocumentFilter=void 0,exports$1.MonikerRequest=exports$1.MonikerKind=exports$1.UniquenessLevel=exports$1.WillDeleteFilesRequest=exports$1.DidDeleteFilesNotification=exports$1.WillRenameFilesRequest=exports$1.DidRenameFilesNotification=exports$1.WillCreateFilesRequest=exports$1.DidCreateFilesNotification=exports$1.FileOperationPatternKind=exports$1.LinkedEditingRangeRequest=exports$1.ShowDocumentRequest=exports$1.SemanticTokensRegistrationType=exports$1.SemanticTokensRefreshRequest=exports$1.SemanticTokensRangeRequest=exports$1.SemanticTokensDeltaRequest=exports$1.SemanticTokensRequest=exports$1.TokenFormat=exports$1.CallHierarchyPrepareRequest=exports$1.CallHierarchyOutgoingCallsRequest=exports$1.CallHierarchyIncomingCallsRequest=exports$1.WorkDoneProgressCancelNotification=exports$1.WorkDoneProgressCreateRequest=exports$1.WorkDoneProgress=exports$1.SelectionRangeRequest=exports$1.DeclarationRequest=exports$1.FoldingRangeRefreshRequest=exports$1.FoldingRangeRequest=exports$1.ColorPresentationRequest=exports$1.DocumentColorRequest=exports$1.ConfigurationRequest=exports$1.DidChangeWorkspaceFoldersNotification=exports$1.WorkspaceFoldersRequest=exports$1.TypeDefinitionRequest=exports$1.ImplementationRequest=exports$1.ApplyWorkspaceEditRequest=exports$1.ExecuteCommandRequest=exports$1.PrepareRenameRequest=exports$1.RenameRequest=exports$1.PrepareSupportDefaultBehavior=exports$1.DocumentOnTypeFormattingRequest=exports$1.DocumentRangesFormattingRequest=exports$1.DocumentRangeFormattingRequest=exports$1.DocumentFormattingRequest=exports$1.DocumentLinkResolveRequest=exports$1.DocumentLinkRequest=exports$1.CodeLensRefreshRequest=exports$1.CodeLensResolveRequest=exports$1.CodeLensRequest=exports$1.WorkspaceSymbolResolveRequest=void 0,exports$1.InlineCompletionRequest=exports$1.DidCloseNotebookDocumentNotification=exports$1.DidSaveNotebookDocumentNotification=exports$1.DidChangeNotebookDocumentNotification=exports$1.NotebookCellArrayChange=exports$1.DidOpenNotebookDocumentNotification=exports$1.NotebookDocumentSyncRegistrationType=exports$1.NotebookDocument=exports$1.NotebookCell=exports$1.ExecutionSummary=exports$1.NotebookCellKind=exports$1.DiagnosticRefreshRequest=exports$1.WorkspaceDiagnosticRequest=exports$1.DocumentDiagnosticRequest=exports$1.DocumentDiagnosticReportKind=exports$1.DiagnosticServerCancellationData=exports$1.InlayHintRefreshRequest=exports$1.InlayHintResolveRequest=exports$1.InlayHintRequest=exports$1.InlineValueRefreshRequest=exports$1.InlineValueRequest=exports$1.TypeHierarchySupertypesRequest=exports$1.TypeHierarchySubtypesRequest=exports$1.TypeHierarchyPrepareRequest=void 0;const messages_1=requireMessages(),vscode_languageserver_types_1=require$$1,Is2=requireIs(),protocol_implementation_1=requireProtocol_implementation();Object.defineProperty(exports$1,"ImplementationRequest",{enumerable:!0,get:function(){return protocol_implementation_1.ImplementationRequest}});const protocol_typeDefinition_1=requireProtocol_typeDefinition();Object.defineProperty(exports$1,"TypeDefinitionRequest",{enumerable:!0,get:function(){return protocol_typeDefinition_1.TypeDefinitionRequest}});const protocol_workspaceFolder_1=requireProtocol_workspaceFolder();Object.defineProperty(exports$1,"WorkspaceFoldersRequest",{enumerable:!0,get:function(){return protocol_workspaceFolder_1.WorkspaceFoldersRequest}}),Object.defineProperty(exports$1,"DidChangeWorkspaceFoldersNotification",{enumerable:!0,get:function(){return protocol_workspaceFolder_1.DidChangeWorkspaceFoldersNotification}});const protocol_configuration_1=requireProtocol_configuration();Object.defineProperty(exports$1,"ConfigurationRequest",{enumerable:!0,get:function(){return protocol_configuration_1.ConfigurationRequest}});const protocol_colorProvider_1=requireProtocol_colorProvider();Object.defineProperty(exports$1,"DocumentColorRequest",{enumerable:!0,get:function(){return protocol_colorProvider_1.DocumentColorRequest}}),Object.defineProperty(exports$1,"ColorPresentationRequest",{enumerable:!0,get:function(){return protocol_colorProvider_1.ColorPresentationRequest}});const protocol_foldingRange_1=requireProtocol_foldingRange();Object.defineProperty(exports$1,"FoldingRangeRequest",{enumerable:!0,get:function(){return protocol_foldingRange_1.FoldingRangeRequest}}),Object.defineProperty(exports$1,"FoldingRangeRefreshRequest",{enumerable:!0,get:function(){return protocol_foldingRange_1.FoldingRangeRefreshRequest}});const protocol_declaration_1=requireProtocol_declaration();Object.defineProperty(exports$1,"DeclarationRequest",{enumerable:!0,get:function(){return protocol_declaration_1.DeclarationRequest}});const protocol_selectionRange_1=requireProtocol_selectionRange();Object.defineProperty(exports$1,"SelectionRangeRequest",{enumerable:!0,get:function(){return protocol_selectionRange_1.SelectionRangeRequest}});const protocol_progress_1=requireProtocol_progress();Object.defineProperty(exports$1,"WorkDoneProgress",{enumerable:!0,get:function(){return protocol_progress_1.WorkDoneProgress}}),Object.defineProperty(exports$1,"WorkDoneProgressCreateRequest",{enumerable:!0,get:function(){return protocol_progress_1.WorkDoneProgressCreateRequest}}),Object.defineProperty(exports$1,"WorkDoneProgressCancelNotification",{enumerable:!0,get:function(){return protocol_progress_1.WorkDoneProgressCancelNotification}});const protocol_callHierarchy_1=requireProtocol_callHierarchy();Object.defineProperty(exports$1,"CallHierarchyIncomingCallsRequest",{enumerable:!0,get:function(){return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest}}),Object.defineProperty(exports$1,"CallHierarchyOutgoingCallsRequest",{enumerable:!0,get:function(){return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest}}),Object.defineProperty(exports$1,"CallHierarchyPrepareRequest",{enumerable:!0,get:function(){return protocol_callHierarchy_1.CallHierarchyPrepareRequest}});const protocol_semanticTokens_1=requireProtocol_semanticTokens();Object.defineProperty(exports$1,"TokenFormat",{enumerable:!0,get:function(){return protocol_semanticTokens_1.TokenFormat}}),Object.defineProperty(exports$1,"SemanticTokensRequest",{enumerable:!0,get:function(){return protocol_semanticTokens_1.SemanticTokensRequest}}),Object.defineProperty(exports$1,"SemanticTokensDeltaRequest",{enumerable:!0,get:function(){return protocol_semanticTokens_1.SemanticTokensDeltaRequest}}),Object.defineProperty(exports$1,"SemanticTokensRangeRequest",{enumerable:!0,get:function(){return protocol_semanticTokens_1.SemanticTokensRangeRequest}}),Object.defineProperty(exports$1,"SemanticTokensRefreshRequest",{enumerable:!0,get:function(){return protocol_semanticTokens_1.SemanticTokensRefreshRequest}}),Object.defineProperty(exports$1,"SemanticTokensRegistrationType",{enumerable:!0,get:function(){return protocol_semanticTokens_1.SemanticTokensRegistrationType}});const protocol_showDocument_1=requireProtocol_showDocument();Object.defineProperty(exports$1,"ShowDocumentRequest",{enumerable:!0,get:function(){return protocol_showDocument_1.ShowDocumentRequest}});const protocol_linkedEditingRange_1=requireProtocol_linkedEditingRange();Object.defineProperty(exports$1,"LinkedEditingRangeRequest",{enumerable:!0,get:function(){return protocol_linkedEditingRange_1.LinkedEditingRangeRequest}});const protocol_fileOperations_1=requireProtocol_fileOperations();Object.defineProperty(exports$1,"FileOperationPatternKind",{enumerable:!0,get:function(){return protocol_fileOperations_1.FileOperationPatternKind}}),Object.defineProperty(exports$1,"DidCreateFilesNotification",{enumerable:!0,get:function(){return protocol_fileOperations_1.DidCreateFilesNotification}}),Object.defineProperty(exports$1,"WillCreateFilesRequest",{enumerable:!0,get:function(){return protocol_fileOperations_1.WillCreateFilesRequest}}),Object.defineProperty(exports$1,"DidRenameFilesNotification",{enumerable:!0,get:function(){return protocol_fileOperations_1.DidRenameFilesNotification}}),Object.defineProperty(exports$1,"WillRenameFilesRequest",{enumerable:!0,get:function(){return protocol_fileOperations_1.WillRenameFilesRequest}}),Object.defineProperty(exports$1,"DidDeleteFilesNotification",{enumerable:!0,get:function(){return protocol_fileOperations_1.DidDeleteFilesNotification}}),Object.defineProperty(exports$1,"WillDeleteFilesRequest",{enumerable:!0,get:function(){return protocol_fileOperations_1.WillDeleteFilesRequest}});const protocol_moniker_1=requireProtocol_moniker();Object.defineProperty(exports$1,"UniquenessLevel",{enumerable:!0,get:function(){return protocol_moniker_1.UniquenessLevel}}),Object.defineProperty(exports$1,"MonikerKind",{enumerable:!0,get:function(){return protocol_moniker_1.MonikerKind}}),Object.defineProperty(exports$1,"MonikerRequest",{enumerable:!0,get:function(){return protocol_moniker_1.MonikerRequest}});const protocol_typeHierarchy_1=requireProtocol_typeHierarchy();Object.defineProperty(exports$1,"TypeHierarchyPrepareRequest",{enumerable:!0,get:function(){return protocol_typeHierarchy_1.TypeHierarchyPrepareRequest}}),Object.defineProperty(exports$1,"TypeHierarchySubtypesRequest",{enumerable:!0,get:function(){return protocol_typeHierarchy_1.TypeHierarchySubtypesRequest}}),Object.defineProperty(exports$1,"TypeHierarchySupertypesRequest",{enumerable:!0,get:function(){return protocol_typeHierarchy_1.TypeHierarchySupertypesRequest}});const protocol_inlineValue_1=requireProtocol_inlineValue();Object.defineProperty(exports$1,"InlineValueRequest",{enumerable:!0,get:function(){return protocol_inlineValue_1.InlineValueRequest}}),Object.defineProperty(exports$1,"InlineValueRefreshRequest",{enumerable:!0,get:function(){return protocol_inlineValue_1.InlineValueRefreshRequest}});const protocol_inlayHint_1=requireProtocol_inlayHint();Object.defineProperty(exports$1,"InlayHintRequest",{enumerable:!0,get:function(){return protocol_inlayHint_1.InlayHintRequest}}),Object.defineProperty(exports$1,"InlayHintResolveRequest",{enumerable:!0,get:function(){return protocol_inlayHint_1.InlayHintResolveRequest}}),Object.defineProperty(exports$1,"InlayHintRefreshRequest",{enumerable:!0,get:function(){return protocol_inlayHint_1.InlayHintRefreshRequest}});const protocol_diagnostic_1=requireProtocol_diagnostic();Object.defineProperty(exports$1,"DiagnosticServerCancellationData",{enumerable:!0,get:function(){return protocol_diagnostic_1.DiagnosticServerCancellationData}}),Object.defineProperty(exports$1,"DocumentDiagnosticReportKind",{enumerable:!0,get:function(){return protocol_diagnostic_1.DocumentDiagnosticReportKind}}),Object.defineProperty(exports$1,"DocumentDiagnosticRequest",{enumerable:!0,get:function(){return protocol_diagnostic_1.DocumentDiagnosticRequest}}),Object.defineProperty(exports$1,"WorkspaceDiagnosticRequest",{enumerable:!0,get:function(){return protocol_diagnostic_1.WorkspaceDiagnosticRequest}}),Object.defineProperty(exports$1,"DiagnosticRefreshRequest",{enumerable:!0,get:function(){return protocol_diagnostic_1.DiagnosticRefreshRequest}});const protocol_notebook_1=requireProtocol_notebook();Object.defineProperty(exports$1,"NotebookCellKind",{enumerable:!0,get:function(){return protocol_notebook_1.NotebookCellKind}}),Object.defineProperty(exports$1,"ExecutionSummary",{enumerable:!0,get:function(){return protocol_notebook_1.ExecutionSummary}}),Object.defineProperty(exports$1,"NotebookCell",{enumerable:!0,get:function(){return protocol_notebook_1.NotebookCell}}),Object.defineProperty(exports$1,"NotebookDocument",{enumerable:!0,get:function(){return protocol_notebook_1.NotebookDocument}}),Object.defineProperty(exports$1,"NotebookDocumentSyncRegistrationType",{enumerable:!0,get:function(){return protocol_notebook_1.NotebookDocumentSyncRegistrationType}}),Object.defineProperty(exports$1,"DidOpenNotebookDocumentNotification",{enumerable:!0,get:function(){return protocol_notebook_1.DidOpenNotebookDocumentNotification}}),Object.defineProperty(exports$1,"NotebookCellArrayChange",{enumerable:!0,get:function(){return protocol_notebook_1.NotebookCellArrayChange}}),Object.defineProperty(exports$1,"DidChangeNotebookDocumentNotification",{enumerable:!0,get:function(){return protocol_notebook_1.DidChangeNotebookDocumentNotification}}),Object.defineProperty(exports$1,"DidSaveNotebookDocumentNotification",{enumerable:!0,get:function(){return protocol_notebook_1.DidSaveNotebookDocumentNotification}}),Object.defineProperty(exports$1,"DidCloseNotebookDocumentNotification",{enumerable:!0,get:function(){return protocol_notebook_1.DidCloseNotebookDocumentNotification}});const protocol_inlineCompletion_1=requireProtocol_inlineCompletion();Object.defineProperty(exports$1,"InlineCompletionRequest",{enumerable:!0,get:function(){return protocol_inlineCompletion_1.InlineCompletionRequest}});var TextDocumentFilter;(function(TextDocumentFilter2){function is2(value){const candidate=value;return Is2.string(candidate)||Is2.string(candidate.language)||Is2.string(candidate.scheme)||Is2.string(candidate.pattern)}TextDocumentFilter2.is=is2})(TextDocumentFilter||(exports$1.TextDocumentFilter=TextDocumentFilter={}));var NotebookDocumentFilter;(function(NotebookDocumentFilter2){function is2(value){const candidate=value;return Is2.objectLiteral(candidate)&&(Is2.string(candidate.notebookType)||Is2.string(candidate.scheme)||Is2.string(candidate.pattern))}NotebookDocumentFilter2.is=is2})(NotebookDocumentFilter||(exports$1.NotebookDocumentFilter=NotebookDocumentFilter={}));var NotebookCellTextDocumentFilter;(function(NotebookCellTextDocumentFilter2){function is2(value){const candidate=value;return Is2.objectLiteral(candidate)&&(Is2.string(candidate.notebook)||NotebookDocumentFilter.is(candidate.notebook))&&(candidate.language===void 0||Is2.string(candidate.language))}NotebookCellTextDocumentFilter2.is=is2})(NotebookCellTextDocumentFilter||(exports$1.NotebookCellTextDocumentFilter=NotebookCellTextDocumentFilter={}));var DocumentSelector;(function(DocumentSelector2){function is2(value){if(!Array.isArray(value))return!1;for(let elem of value)if(!Is2.string(elem)&&!TextDocumentFilter.is(elem)&&!NotebookCellTextDocumentFilter.is(elem))return!1;return!0}DocumentSelector2.is=is2})(DocumentSelector||(exports$1.DocumentSelector=DocumentSelector={}));var RegistrationRequest;(function(RegistrationRequest2){RegistrationRequest2.method="client/registerCapability",RegistrationRequest2.messageDirection=messages_1.MessageDirection.serverToClient,RegistrationRequest2.type=new messages_1.ProtocolRequestType(RegistrationRequest2.method)})(RegistrationRequest||(exports$1.RegistrationRequest=RegistrationRequest={}));var UnregistrationRequest;(function(UnregistrationRequest2){UnregistrationRequest2.method="client/unregisterCapability",UnregistrationRequest2.messageDirection=messages_1.MessageDirection.serverToClient,UnregistrationRequest2.type=new messages_1.ProtocolRequestType(UnregistrationRequest2.method)})(UnregistrationRequest||(exports$1.UnregistrationRequest=UnregistrationRequest={}));var ResourceOperationKind;(function(ResourceOperationKind2){ResourceOperationKind2.Create="create",ResourceOperationKind2.Rename="rename",ResourceOperationKind2.Delete="delete"})(ResourceOperationKind||(exports$1.ResourceOperationKind=ResourceOperationKind={}));var FailureHandlingKind;(function(FailureHandlingKind2){FailureHandlingKind2.Abort="abort",FailureHandlingKind2.Transactional="transactional",FailureHandlingKind2.TextOnlyTransactional="textOnlyTransactional",FailureHandlingKind2.Undo="undo"})(FailureHandlingKind||(exports$1.FailureHandlingKind=FailureHandlingKind={}));var PositionEncodingKind;(function(PositionEncodingKind2){PositionEncodingKind2.UTF8="utf-8",PositionEncodingKind2.UTF16="utf-16",PositionEncodingKind2.UTF32="utf-32"})(PositionEncodingKind||(exports$1.PositionEncodingKind=PositionEncodingKind={}));var StaticRegistrationOptions;(function(StaticRegistrationOptions2){function hasId(value){const candidate=value;return candidate&&Is2.string(candidate.id)&&candidate.id.length>0}StaticRegistrationOptions2.hasId=hasId})(StaticRegistrationOptions||(exports$1.StaticRegistrationOptions=StaticRegistrationOptions={}));var TextDocumentRegistrationOptions;(function(TextDocumentRegistrationOptions2){function is2(value){const candidate=value;return candidate&&(candidate.documentSelector===null||DocumentSelector.is(candidate.documentSelector))}TextDocumentRegistrationOptions2.is=is2})(TextDocumentRegistrationOptions||(exports$1.TextDocumentRegistrationOptions=TextDocumentRegistrationOptions={}));var WorkDoneProgressOptions;(function(WorkDoneProgressOptions2){function is2(value){const candidate=value;return Is2.objectLiteral(candidate)&&(candidate.workDoneProgress===void 0||Is2.boolean(candidate.workDoneProgress))}WorkDoneProgressOptions2.is=is2;function hasWorkDoneProgress(value){const candidate=value;return candidate&&Is2.boolean(candidate.workDoneProgress)}WorkDoneProgressOptions2.hasWorkDoneProgress=hasWorkDoneProgress})(WorkDoneProgressOptions||(exports$1.WorkDoneProgressOptions=WorkDoneProgressOptions={}));var InitializeRequest;(function(InitializeRequest2){InitializeRequest2.method="initialize",InitializeRequest2.messageDirection=messages_1.MessageDirection.clientToServer,InitializeRequest2.type=new messages_1.ProtocolRequestType(InitializeRequest2.method)})(InitializeRequest||(exports$1.InitializeRequest=InitializeRequest={}));var InitializeErrorCodes;(function(InitializeErrorCodes2){InitializeErrorCodes2.unknownProtocolVersion=1})(InitializeErrorCodes||(exports$1.InitializeErrorCodes=InitializeErrorCodes={}));var InitializedNotification;(function(InitializedNotification2){InitializedNotification2.method="initialized",InitializedNotification2.messageDirection=messages_1.MessageDirection.clientToServer,InitializedNotification2.type=new messages_1.ProtocolNotificationType(InitializedNotification2.method)})(InitializedNotification||(exports$1.InitializedNotification=InitializedNotification={}));var ShutdownRequest;(function(ShutdownRequest2){ShutdownRequest2.method="shutdown",ShutdownRequest2.messageDirection=messages_1.MessageDirection.clientToServer,ShutdownRequest2.type=new messages_1.ProtocolRequestType0(ShutdownRequest2.method)})(ShutdownRequest||(exports$1.ShutdownRequest=ShutdownRequest={}));var ExitNotification;(function(ExitNotification2){ExitNotification2.method="exit",ExitNotification2.messageDirection=messages_1.MessageDirection.clientToServer,ExitNotification2.type=new messages_1.ProtocolNotificationType0(ExitNotification2.method)})(ExitNotification||(exports$1.ExitNotification=ExitNotification={}));var DidChangeConfigurationNotification;(function(DidChangeConfigurationNotification2){DidChangeConfigurationNotification2.method="workspace/didChangeConfiguration",DidChangeConfigurationNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidChangeConfigurationNotification2.type=new messages_1.ProtocolNotificationType(DidChangeConfigurationNotification2.method)})(DidChangeConfigurationNotification||(exports$1.DidChangeConfigurationNotification=DidChangeConfigurationNotification={}));var MessageType;(function(MessageType2){MessageType2.Error=1,MessageType2.Warning=2,MessageType2.Info=3,MessageType2.Log=4,MessageType2.Debug=5})(MessageType||(exports$1.MessageType=MessageType={}));var ShowMessageNotification;(function(ShowMessageNotification2){ShowMessageNotification2.method="window/showMessage",ShowMessageNotification2.messageDirection=messages_1.MessageDirection.serverToClient,ShowMessageNotification2.type=new messages_1.ProtocolNotificationType(ShowMessageNotification2.method)})(ShowMessageNotification||(exports$1.ShowMessageNotification=ShowMessageNotification={}));var ShowMessageRequest;(function(ShowMessageRequest2){ShowMessageRequest2.method="window/showMessageRequest",ShowMessageRequest2.messageDirection=messages_1.MessageDirection.serverToClient,ShowMessageRequest2.type=new messages_1.ProtocolRequestType(ShowMessageRequest2.method)})(ShowMessageRequest||(exports$1.ShowMessageRequest=ShowMessageRequest={}));var LogMessageNotification;(function(LogMessageNotification2){LogMessageNotification2.method="window/logMessage",LogMessageNotification2.messageDirection=messages_1.MessageDirection.serverToClient,LogMessageNotification2.type=new messages_1.ProtocolNotificationType(LogMessageNotification2.method)})(LogMessageNotification||(exports$1.LogMessageNotification=LogMessageNotification={}));var TelemetryEventNotification;(function(TelemetryEventNotification2){TelemetryEventNotification2.method="telemetry/event",TelemetryEventNotification2.messageDirection=messages_1.MessageDirection.serverToClient,TelemetryEventNotification2.type=new messages_1.ProtocolNotificationType(TelemetryEventNotification2.method)})(TelemetryEventNotification||(exports$1.TelemetryEventNotification=TelemetryEventNotification={}));var TextDocumentSyncKind;(function(TextDocumentSyncKind2){TextDocumentSyncKind2.None=0,TextDocumentSyncKind2.Full=1,TextDocumentSyncKind2.Incremental=2})(TextDocumentSyncKind||(exports$1.TextDocumentSyncKind=TextDocumentSyncKind={}));var DidOpenTextDocumentNotification;(function(DidOpenTextDocumentNotification2){DidOpenTextDocumentNotification2.method="textDocument/didOpen",DidOpenTextDocumentNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidOpenTextDocumentNotification2.type=new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification2.method)})(DidOpenTextDocumentNotification||(exports$1.DidOpenTextDocumentNotification=DidOpenTextDocumentNotification={}));var TextDocumentContentChangeEvent;(function(TextDocumentContentChangeEvent2){function isIncremental(event){let candidate=event;return candidate!=null&&typeof candidate.text=="string"&&candidate.range!==void 0&&(candidate.rangeLength===void 0||typeof candidate.rangeLength=="number")}TextDocumentContentChangeEvent2.isIncremental=isIncremental;function isFull(event){let candidate=event;return candidate!=null&&typeof candidate.text=="string"&&candidate.range===void 0&&candidate.rangeLength===void 0}TextDocumentContentChangeEvent2.isFull=isFull})(TextDocumentContentChangeEvent||(exports$1.TextDocumentContentChangeEvent=TextDocumentContentChangeEvent={}));var DidChangeTextDocumentNotification;(function(DidChangeTextDocumentNotification2){DidChangeTextDocumentNotification2.method="textDocument/didChange",DidChangeTextDocumentNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidChangeTextDocumentNotification2.type=new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification2.method)})(DidChangeTextDocumentNotification||(exports$1.DidChangeTextDocumentNotification=DidChangeTextDocumentNotification={}));var DidCloseTextDocumentNotification;(function(DidCloseTextDocumentNotification2){DidCloseTextDocumentNotification2.method="textDocument/didClose",DidCloseTextDocumentNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidCloseTextDocumentNotification2.type=new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification2.method)})(DidCloseTextDocumentNotification||(exports$1.DidCloseTextDocumentNotification=DidCloseTextDocumentNotification={}));var DidSaveTextDocumentNotification;(function(DidSaveTextDocumentNotification2){DidSaveTextDocumentNotification2.method="textDocument/didSave",DidSaveTextDocumentNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidSaveTextDocumentNotification2.type=new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification2.method)})(DidSaveTextDocumentNotification||(exports$1.DidSaveTextDocumentNotification=DidSaveTextDocumentNotification={}));var TextDocumentSaveReason;(function(TextDocumentSaveReason2){TextDocumentSaveReason2.Manual=1,TextDocumentSaveReason2.AfterDelay=2,TextDocumentSaveReason2.FocusOut=3})(TextDocumentSaveReason||(exports$1.TextDocumentSaveReason=TextDocumentSaveReason={}));var WillSaveTextDocumentNotification;(function(WillSaveTextDocumentNotification2){WillSaveTextDocumentNotification2.method="textDocument/willSave",WillSaveTextDocumentNotification2.messageDirection=messages_1.MessageDirection.clientToServer,WillSaveTextDocumentNotification2.type=new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification2.method)})(WillSaveTextDocumentNotification||(exports$1.WillSaveTextDocumentNotification=WillSaveTextDocumentNotification={}));var WillSaveTextDocumentWaitUntilRequest;(function(WillSaveTextDocumentWaitUntilRequest2){WillSaveTextDocumentWaitUntilRequest2.method="textDocument/willSaveWaitUntil",WillSaveTextDocumentWaitUntilRequest2.messageDirection=messages_1.MessageDirection.clientToServer,WillSaveTextDocumentWaitUntilRequest2.type=new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest2.method)})(WillSaveTextDocumentWaitUntilRequest||(exports$1.WillSaveTextDocumentWaitUntilRequest=WillSaveTextDocumentWaitUntilRequest={}));var DidChangeWatchedFilesNotification;(function(DidChangeWatchedFilesNotification2){DidChangeWatchedFilesNotification2.method="workspace/didChangeWatchedFiles",DidChangeWatchedFilesNotification2.messageDirection=messages_1.MessageDirection.clientToServer,DidChangeWatchedFilesNotification2.type=new messages_1.ProtocolNotificationType(DidChangeWatchedFilesNotification2.method)})(DidChangeWatchedFilesNotification||(exports$1.DidChangeWatchedFilesNotification=DidChangeWatchedFilesNotification={}));var FileChangeType;(function(FileChangeType2){FileChangeType2.Created=1,FileChangeType2.Changed=2,FileChangeType2.Deleted=3})(FileChangeType||(exports$1.FileChangeType=FileChangeType={}));var RelativePattern;(function(RelativePattern2){function is2(value){const candidate=value;return Is2.objectLiteral(candidate)&&(vscode_languageserver_types_1.URI.is(candidate.baseUri)||vscode_languageserver_types_1.WorkspaceFolder.is(candidate.baseUri))&&Is2.string(candidate.pattern)}RelativePattern2.is=is2})(RelativePattern||(exports$1.RelativePattern=RelativePattern={}));var WatchKind;(function(WatchKind2){WatchKind2.Create=1,WatchKind2.Change=2,WatchKind2.Delete=4})(WatchKind||(exports$1.WatchKind=WatchKind={}));var PublishDiagnosticsNotification;(function(PublishDiagnosticsNotification2){PublishDiagnosticsNotification2.method="textDocument/publishDiagnostics",PublishDiagnosticsNotification2.messageDirection=messages_1.MessageDirection.serverToClient,PublishDiagnosticsNotification2.type=new messages_1.ProtocolNotificationType(PublishDiagnosticsNotification2.method)})(PublishDiagnosticsNotification||(exports$1.PublishDiagnosticsNotification=PublishDiagnosticsNotification={}));var CompletionTriggerKind;(function(CompletionTriggerKind2){CompletionTriggerKind2.Invoked=1,CompletionTriggerKind2.TriggerCharacter=2,CompletionTriggerKind2.TriggerForIncompleteCompletions=3})(CompletionTriggerKind||(exports$1.CompletionTriggerKind=CompletionTriggerKind={}));var CompletionRequest;(function(CompletionRequest2){CompletionRequest2.method="textDocument/completion",CompletionRequest2.messageDirection=messages_1.MessageDirection.clientToServer,CompletionRequest2.type=new messages_1.ProtocolRequestType(CompletionRequest2.method)})(CompletionRequest||(exports$1.CompletionRequest=CompletionRequest={}));var CompletionResolveRequest;(function(CompletionResolveRequest2){CompletionResolveRequest2.method="completionItem/resolve",CompletionResolveRequest2.messageDirection=messages_1.MessageDirection.clientToServer,CompletionResolveRequest2.type=new messages_1.ProtocolRequestType(CompletionResolveRequest2.method)})(CompletionResolveRequest||(exports$1.CompletionResolveRequest=CompletionResolveRequest={}));var HoverRequest;(function(HoverRequest2){HoverRequest2.method="textDocument/hover",HoverRequest2.messageDirection=messages_1.MessageDirection.clientToServer,HoverRequest2.type=new messages_1.ProtocolRequestType(HoverRequest2.method)})(HoverRequest||(exports$1.HoverRequest=HoverRequest={}));var SignatureHelpTriggerKind;(function(SignatureHelpTriggerKind2){SignatureHelpTriggerKind2.Invoked=1,SignatureHelpTriggerKind2.TriggerCharacter=2,SignatureHelpTriggerKind2.ContentChange=3})(SignatureHelpTriggerKind||(exports$1.SignatureHelpTriggerKind=SignatureHelpTriggerKind={}));var SignatureHelpRequest;(function(SignatureHelpRequest2){SignatureHelpRequest2.method="textDocument/signatureHelp",SignatureHelpRequest2.messageDirection=messages_1.MessageDirection.clientToServer,SignatureHelpRequest2.type=new messages_1.ProtocolRequestType(SignatureHelpRequest2.method)})(SignatureHelpRequest||(exports$1.SignatureHelpRequest=SignatureHelpRequest={}));var DefinitionRequest;(function(DefinitionRequest2){DefinitionRequest2.method="textDocument/definition",DefinitionRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DefinitionRequest2.type=new messages_1.ProtocolRequestType(DefinitionRequest2.method)})(DefinitionRequest||(exports$1.DefinitionRequest=DefinitionRequest={}));var ReferencesRequest;(function(ReferencesRequest2){ReferencesRequest2.method="textDocument/references",ReferencesRequest2.messageDirection=messages_1.MessageDirection.clientToServer,ReferencesRequest2.type=new messages_1.ProtocolRequestType(ReferencesRequest2.method)})(ReferencesRequest||(exports$1.ReferencesRequest=ReferencesRequest={}));var DocumentHighlightRequest;(function(DocumentHighlightRequest2){DocumentHighlightRequest2.method="textDocument/documentHighlight",DocumentHighlightRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DocumentHighlightRequest2.type=new messages_1.ProtocolRequestType(DocumentHighlightRequest2.method)})(DocumentHighlightRequest||(exports$1.DocumentHighlightRequest=DocumentHighlightRequest={}));var DocumentSymbolRequest;(function(DocumentSymbolRequest2){DocumentSymbolRequest2.method="textDocument/documentSymbol",DocumentSymbolRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DocumentSymbolRequest2.type=new messages_1.ProtocolRequestType(DocumentSymbolRequest2.method)})(DocumentSymbolRequest||(exports$1.DocumentSymbolRequest=DocumentSymbolRequest={}));var CodeActionRequest;(function(CodeActionRequest2){CodeActionRequest2.method="textDocument/codeAction",CodeActionRequest2.messageDirection=messages_1.MessageDirection.clientToServer,CodeActionRequest2.type=new messages_1.ProtocolRequestType(CodeActionRequest2.method)})(CodeActionRequest||(exports$1.CodeActionRequest=CodeActionRequest={}));var CodeActionResolveRequest;(function(CodeActionResolveRequest2){CodeActionResolveRequest2.method="codeAction/resolve",CodeActionResolveRequest2.messageDirection=messages_1.MessageDirection.clientToServer,CodeActionResolveRequest2.type=new messages_1.ProtocolRequestType(CodeActionResolveRequest2.method)})(CodeActionResolveRequest||(exports$1.CodeActionResolveRequest=CodeActionResolveRequest={}));var WorkspaceSymbolRequest;(function(WorkspaceSymbolRequest2){WorkspaceSymbolRequest2.method="workspace/symbol",WorkspaceSymbolRequest2.messageDirection=messages_1.MessageDirection.clientToServer,WorkspaceSymbolRequest2.type=new messages_1.ProtocolRequestType(WorkspaceSymbolRequest2.method)})(WorkspaceSymbolRequest||(exports$1.WorkspaceSymbolRequest=WorkspaceSymbolRequest={}));var WorkspaceSymbolResolveRequest;(function(WorkspaceSymbolResolveRequest2){WorkspaceSymbolResolveRequest2.method="workspaceSymbol/resolve",WorkspaceSymbolResolveRequest2.messageDirection=messages_1.MessageDirection.clientToServer,WorkspaceSymbolResolveRequest2.type=new messages_1.ProtocolRequestType(WorkspaceSymbolResolveRequest2.method)})(WorkspaceSymbolResolveRequest||(exports$1.WorkspaceSymbolResolveRequest=WorkspaceSymbolResolveRequest={}));var CodeLensRequest;(function(CodeLensRequest2){CodeLensRequest2.method="textDocument/codeLens",CodeLensRequest2.messageDirection=messages_1.MessageDirection.clientToServer,CodeLensRequest2.type=new messages_1.ProtocolRequestType(CodeLensRequest2.method)})(CodeLensRequest||(exports$1.CodeLensRequest=CodeLensRequest={}));var CodeLensResolveRequest;(function(CodeLensResolveRequest2){CodeLensResolveRequest2.method="codeLens/resolve",CodeLensResolveRequest2.messageDirection=messages_1.MessageDirection.clientToServer,CodeLensResolveRequest2.type=new messages_1.ProtocolRequestType(CodeLensResolveRequest2.method)})(CodeLensResolveRequest||(exports$1.CodeLensResolveRequest=CodeLensResolveRequest={}));var CodeLensRefreshRequest;(function(CodeLensRefreshRequest2){CodeLensRefreshRequest2.method="workspace/codeLens/refresh",CodeLensRefreshRequest2.messageDirection=messages_1.MessageDirection.serverToClient,CodeLensRefreshRequest2.type=new messages_1.ProtocolRequestType0(CodeLensRefreshRequest2.method)})(CodeLensRefreshRequest||(exports$1.CodeLensRefreshRequest=CodeLensRefreshRequest={}));var DocumentLinkRequest;(function(DocumentLinkRequest2){DocumentLinkRequest2.method="textDocument/documentLink",DocumentLinkRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DocumentLinkRequest2.type=new messages_1.ProtocolRequestType(DocumentLinkRequest2.method)})(DocumentLinkRequest||(exports$1.DocumentLinkRequest=DocumentLinkRequest={}));var DocumentLinkResolveRequest;(function(DocumentLinkResolveRequest2){DocumentLinkResolveRequest2.method="documentLink/resolve",DocumentLinkResolveRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DocumentLinkResolveRequest2.type=new messages_1.ProtocolRequestType(DocumentLinkResolveRequest2.method)})(DocumentLinkResolveRequest||(exports$1.DocumentLinkResolveRequest=DocumentLinkResolveRequest={}));var DocumentFormattingRequest;(function(DocumentFormattingRequest2){DocumentFormattingRequest2.method="textDocument/formatting",DocumentFormattingRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DocumentFormattingRequest2.type=new messages_1.ProtocolRequestType(DocumentFormattingRequest2.method)})(DocumentFormattingRequest||(exports$1.DocumentFormattingRequest=DocumentFormattingRequest={}));var DocumentRangeFormattingRequest;(function(DocumentRangeFormattingRequest2){DocumentRangeFormattingRequest2.method="textDocument/rangeFormatting",DocumentRangeFormattingRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DocumentRangeFormattingRequest2.type=new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest2.method)})(DocumentRangeFormattingRequest||(exports$1.DocumentRangeFormattingRequest=DocumentRangeFormattingRequest={}));var DocumentRangesFormattingRequest;(function(DocumentRangesFormattingRequest2){DocumentRangesFormattingRequest2.method="textDocument/rangesFormatting",DocumentRangesFormattingRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DocumentRangesFormattingRequest2.type=new messages_1.ProtocolRequestType(DocumentRangesFormattingRequest2.method)})(DocumentRangesFormattingRequest||(exports$1.DocumentRangesFormattingRequest=DocumentRangesFormattingRequest={}));var DocumentOnTypeFormattingRequest;(function(DocumentOnTypeFormattingRequest2){DocumentOnTypeFormattingRequest2.method="textDocument/onTypeFormatting",DocumentOnTypeFormattingRequest2.messageDirection=messages_1.MessageDirection.clientToServer,DocumentOnTypeFormattingRequest2.type=new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest2.method)})(DocumentOnTypeFormattingRequest||(exports$1.DocumentOnTypeFormattingRequest=DocumentOnTypeFormattingRequest={}));var PrepareSupportDefaultBehavior;(function(PrepareSupportDefaultBehavior2){PrepareSupportDefaultBehavior2.Identifier=1})(PrepareSupportDefaultBehavior||(exports$1.PrepareSupportDefaultBehavior=PrepareSupportDefaultBehavior={}));var RenameRequest;(function(RenameRequest2){RenameRequest2.method="textDocument/rename",RenameRequest2.messageDirection=messages_1.MessageDirection.clientToServer,RenameRequest2.type=new messages_1.ProtocolRequestType(RenameRequest2.method)})(RenameRequest||(exports$1.RenameRequest=RenameRequest={}));var PrepareRenameRequest;(function(PrepareRenameRequest2){PrepareRenameRequest2.method="textDocument/prepareRename",PrepareRenameRequest2.messageDirection=messages_1.MessageDirection.clientToServer,PrepareRenameRequest2.type=new messages_1.ProtocolRequestType(PrepareRenameRequest2.method)})(PrepareRenameRequest||(exports$1.PrepareRenameRequest=PrepareRenameRequest={}));var ExecuteCommandRequest;(function(ExecuteCommandRequest2){ExecuteCommandRequest2.method="workspace/executeCommand",ExecuteCommandRequest2.messageDirection=messages_1.MessageDirection.clientToServer,ExecuteCommandRequest2.type=new messages_1.ProtocolRequestType(ExecuteCommandRequest2.method)})(ExecuteCommandRequest||(exports$1.ExecuteCommandRequest=ExecuteCommandRequest={}));var ApplyWorkspaceEditRequest;(function(ApplyWorkspaceEditRequest2){ApplyWorkspaceEditRequest2.method="workspace/applyEdit",ApplyWorkspaceEditRequest2.messageDirection=messages_1.MessageDirection.serverToClient,ApplyWorkspaceEditRequest2.type=new messages_1.ProtocolRequestType("workspace/applyEdit")})(ApplyWorkspaceEditRequest||(exports$1.ApplyWorkspaceEditRequest=ApplyWorkspaceEditRequest={}))})(protocol)),protocol}var connection={},hasRequiredConnection;function requireConnection(){if(hasRequiredConnection)return connection;hasRequiredConnection=1,Object.defineProperty(connection,"__esModule",{value:!0}),connection.createProtocolConnection=void 0;const vscode_jsonrpc_1=requireMain$1();function createProtocolConnection(input,output,logger,options){return vscode_jsonrpc_1.ConnectionStrategy.is(options)&&(options={connectionStrategy:options}),(0,vscode_jsonrpc_1.createMessageConnection)(input,output,logger,options)}return connection.createProtocolConnection=createProtocolConnection,connection}var hasRequiredApi;function requireApi(){return hasRequiredApi||(hasRequiredApi=1,(function(exports$1){var __createBinding=api&&api.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=api&&api.__exportStar||function(m,exports$12){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports$12,p)&&__createBinding(exports$12,m,p)};Object.defineProperty(exports$1,"__esModule",{value:!0}),exports$1.LSPErrorCodes=exports$1.createProtocolConnection=void 0,__exportStar(requireMain$1(),exports$1),__exportStar(require$$1,exports$1),__exportStar(requireMessages(),exports$1),__exportStar(requireProtocol(),exports$1);var connection_1=requireConnection();Object.defineProperty(exports$1,"createProtocolConnection",{enumerable:!0,get:function(){return connection_1.createProtocolConnection}});var LSPErrorCodes;(function(LSPErrorCodes2){LSPErrorCodes2.lspReservedErrorRangeStart=-32899,LSPErrorCodes2.RequestFailed=-32803,LSPErrorCodes2.ServerCancelled=-32802,LSPErrorCodes2.ContentModified=-32801,LSPErrorCodes2.RequestCancelled=-32800,LSPErrorCodes2.lspReservedErrorRangeEnd=-32800})(LSPErrorCodes||(exports$1.LSPErrorCodes=LSPErrorCodes={}))})(api)),api}var hasRequiredMain;function requireMain(){return hasRequiredMain||(hasRequiredMain=1,(function(exports$1){var __createBinding=main$1&&main$1.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=main$1&&main$1.__exportStar||function(m,exports$12){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports$12,p)&&__createBinding(exports$12,m,p)};Object.defineProperty(exports$1,"__esModule",{value:!0}),exports$1.createProtocolConnection=void 0;const browser_1=requireBrowser();__exportStar(requireBrowser(),exports$1),__exportStar(requireApi(),exports$1);function createProtocolConnection(reader,writer,logger,options){return(0,browser_1.createMessageConnection)(reader,writer,logger,options)}exports$1.createProtocolConnection=createProtocolConnection})(main$1)),main$1}var mainExports=requireMain(),Disposable;(function(Disposable2){function create(callback){return{dispose:async()=>await callback()}}Disposable2.create=create})(Disposable||(Disposable={}));class DefaultDocumentBuilder{constructor(services){this.updateBuildOptions={validation:{categories:["built-in","fast"]}},this.updateListeners=[],this.buildPhaseListeners=new MultiMap,this.documentPhaseListeners=new MultiMap,this.buildState=new Map,this.documentBuildWaiters=new Map,this.currentState=DocumentState.Changed,this.langiumDocuments=services.workspace.LangiumDocuments,this.langiumDocumentFactory=services.workspace.LangiumDocumentFactory,this.textDocuments=services.workspace.TextDocuments,this.indexManager=services.workspace.IndexManager,this.fileSystemProvider=services.workspace.FileSystemProvider,this.workspaceManager=()=>services.workspace.WorkspaceManager,this.serviceRegistry=services.ServiceRegistry}async build(documents,options={},cancelToken=cancellationExports.CancellationToken.None){var _a21;for(const document of documents){const key=document.uri.toString();if(document.state===DocumentState.Validated){if(typeof options.validation=="boolean"&&options.validation)this.resetToState(document,DocumentState.IndexedReferences);else if(typeof options.validation=="object"){const categories=this.findMissingValidationCategories(document,options);categories.length>0&&(this.buildState.set(key,{completed:!1,options:{validation:{categories}},result:(_a21=this.buildState.get(key))==null?void 0:_a21.result}),document.state=DocumentState.IndexedReferences)}}else this.buildState.delete(key)}this.currentState=DocumentState.Changed,await this.emitUpdate(documents.map(e=>e.uri),[]),await this.buildDocuments(documents,options,cancelToken)}async update(changed,deleted,cancelToken=cancellationExports.CancellationToken.None){this.currentState=DocumentState.Changed;const deletedUris=[];for(const deletedUri of deleted){const deletedDocs=this.langiumDocuments.deleteDocuments(deletedUri);for(const doc of deletedDocs)deletedUris.push(doc.uri),this.cleanUpDeleted(doc)}const changedUris=(await Promise.all(changed.map(uri=>this.findChangedUris(uri)))).flat();for(const changedUri of changedUris){let changedDocument=this.langiumDocuments.getDocument(changedUri);changedDocument===void 0&&(changedDocument=this.langiumDocumentFactory.fromModel({$type:"INVALID"},changedUri),changedDocument.state=DocumentState.Changed,this.langiumDocuments.addDocument(changedDocument)),this.resetToState(changedDocument,DocumentState.Changed)}const allChangedUris=stream(changedUris).concat(deletedUris).map(uri=>uri.toString()).toSet();this.langiumDocuments.all.filter(doc=>!allChangedUris.has(doc.uri.toString())&&this.shouldRelink(doc,allChangedUris)).forEach(doc=>this.resetToState(doc,DocumentState.ComputedScopes)),await this.emitUpdate(changedUris,deletedUris),await interruptAndCheck(cancelToken);const rebuildDocuments=this.sortDocuments(this.langiumDocuments.all.filter(doc=>{var _a21;return doc.state<DocumentState.Validated||!((_a21=this.buildState.get(doc.uri.toString()))!=null&&_a21.completed)||this.resultsAreIncomplete(doc,this.updateBuildOptions)}).toArray());await this.buildDocuments(rebuildDocuments,this.updateBuildOptions,cancelToken)}resultsAreIncomplete(document,options){return this.findMissingValidationCategories(document,options).length>=1}findMissingValidationCategories(document,options){var _a21,_b;const state=this.buildState.get(document.uri.toString()),allCategories=this.serviceRegistry.getServices(document.uri).validation.ValidationRegistry.getAllValidationCategories(document),executedCategories=(_a21=state==null?void 0:state.result)!=null&&_a21.validationChecks?new Set((_b=state==null?void 0:state.result)==null?void 0:_b.validationChecks):state!=null&&state.completed?allCategories:new Set,requestedCategories=options===void 0||options.validation===!0?allCategories:typeof options.validation=="object"?options.validation.categories??allCategories:[];return stream(requestedCategories).filter(requested=>!executedCategories.has(requested)).toArray()}async findChangedUris(changed){var _a21;if(this.langiumDocuments.getDocument(changed)??((_a21=this.textDocuments)==null?void 0:_a21.get(changed)))return[changed];try{const stat=await this.fileSystemProvider.stat(changed);if(stat.isDirectory)return await this.workspaceManager().searchFolder(changed);if(this.workspaceManager().shouldIncludeEntry(stat))return[changed]}catch{}return[]}async emitUpdate(changed,deleted){await Promise.all(this.updateListeners.map(listener=>listener(changed,deleted)))}sortDocuments(documents){let left=0,right=documents.length-1;for(;left<right;){for(;left<documents.length&&this.hasTextDocument(documents[left]);)left++;for(;right>=0&&!this.hasTextDocument(documents[right]);)right--;left<right&&([documents[left],documents[right]]=[documents[right],documents[left]])}return documents}hasTextDocument(doc){var _a21;return!!((_a21=this.textDocuments)!=null&&_a21.get(doc.uri))}shouldRelink(document,changedUris){return document.references.some(ref=>ref.error!==void 0)?!0:this.indexManager.isAffected(document,changedUris)}onUpdate(callback){return this.updateListeners.push(callback),Disposable.create(()=>{const index=this.updateListeners.indexOf(callback);index>=0&&this.updateListeners.splice(index,1)})}resetToState(document,state){switch(state){case DocumentState.Changed:case DocumentState.Parsed:this.indexManager.removeContent(document.uri);case DocumentState.IndexedContent:document.localSymbols=void 0;case DocumentState.ComputedScopes:this.serviceRegistry.getServices(document.uri).references.Linker.unlink(document);case DocumentState.Linked:this.indexManager.removeReferences(document.uri);case DocumentState.IndexedReferences:document.diagnostics=void 0,this.buildState.delete(document.uri.toString());case DocumentState.Validated:}document.state>state&&(document.state=state)}cleanUpDeleted(document){this.buildState.delete(document.uri.toString()),this.indexManager.remove(document.uri),document.state=DocumentState.Changed}async buildDocuments(documents,options,cancelToken){this.prepareBuild(documents,options),await this.runCancelable(documents,DocumentState.Parsed,cancelToken,doc=>this.langiumDocumentFactory.update(doc,cancelToken)),await this.runCancelable(documents,DocumentState.IndexedContent,cancelToken,doc=>this.indexManager.updateContent(doc,cancelToken)),await this.runCancelable(documents,DocumentState.ComputedScopes,cancelToken,async doc=>{const scopeComputation=this.serviceRegistry.getServices(doc.uri).references.ScopeComputation;doc.localSymbols=await scopeComputation.collectLocalSymbols(doc,cancelToken)});const toBeLinked=documents.filter(doc=>this.shouldLink(doc));await this.runCancelable(toBeLinked,DocumentState.Linked,cancelToken,doc=>this.serviceRegistry.getServices(doc.uri).references.Linker.link(doc,cancelToken)),await this.runCancelable(toBeLinked,DocumentState.IndexedReferences,cancelToken,doc=>this.indexManager.updateReferences(doc,cancelToken));const toBeValidated=documents.filter(doc=>this.shouldValidate(doc)?!0:(this.markAsCompleted(doc),!1));await this.runCancelable(toBeValidated,DocumentState.Validated,cancelToken,async doc=>{await this.validate(doc,cancelToken),this.markAsCompleted(doc)})}markAsCompleted(document){const state=this.buildState.get(document.uri.toString());state&&(state.completed=!0)}prepareBuild(documents,options){for(const doc of documents){const key=doc.uri.toString(),state=this.buildState.get(key);(!state||state.completed)&&this.buildState.set(key,{completed:!1,options,result:state==null?void 0:state.result})}}async runCancelable(documents,targetState,cancelToken,callback){for(const document of documents)document.state<targetState&&(await interruptAndCheck(cancelToken),await callback(document),document.state=targetState,await this.notifyDocumentPhase(document,targetState,cancelToken));const targetStateDocs=documents.filter(doc=>doc.state===targetState);await this.notifyBuildPhase(targetStateDocs,targetState,cancelToken),this.currentState=targetState}onBuildPhase(targetState,callback){return this.buildPhaseListeners.add(targetState,callback),Disposable.create(()=>{this.buildPhaseListeners.delete(targetState,callback)})}onDocumentPhase(targetState,callback){return this.documentPhaseListeners.add(targetState,callback),Disposable.create(()=>{this.documentPhaseListeners.delete(targetState,callback)})}waitUntil(state,uriOrToken,cancelToken){let uri;return uriOrToken&&"path"in uriOrToken?uri=uriOrToken:cancelToken=uriOrToken,cancelToken??(cancelToken=cancellationExports.CancellationToken.None),uri?this.awaitDocumentState(state,uri,cancelToken):this.awaitBuilderState(state,cancelToken)}awaitDocumentState(state,uri,cancelToken){const document=this.langiumDocuments.getDocument(uri);if(document){if(document.state>=state)return Promise.resolve(uri);if(cancelToken.isCancellationRequested)return Promise.reject(OperationCancelled);if(this.currentState>=state&&state>document.state)return Promise.reject(new mainExports.ResponseError(mainExports.LSPErrorCodes.RequestFailed,`Document state of ${uri.toString()} is ${DocumentState[document.state]}, requiring ${DocumentState[state]}, but workspace state is already ${DocumentState[this.currentState]}. Returning undefined.`))}else return Promise.reject(new mainExports.ResponseError(mainExports.LSPErrorCodes.ServerCancelled,`No document found for URI: ${uri.toString()}`));return new Promise((resolve,reject)=>{const buildDisposable=this.onDocumentPhase(state,doc=>{UriUtils.equals(doc.uri,uri)&&(buildDisposable.dispose(),cancelDisposable.dispose(),resolve(doc.uri))}),cancelDisposable=cancelToken.onCancellationRequested(()=>{buildDisposable.dispose(),cancelDisposable.dispose(),reject(OperationCancelled)})})}awaitBuilderState(state,cancelToken){return this.currentState>=state?Promise.resolve():cancelToken.isCancellationRequested?Promise.reject(OperationCancelled):new Promise((resolve,reject)=>{const buildDisposable=this.onBuildPhase(state,()=>{buildDisposable.dispose(),cancelDisposable.dispose(),resolve()}),cancelDisposable=cancelToken.onCancellationRequested(()=>{buildDisposable.dispose(),cancelDisposable.dispose(),reject(OperationCancelled)})})}async notifyDocumentPhase(document,state,cancelToken){const listenersCopy=this.documentPhaseListeners.get(state).slice();for(const listener of listenersCopy)try{await interruptAndCheck(cancelToken),await listener(document,cancelToken)}catch(err){if(!isOperationCancelled(err))throw err}}async notifyBuildPhase(documents,state,cancelToken){if(documents.length===0)return;const listenersCopy=this.buildPhaseListeners.get(state).slice();for(const listener of listenersCopy)await interruptAndCheck(cancelToken),await listener(documents,cancelToken)}shouldLink(document){return this.getBuildOptions(document).eagerLinking??!0}shouldValidate(document){return!!this.getBuildOptions(document).validation}async validate(document,cancelToken){const validator=this.serviceRegistry.getServices(document.uri).validation.DocumentValidator,options=this.getBuildOptions(document),validationOptions=typeof options.validation=="object"?{...options.validation}:{};validationOptions.categories=this.findMissingValidationCategories(document,options);const diagnostics=await validator.validateDocument(document,validationOptions,cancelToken);document.diagnostics?document.diagnostics.push(...diagnostics):document.diagnostics=diagnostics;const state=this.buildState.get(document.uri.toString());state&&(state.result??(state.result={}),state.result.validationChecks?state.result.validationChecks=stream(state.result.validationChecks).concat(validationOptions.categories).distinct().toArray():state.result.validationChecks=[...validationOptions.categories])}getBuildOptions(document){var _a21;return((_a21=this.buildState.get(document.uri.toString()))==null?void 0:_a21.options)??{}}}class DefaultIndexManager{constructor(services){this.symbolIndex=new Map,this.symbolByTypeIndex=new ContextCache,this.referenceIndex=new Map,this.documents=services.workspace.LangiumDocuments,this.serviceRegistry=services.ServiceRegistry,this.astReflection=services.AstReflection}findAllReferences(targetNode,astNodePath){const targetDocUri=getDocument(targetNode).uri,result=[];return this.referenceIndex.forEach(docRefs=>{docRefs.forEach(refDescr=>{UriUtils.equals(refDescr.targetUri,targetDocUri)&&refDescr.targetPath===astNodePath&&result.push(refDescr)})}),stream(result)}allElements(nodeType,uris){let documentUris=stream(this.symbolIndex.keys());return uris&&(documentUris=documentUris.filter(uri=>!uris||uris.has(uri))),documentUris.map(uri=>this.getFileDescriptions(uri,nodeType)).flat()}getFileDescriptions(uri,nodeType){return nodeType?this.symbolByTypeIndex.get(uri,nodeType,()=>(this.symbolIndex.get(uri)??[]).filter(e=>this.astReflection.isSubtype(e.type,nodeType))):this.symbolIndex.get(uri)??[]}remove(uri){this.removeContent(uri),this.removeReferences(uri)}removeContent(uri){const uriString=uri.toString();this.symbolIndex.delete(uriString),this.symbolByTypeIndex.clear(uriString)}removeReferences(uri){const uriString=uri.toString();this.referenceIndex.delete(uriString)}async updateContent(document,cancelToken=cancellationExports.CancellationToken.None){const exports$1=await this.serviceRegistry.getServices(document.uri).references.ScopeComputation.collectExportedSymbols(document,cancelToken),uri=document.uri.toString();this.symbolIndex.set(uri,exports$1),this.symbolByTypeIndex.clear(uri)}async updateReferences(document,cancelToken=cancellationExports.CancellationToken.None){const indexData=await this.serviceRegistry.getServices(document.uri).workspace.ReferenceDescriptionProvider.createDescriptions(document,cancelToken);this.referenceIndex.set(document.uri.toString(),indexData)}isAffected(document,changedUris){const references=this.referenceIndex.get(document.uri.toString());return references?references.some(ref=>!ref.local&&changedUris.has(ref.targetUri.toString())):!1}}class DefaultWorkspaceManager{constructor(services){this.initialBuildOptions={},this._ready=new Deferred,this.serviceRegistry=services.ServiceRegistry,this.langiumDocuments=services.workspace.LangiumDocuments,this.documentBuilder=services.workspace.DocumentBuilder,this.fileSystemProvider=services.workspace.FileSystemProvider,this.mutex=services.workspace.WorkspaceLock}get ready(){return this._ready.promise}get workspaceFolders(){return this.folders}initialize(params){this.folders=params.workspaceFolders??void 0}initialized(_params){return this.mutex.write(token=>this.initializeWorkspace(this.folders??[],token))}async initializeWorkspace(folders,cancelToken=cancellationExports.CancellationToken.None){const documents=await this.performStartup(folders);await interruptAndCheck(cancelToken),await this.documentBuilder.build(documents,this.initialBuildOptions,cancelToken)}async performStartup(folders){const documents=[],collector=document=>{documents.push(document),this.langiumDocuments.hasDocument(document.uri)||this.langiumDocuments.addDocument(document)};await this.loadAdditionalDocuments(folders,collector);const uris=[];await Promise.all(folders.map(wf=>this.getRootFolder(wf)).map(async entry=>this.traverseFolder(entry,uris)));const uniqueUris=stream(uris).distinct(uri=>uri.toString()).filter(uri=>!this.langiumDocuments.hasDocument(uri));return await this.loadWorkspaceDocuments(uniqueUris,collector),this._ready.resolve(),documents}async loadWorkspaceDocuments(uris,collector){await Promise.all(uris.map(async uri=>{const document=await this.langiumDocuments.getOrCreateDocument(uri);collector(document)}))}loadAdditionalDocuments(_folders,_collector){return Promise.resolve()}getRootFolder(workspaceFolder){return URI.parse(workspaceFolder.uri)}async traverseFolder(folderPath,uris){try{const content=await this.fileSystemProvider.readDirectory(folderPath);await Promise.all(content.map(async entry=>{this.shouldIncludeEntry(entry)&&(entry.isDirectory?await this.traverseFolder(entry.uri,uris):entry.isFile&&uris.push(entry.uri))}))}catch(e){console.error("Failure to read directory content of "+folderPath.toString(!0),e)}}async searchFolder(uri){const uris=[];return await this.traverseFolder(uri,uris),uris}shouldIncludeEntry(entry){const name=UriUtils.basename(entry.uri);return name.startsWith(".")?!1:entry.isDirectory?name!=="node_modules"&&name!=="out":entry.isFile?this.serviceRegistry.hasServices(entry.uri):!1}}class DefaultLexerErrorMessageProvider{buildUnexpectedCharactersMessage(fullText,startOffset,length,line,column){return defaultLexerErrorProvider.buildUnexpectedCharactersMessage(fullText,startOffset,length,line,column)}buildUnableToPopLexerModeMessage(token){return defaultLexerErrorProvider.buildUnableToPopLexerModeMessage(token)}}const DEFAULT_TOKENIZE_OPTIONS={mode:"full"};class DefaultLexer{constructor(services){this.errorMessageProvider=services.parser.LexerErrorMessageProvider,this.tokenBuilder=services.parser.TokenBuilder;const tokens=this.tokenBuilder.buildTokens(services.Grammar,{caseInsensitive:services.LanguageMetaData.caseInsensitive});this.tokenTypes=this.toTokenTypeDictionary(tokens);const lexerTokens=isTokenTypeDictionary(tokens)?Object.values(tokens):tokens,production=services.LanguageMetaData.mode==="production";this.chevrotainLexer=new Lexer(lexerTokens,{positionTracking:"full",skipValidations:production,errorMessageProvider:this.errorMessageProvider})}get definition(){return this.tokenTypes}tokenize(text,_options=DEFAULT_TOKENIZE_OPTIONS){var _a21,_b;const chevrotainResult=this.chevrotainLexer.tokenize(text);return{tokens:chevrotainResult.tokens,errors:chevrotainResult.errors,hidden:chevrotainResult.groups.hidden??[],report:(_b=(_a21=this.tokenBuilder).flushLexingReport)==null?void 0:_b.call(_a21,text)}}toTokenTypeDictionary(buildTokens){if(isTokenTypeDictionary(buildTokens))return buildTokens;const tokens=isIMultiModeLexerDefinition(buildTokens)?Object.values(buildTokens.modes).flat():buildTokens,res={};return tokens.forEach(token=>res[token.name]=token),res}}function isTokenTypeArray(tokenVocabulary){return Array.isArray(tokenVocabulary)&&(tokenVocabulary.length===0||"name"in tokenVocabulary[0])}function isIMultiModeLexerDefinition(tokenVocabulary){return tokenVocabulary&&"modes"in tokenVocabulary&&"defaultMode"in tokenVocabulary}function isTokenTypeDictionary(tokenVocabulary){return!isTokenTypeArray(tokenVocabulary)&&!isIMultiModeLexerDefinition(tokenVocabulary)}function parseJSDoc(node,start,options){let opts,position;typeof node=="string"?(position=start,opts=options):(position=node.range.start,opts=start),position||(position=Position.create(0,0));const lines=getLines(node),normalizedOptions=normalizeOptions(opts),tokens=tokenize({lines,position,options:normalizedOptions});return parseJSDocComment({index:0,tokens,position})}function isJSDoc(node,options){const normalizedOptions=normalizeOptions(options),lines=getLines(node);if(lines.length===0)return!1;const first2=lines[0],last=lines[lines.length-1],firstRegex=normalizedOptions.start,lastRegex=normalizedOptions.end;return!!(firstRegex!=null&&firstRegex.exec(first2))&&!!(lastRegex!=null&&lastRegex.exec(last))}function getLines(node){let content="";return typeof node=="string"?content=node:content=node.text,content.split(NEWLINE_REGEXP)}const tagRegex=/\s*(@([\p{L}][\p{L}\p{N}]*)?)/uy,inlineTagRegex=/\{(@[\p{L}][\p{L}\p{N}]*)(\s*)([^\r\n}]+)?\}/gu;function tokenize(context){var _a21,_b,_c;const tokens=[];let currentLine=context.position.line,currentCharacter=context.position.character;for(let i=0;i<context.lines.length;i++){const first2=i===0,last=i===context.lines.length-1;let line=context.lines[i],index=0;if(first2&&context.options.start){const match=(_a21=context.options.start)==null?void 0:_a21.exec(line);match&&(index=match.index+match[0].length)}else{const match=(_b=context.options.line)==null?void 0:_b.exec(line);match&&(index=match.index+match[0].length)}if(last){const match=(_c=context.options.end)==null?void 0:_c.exec(line);match&&(line=line.substring(0,match.index))}if(line=line.substring(0,lastCharacter(line)),skipWhitespace(line,index)>=line.length){if(tokens.length>0){const position=Position.create(currentLine,currentCharacter);tokens.push({type:"break",content:"",range:Range.create(position,position)})}}else{tagRegex.lastIndex=index;const tagMatch=tagRegex.exec(line);if(tagMatch){const fullMatch=tagMatch[0],value=tagMatch[1],start=Position.create(currentLine,currentCharacter+index),end=Position.create(currentLine,currentCharacter+index+fullMatch.length);tokens.push({type:"tag",content:value,range:Range.create(start,end)}),index+=fullMatch.length,index=skipWhitespace(line,index)}if(index<line.length){const rest=line.substring(index),inlineTagMatches=Array.from(rest.matchAll(inlineTagRegex));tokens.push(...buildInlineTokens(inlineTagMatches,rest,currentLine,currentCharacter+index))}}currentLine++,currentCharacter=0}return tokens.length>0&&tokens[tokens.length-1].type==="break"?tokens.slice(0,-1):tokens}function buildInlineTokens(tags,line,lineIndex,characterIndex){const tokens=[];if(tags.length===0){const start=Position.create(lineIndex,characterIndex),end=Position.create(lineIndex,characterIndex+line.length);tokens.push({type:"text",content:line,range:Range.create(start,end)})}else{let lastIndex=0;for(const match of tags){const matchIndex=match.index,startContent=line.substring(lastIndex,matchIndex);startContent.length>0&&tokens.push({type:"text",content:line.substring(lastIndex,matchIndex),range:Range.create(Position.create(lineIndex,lastIndex+characterIndex),Position.create(lineIndex,matchIndex+characterIndex))});let offset=startContent.length+1;const tagName=match[1];if(tokens.push({type:"inline-tag",content:tagName,range:Range.create(Position.create(lineIndex,lastIndex+offset+characterIndex),Position.create(lineIndex,lastIndex+offset+tagName.length+characterIndex))}),offset+=tagName.length,match.length===4){offset+=match[2].length;const value=match[3];tokens.push({type:"text",content:value,range:Range.create(Position.create(lineIndex,lastIndex+offset+characterIndex),Position.create(lineIndex,lastIndex+offset+value.length+characterIndex))})}else tokens.push({type:"text",content:"",range:Range.create(Position.create(lineIndex,lastIndex+offset+characterIndex),Position.create(lineIndex,lastIndex+offset+characterIndex))});lastIndex=matchIndex+match[0].length}const endContent=line.substring(lastIndex);endContent.length>0&&tokens.push({type:"text",content:endContent,range:Range.create(Position.create(lineIndex,lastIndex+characterIndex),Position.create(lineIndex,lastIndex+characterIndex+endContent.length))})}return tokens}const nonWhitespaceRegex=/\S/,whitespaceEndRegex=/\s*$/;function skipWhitespace(line,index){const match=line.substring(index).match(nonWhitespaceRegex);return match?index+match.index:line.length}function lastCharacter(line){const match=line.match(whitespaceEndRegex);if(match&&typeof match.index=="number")return match.index}function parseJSDocComment(context){var _a21,_b;const startPosition=Position.create(context.position.line,context.position.character);if(context.tokens.length===0)return new JSDocCommentImpl([],Range.create(startPosition,startPosition));const elements=[];for(;context.index<context.tokens.length;){const element=parseJSDocElement(context,elements[elements.length-1]);element&&elements.push(element)}const start=((_a21=elements[0])==null?void 0:_a21.range.start)??startPosition,end=((_b=elements[elements.length-1])==null?void 0:_b.range.end)??startPosition;return new JSDocCommentImpl(elements,Range.create(start,end))}function parseJSDocElement(context,last){const next=context.tokens[context.index];if(next.type==="tag")return parseJSDocTag(context,!1);if(next.type==="text"||next.type==="inline-tag")return parseJSDocText(context);appendEmptyLine(next,last),context.index++}function appendEmptyLine(token,element){if(element){const line=new JSDocLineImpl("",token.range);"inlines"in element?element.inlines.push(line):element.content.inlines.push(line)}}function parseJSDocText(context){let token=context.tokens[context.index];const firstToken=token;let lastToken=token;const lines=[];for(;token&&token.type!=="break"&&token.type!=="tag";)lines.push(parseJSDocInline(context)),lastToken=token,token=context.tokens[context.index];return new JSDocTextImpl(lines,Range.create(firstToken.range.start,lastToken.range.end))}function parseJSDocInline(context){return context.tokens[context.index].type==="inline-tag"?parseJSDocTag(context,!0):parseJSDocLine(context)}function parseJSDocTag(context,inline){const tagToken=context.tokens[context.index++],name=tagToken.content.substring(1),nextToken=context.tokens[context.index];if((nextToken==null?void 0:nextToken.type)==="text")if(inline){const docLine=parseJSDocLine(context);return new JSDocTagImpl(name,new JSDocTextImpl([docLine],docLine.range),inline,Range.create(tagToken.range.start,docLine.range.end))}else{const textDoc=parseJSDocText(context);return new JSDocTagImpl(name,textDoc,inline,Range.create(tagToken.range.start,textDoc.range.end))}else{const range=tagToken.range;return new JSDocTagImpl(name,new JSDocTextImpl([],range),inline,range)}}function parseJSDocLine(context){const token=context.tokens[context.index++];return new JSDocLineImpl(token.content,token.range)}function normalizeOptions(options){if(!options)return normalizeOptions({start:"/**",end:"*/",line:"*"});const{start,end,line}=options;return{start:normalizeOption(start,!0),end:normalizeOption(end,!1),line:normalizeOption(line,!0)}}function normalizeOption(option2,start){if(typeof option2=="string"||typeof option2=="object"){const escaped=typeof option2=="string"?escapeRegExp(option2):option2.source;return start?new RegExp(`^\\s*${escaped}`):new RegExp(`\\s*${escaped}\\s*$`)}else return option2}class JSDocCommentImpl{constructor(elements,range){this.elements=elements,this.range=range}getTag(name){return this.getAllTags().find(e=>e.name===name)}getTags(name){return this.getAllTags().filter(e=>e.name===name)}getAllTags(){return this.elements.filter(e=>"name"in e)}toString(){let value="";for(const element of this.elements)if(value.length===0)value=element.toString();else{const text=element.toString();value+=fillNewlines(value)+text}return value.trim()}toMarkdown(options){let value="";for(const element of this.elements)if(value.length===0)value=element.toMarkdown(options);else{const text=element.toMarkdown(options);value+=fillNewlines(value)+text}return value.trim()}}class JSDocTagImpl{constructor(name,content,inline,range){this.name=name,this.content=content,this.inline=inline,this.range=range}toString(){let text=`@${this.name}`;const content=this.content.toString();return this.content.inlines.length===1?text=`${text} ${content}`:this.content.inlines.length>1&&(text=`${text}
152
+ ${content}`),this.inline?`{${text}}`:text}toMarkdown(options){var _a21;return((_a21=options==null?void 0:options.renderTag)==null?void 0:_a21.call(options,this))??this.toMarkdownDefault(options)}toMarkdownDefault(options){const content=this.content.toMarkdown(options);if(this.inline){const rendered=renderInlineTag(this.name,content,options??{});if(typeof rendered=="string")return rendered}let marker="";(options==null?void 0:options.tag)==="italic"||(options==null?void 0:options.tag)===void 0?marker="*":(options==null?void 0:options.tag)==="bold"?marker="**":(options==null?void 0:options.tag)==="bold-italic"&&(marker="***");let text=`${marker}@${this.name}${marker}`;return this.content.inlines.length===1?text=`${text} — ${content}`:this.content.inlines.length>1&&(text=`${text}
153
+ ${content}`),this.inline?`{${text}}`:text}}function renderInlineTag(tag,content,options){var _a21;if(tag==="linkplain"||tag==="linkcode"||tag==="link"){const index=content.indexOf(" ");let display=content;if(index>0){const displayStart=skipWhitespace(content,index);display=content.substring(displayStart),content=content.substring(0,index)}return(tag==="linkcode"||tag==="link"&&options.link==="code")&&(display=`\`${display}\``),((_a21=options.renderLink)==null?void 0:_a21.call(options,content,display))??renderLinkDefault(content,display)}}function renderLinkDefault(content,display){try{return URI.parse(content,!0),`[${display}](${content})`}catch{return content}}class JSDocTextImpl{constructor(lines,range){this.inlines=lines,this.range=range}toString(){let text="";for(let i=0;i<this.inlines.length;i++){const inline=this.inlines[i],next=this.inlines[i+1];text+=inline.toString(),next&&next.range.start.line>inline.range.start.line&&(text+=`
154
+ `)}return text}toMarkdown(options){let text="";for(let i=0;i<this.inlines.length;i++){const inline=this.inlines[i],next=this.inlines[i+1];text+=inline.toMarkdown(options),next&&next.range.start.line>inline.range.start.line&&(text+=`
155
+ `)}return text}}class JSDocLineImpl{constructor(text,range){this.text=text,this.range=range}toString(){return this.text}toMarkdown(){return this.text}}function fillNewlines(text){return text.endsWith(`
156
+ `)?`
157
+ `:`
158
+
159
+ `}class JSDocDocumentationProvider{constructor(services){this.indexManager=services.shared.workspace.IndexManager,this.commentProvider=services.documentation.CommentProvider}getDocumentation(node){const comment=this.commentProvider.getComment(node);if(comment&&isJSDoc(comment))return parseJSDoc(comment).toMarkdown({renderLink:(link,display)=>this.documentationLinkRenderer(node,link,display),renderTag:tag=>this.documentationTagRenderer(node,tag)})}documentationLinkRenderer(node,name,display){const description=this.findNameInLocalSymbols(node,name)??this.findNameInGlobalScope(node,name);if(description&&description.nameSegment){const line=description.nameSegment.range.start.line+1,character=description.nameSegment.range.start.character+1,uri=description.documentUri.with({fragment:`L${line},${character}`});return`[${display}](${uri.toString()})`}else return}documentationTagRenderer(_node,_tag){}findNameInLocalSymbols(node,name){const precomputed=getDocument(node).localSymbols;if(!precomputed)return;let currentNode=node;do{const description=precomputed.getStream(currentNode).find(e=>e.name===name);if(description)return description;currentNode=currentNode.$container}while(currentNode)}findNameInGlobalScope(node,name){return this.indexManager.allElements().find(e=>e.name===name)}}class DefaultCommentProvider{constructor(services){this.grammarConfig=()=>services.parser.GrammarConfig}getComment(node){var _a21;return isAstNodeWithComment(node)?node.$comment:(_a21=findCommentNode(node.$cstNode,this.grammarConfig().multilineCommentRules))==null?void 0:_a21.text}}class DefaultAsyncParser{constructor(services){this.syncParser=services.parser.LangiumParser}parse(text,_cancelToken){return Promise.resolve(this.syncParser.parse(text))}}class DefaultWorkspaceLock{constructor(){this.previousTokenSource=new cancellationExports.CancellationTokenSource,this.writeQueue=[],this.readQueue=[],this.done=!0}write(action){this.cancelWrite();const tokenSource=startCancelableOperation();return this.previousTokenSource=tokenSource,this.enqueue(this.writeQueue,action,tokenSource.token)}read(action){return this.enqueue(this.readQueue,action)}enqueue(queue,action,cancellationToken=cancellationExports.CancellationToken.None){const deferred=new Deferred,entry={action,deferred,cancellationToken};return queue.push(entry),this.performNextOperation(),deferred.promise}async performNextOperation(){if(!this.done)return;const entries=[];if(this.writeQueue.length>0)entries.push(this.writeQueue.shift());else if(this.readQueue.length>0)entries.push(...this.readQueue.splice(0,this.readQueue.length));else return;this.done=!1,await Promise.all(entries.map(async({action,deferred,cancellationToken})=>{try{const result=await Promise.resolve().then(()=>action(cancellationToken));deferred.resolve(result)}catch(err){isOperationCancelled(err)?deferred.resolve(void 0):deferred.reject(err)}})),this.done=!0,this.performNextOperation()}cancelWrite(){this.previousTokenSource.cancel()}}class DefaultHydrator{constructor(services){this.grammarElementIdMap=new BiMap,this.tokenTypeIdMap=new BiMap,this.grammar=services.Grammar,this.lexer=services.parser.Lexer,this.linker=services.references.Linker}dehydrate(result){return{lexerErrors:result.lexerErrors,lexerReport:result.lexerReport?this.dehydrateLexerReport(result.lexerReport):void 0,parserErrors:result.parserErrors.map(e=>({...e,message:e.message})),value:this.dehydrateAstNode(result.value,this.createDehyrationContext(result.value))}}dehydrateLexerReport(lexerReport){return lexerReport}createDehyrationContext(node){const astNodes=new Map,cstNodes=new Map;for(const astNode of streamAst(node))astNodes.set(astNode,{});if(node.$cstNode)for(const cstNode of streamCst(node.$cstNode))cstNodes.set(cstNode,{});return{astNodes,cstNodes}}dehydrateAstNode(node,context){const obj=context.astNodes.get(node);obj.$type=node.$type,obj.$containerIndex=node.$containerIndex,obj.$containerProperty=node.$containerProperty,node.$cstNode!==void 0&&(obj.$cstNode=this.dehydrateCstNode(node.$cstNode,context));for(const[name,value]of Object.entries(node))if(!name.startsWith("$"))if(Array.isArray(value)){const arr=[];obj[name]=arr;for(const item of value)isAstNode(item)?arr.push(this.dehydrateAstNode(item,context)):isReference(item)?arr.push(this.dehydrateReference(item,context)):arr.push(item)}else isAstNode(value)?obj[name]=this.dehydrateAstNode(value,context):isReference(value)?obj[name]=this.dehydrateReference(value,context):value!==void 0&&(obj[name]=value);return obj}dehydrateReference(reference,context){const obj={};return obj.$refText=reference.$refText,reference.$refNode&&(obj.$refNode=context.cstNodes.get(reference.$refNode)),obj}dehydrateCstNode(node,context){const cstNode=context.cstNodes.get(node);return isRootCstNode(node)?cstNode.fullText=node.fullText:cstNode.grammarSource=this.getGrammarElementId(node.grammarSource),cstNode.hidden=node.hidden,cstNode.astNode=context.astNodes.get(node.astNode),isCompositeCstNode(node)?cstNode.content=node.content.map(child=>this.dehydrateCstNode(child,context)):isLeafCstNode(node)&&(cstNode.tokenType=node.tokenType.name,cstNode.offset=node.offset,cstNode.length=node.length,cstNode.startLine=node.range.start.line,cstNode.startColumn=node.range.start.character,cstNode.endLine=node.range.end.line,cstNode.endColumn=node.range.end.character),cstNode}hydrate(result){const node=result.value,context=this.createHydrationContext(node);return"$cstNode"in node&&this.hydrateCstNode(node.$cstNode,context),{lexerErrors:result.lexerErrors,lexerReport:result.lexerReport,parserErrors:result.parserErrors,value:this.hydrateAstNode(node,context)}}createHydrationContext(node){const astNodes=new Map,cstNodes=new Map;for(const astNode of streamAst(node))astNodes.set(astNode,{});let root;if(node.$cstNode)for(const cstNode of streamCst(node.$cstNode)){let cst;"fullText"in cstNode?(cst=new RootCstNodeImpl(cstNode.fullText),root=cst):"content"in cstNode?cst=new CompositeCstNodeImpl:"tokenType"in cstNode&&(cst=this.hydrateCstLeafNode(cstNode)),cst&&(cstNodes.set(cstNode,cst),cst.root=root)}return{astNodes,cstNodes}}hydrateAstNode(node,context){const astNode=context.astNodes.get(node);astNode.$type=node.$type,astNode.$containerIndex=node.$containerIndex,astNode.$containerProperty=node.$containerProperty,node.$cstNode&&(astNode.$cstNode=context.cstNodes.get(node.$cstNode));for(const[name,value]of Object.entries(node))if(!name.startsWith("$"))if(Array.isArray(value)){const arr=[];astNode[name]=arr;for(const item of value)isAstNode(item)?arr.push(this.setParent(this.hydrateAstNode(item,context),astNode)):isReference(item)?arr.push(this.hydrateReference(item,astNode,name,context)):arr.push(item)}else isAstNode(value)?astNode[name]=this.setParent(this.hydrateAstNode(value,context),astNode):isReference(value)?astNode[name]=this.hydrateReference(value,astNode,name,context):value!==void 0&&(astNode[name]=value);return astNode}setParent(node,parent){return node.$container=parent,node}hydrateReference(reference,node,name,context){return this.linker.buildReference(node,name,context.cstNodes.get(reference.$refNode),reference.$refText)}hydrateCstNode(cstNode,context,num=0){const cstNodeObj=context.cstNodes.get(cstNode);if(typeof cstNode.grammarSource=="number"&&(cstNodeObj.grammarSource=this.getGrammarElement(cstNode.grammarSource)),cstNodeObj.astNode=context.astNodes.get(cstNode.astNode),isCompositeCstNode(cstNodeObj))for(const child of cstNode.content){const hydrated=this.hydrateCstNode(child,context,num++);cstNodeObj.content.push(hydrated)}return cstNodeObj}hydrateCstLeafNode(cstNode){const tokenType=this.getTokenType(cstNode.tokenType),offset=cstNode.offset,length=cstNode.length,startLine=cstNode.startLine,startColumn=cstNode.startColumn,endLine=cstNode.endLine,endColumn=cstNode.endColumn,hidden=cstNode.hidden;return new LeafCstNodeImpl(offset,length,{start:{line:startLine,character:startColumn},end:{line:endLine,character:endColumn}},tokenType,hidden)}getTokenType(name){return this.lexer.definition[name]}getGrammarElementId(node){if(node)return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.get(node)}getGrammarElement(id){return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.getKey(id)}createGrammarElementIdMap(){let id=0;for(const element of streamAst(this.grammar))isAbstractElement(element)&&this.grammarElementIdMap.set(element,id++)}}function createDefaultCoreModule(context){return{documentation:{CommentProvider:services=>new DefaultCommentProvider(services),DocumentationProvider:services=>new JSDocDocumentationProvider(services)},parser:{AsyncParser:services=>new DefaultAsyncParser(services),GrammarConfig:services=>createGrammarConfig(services),LangiumParser:services=>createLangiumParser(services),CompletionParser:services=>createCompletionParser(services),ValueConverter:()=>new DefaultValueConverter,TokenBuilder:()=>new DefaultTokenBuilder,Lexer:services=>new DefaultLexer(services),ParserErrorMessageProvider:()=>new LangiumParserErrorMessageProvider,LexerErrorMessageProvider:()=>new DefaultLexerErrorMessageProvider},workspace:{AstNodeLocator:()=>new DefaultAstNodeLocator,AstNodeDescriptionProvider:services=>new DefaultAstNodeDescriptionProvider(services),ReferenceDescriptionProvider:services=>new DefaultReferenceDescriptionProvider(services)},references:{Linker:services=>new DefaultLinker(services),NameProvider:()=>new DefaultNameProvider,ScopeProvider:services=>new DefaultScopeProvider(services),ScopeComputation:services=>new DefaultScopeComputation(services),References:services=>new DefaultReferences(services)},serializer:{Hydrator:services=>new DefaultHydrator(services),JsonSerializer:services=>new DefaultJsonSerializer(services)},validation:{DocumentValidator:services=>new DefaultDocumentValidator(services),ValidationRegistry:services=>new ValidationRegistry(services)},shared:()=>context.shared}}function createDefaultSharedCoreModule(context){return{ServiceRegistry:services=>new DefaultServiceRegistry(services),workspace:{LangiumDocuments:services=>new DefaultLangiumDocuments(services),LangiumDocumentFactory:services=>new DefaultLangiumDocumentFactory(services),DocumentBuilder:services=>new DefaultDocumentBuilder(services),IndexManager:services=>new DefaultIndexManager(services),WorkspaceManager:services=>new DefaultWorkspaceManager(services),FileSystemProvider:services=>context.fileSystemProvider(services),WorkspaceLock:()=>new DefaultWorkspaceLock,ConfigurationProvider:services=>new DefaultConfigurationProvider(services)},profilers:{}}}var Module;(function(Module2){Module2.merge=(m1,m2)=>_merge(_merge({},m1),m2)})(Module||(Module={}));function inject(module1,module2,module3,module4,module5,module6,module7,module8,module9){const module=[module1,module2,module3,module4,module5,module6,module7,module8,module9].reduce(_merge,{});return _inject(module)}const isProxy=Symbol("isProxy");function _inject(module,injector){const proxy=new Proxy({},{deleteProperty:()=>!1,set:()=>{throw new Error("Cannot set property on injected service container")},get:(obj,prop)=>prop===isProxy?!0:_resolve(obj,prop,module,injector||proxy),getOwnPropertyDescriptor:(obj,prop)=>(_resolve(obj,prop,module,injector||proxy),Object.getOwnPropertyDescriptor(obj,prop)),has:(_,prop)=>prop in module,ownKeys:()=>[...Object.getOwnPropertyNames(module)]});return proxy}const __requested__=Symbol();function _resolve(obj,prop,module,injector){if(prop in obj){if(obj[prop]instanceof Error)throw new Error("Construction failure. Please make sure that your dependencies are constructable. Cause: "+obj[prop]);if(obj[prop]===__requested__)throw new Error('Cycle detected. Please make "'+String(prop)+'" lazy. Visit https://langium.org/docs/reference/configuration-services/#resolving-cyclic-dependencies');return obj[prop]}else if(prop in module){const value=module[prop];obj[prop]=__requested__;try{obj[prop]=typeof value=="function"?value(injector):_inject(value,injector)}catch(error){throw obj[prop]=error instanceof Error?error:void 0,error}return obj[prop]}else return}function _merge(target,source){if(source){for(const[key,sourceValue]of Object.entries(source))if(sourceValue!=null)if(typeof sourceValue=="object"){const targetValue=target[key];typeof targetValue=="object"&&targetValue!==null?target[key]=_merge(targetValue,sourceValue):target[key]=_merge({},sourceValue)}else target[key]=sourceValue}return target}class EmptyFileSystemProvider{stat(_uri){throw new Error("No file system is available.")}statSync(_uri){throw new Error("No file system is available.")}async exists(){return!1}existsSync(){return!1}readBinary(){throw new Error("No file system is available.")}readBinarySync(){throw new Error("No file system is available.")}readFile(){throw new Error("No file system is available.")}readFileSync(){throw new Error("No file system is available.")}async readDirectory(){return[]}readDirectorySync(){return[]}}const EmptyFileSystem={fileSystemProvider:()=>new EmptyFileSystemProvider},minimalGrammarModule={Grammar:()=>{},LanguageMetaData:()=>({caseInsensitive:!1,fileExtensions:[".langium"],languageId:"langium"})},minimalSharedGrammarModule={AstReflection:()=>new LangiumGrammarAstReflection};function createMinimalGrammarServices(){const shared=inject(createDefaultSharedCoreModule(EmptyFileSystem),minimalSharedGrammarModule),grammar=inject(createDefaultCoreModule({shared}),minimalGrammarModule);return shared.ServiceRegistry.register(grammar),grammar}function loadGrammarFromJson(json){const services=createMinimalGrammarServices(),astNode=services.serializer.JsonSerializer.deserialize(json);return services.shared.workspace.LangiumDocumentFactory.fromModel(astNode,URI.parse(`memory:/${astNode.name??"grammar"}.langium`)),astNode}var __defProp2=Object.defineProperty,__name=(target,value)=>__defProp2(target,"name",{value,configurable:!0}),ArchitectureGrammar;(ArchitectureGrammar2=>{ArchitectureGrammar2.Terminals={ARROW_DIRECTION:/L|R|T|B/,ARROW_GROUP:/\{group\}/,ARROW_INTO:/<|>/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,ID:/[\w]([-\w]*\w)?/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/,ARCH_ICON:/\([\w-:]+\)/,ARCH_TITLE:/\[(?:"([^"\\]|\\.)*"|'([^'\\]|\\.)*'|[\w ]+)\]/}})(ArchitectureGrammar||(ArchitectureGrammar={}));var GitGraphGrammar;(GitGraphGrammar2=>{GitGraphGrammar2.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,INT:/0|[1-9][0-9]*(?!\.)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/,REFERENCE:/\w([-\./\w]*[-\w])?/}})(GitGraphGrammar||(GitGraphGrammar={}));var InfoGrammar;(InfoGrammar2=>{InfoGrammar2.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(InfoGrammar||(InfoGrammar={}));var PacketGrammar;(PacketGrammar2=>{PacketGrammar2.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,INT:/0|[1-9][0-9]*(?!\.)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(PacketGrammar||(PacketGrammar={}));var PieGrammar;(PieGrammar2=>{PieGrammar2.Terminals={NUMBER_PIE:/(?:-?[0-9]+\.[0-9]+(?!\.))|(?:-?(0|[1-9][0-9]*)(?!\.))/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(PieGrammar||(PieGrammar={}));var RadarGrammar;(RadarGrammar2=>{RadarGrammar2.Terminals={GRATICULE:/circle|polygon/,BOOLEAN:/true|false/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,NUMBER:/(?:[0-9]+\.[0-9]+(?!\.))|(?:0|[1-9][0-9]*(?!\.))/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,ID:/[\w]([-\w]*\w)?/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(RadarGrammar||(RadarGrammar={}));var TreemapGrammar;(TreemapGrammar2=>{TreemapGrammar2.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,TREEMAP_KEYWORD:/treemap-beta|treemap/,CLASS_DEF:/classDef\s+([a-zA-Z_][a-zA-Z0-9_]+)(?:\s+([^;\r\n]*))?(?:;)?/,STYLE_SEPARATOR:/:::/,SEPARATOR:/:/,COMMA:/,/,INDENTATION:/[ \t]{1,}/,WS:/[ \t]+/,ML_COMMENT:/\%\%[^\n]*/,NL:/\r?\n/,ID2:/[a-zA-Z_][a-zA-Z0-9_]*/,NUMBER2:/[0-9_\.\,]+/,STRING2:/"[^"]*"|'[^']*'/}})(TreemapGrammar||(TreemapGrammar={}));var TreeViewGrammar;(TreeViewGrammar2=>{TreeViewGrammar2.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,INDENTATION:/[ \t]{1,}/,WS:/[ \t]+/,ML_COMMENT:/\%\%[^\n]*/,NL:/\r?\n/,STRING2:/"[^"]*"|'[^']*'/}})(TreeViewGrammar||(TreeViewGrammar={}));var WardleyGrammar;(WardleyGrammar2=>{WardleyGrammar2.Terminals={WARDLEY_NUMBER:/[0-9]+\.[0-9]+/,ARROW:/->/,LINK_PORT:/\+<>|\+>|\+</,LINK_ARROW:/-->|-\.->|>|\+'[^']*'<>|\+'[^']*'<|\+'[^']*'>/,LINK_LABEL:/;[^\n\r]+/,STRATEGY:/build|buy|outsource|market/,KW_WARDLEY:/wardley-beta/,KW_SIZE:/size/,KW_EVOLUTION:/evolution/,KW_ANCHOR:/anchor/,KW_COMPONENT:/component/,KW_LABEL:/label/,KW_INERTIA:/inertia/,KW_EVOLVE:/evolve/,KW_PIPELINE:/pipeline/,KW_NOTE:/note/,KW_ANNOTATIONS:/annotations/,KW_ANNOTATION:/annotation/,KW_ACCELERATOR:/accelerator/,KW_DEACCELERATOR:/deaccelerator/,NAME_WITH_SPACES:/(?!title\s|accTitle|accDescr)[A-Za-z][A-Za-z0-9_()&]*(?:[ \t]+[A-Za-z(][A-Za-z0-9_()&]*)*/,WS:/[ \t]+/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,INT:/0|[1-9][0-9]*(?!\.)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,ID:/[\w]([-\w]*\w)?/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(WardleyGrammar||(WardleyGrammar={}));({...ArchitectureGrammar.Terminals,...GitGraphGrammar.Terminals,...InfoGrammar.Terminals,...PacketGrammar.Terminals,...PieGrammar.Terminals,...RadarGrammar.Terminals,...TreeViewGrammar.Terminals,...TreemapGrammar.Terminals,...WardleyGrammar.Terminals});var Accelerator={$type:"Accelerator",name:"name",x:"x",y:"y"},Anchor={$type:"Anchor",evolution:"evolution",name:"name",visibility:"visibility"},Annotation={$type:"Annotation",number:"number",text:"text",x:"x",y:"y"},Annotations={$type:"Annotations",x:"x",y:"y"},Architecture={$type:"Architecture",accDescr:"accDescr",accTitle:"accTitle",edges:"edges",groups:"groups",junctions:"junctions",services:"services",title:"title"};function isArchitecture(item){return reflection.isInstance(item,Architecture.$type)}__name(isArchitecture,"isArchitecture");var Axis={$type:"Axis",label:"label",name:"name"},Branch={$type:"Branch",name:"name",order:"order"};function isBranch(item){return reflection.isInstance(item,Branch.$type)}__name(isBranch,"isBranch");var Checkout={$type:"Checkout",branch:"branch"},CherryPicking={$type:"CherryPicking",id:"id",parent:"parent",tags:"tags"},ClassDefStatement={$type:"ClassDefStatement",className:"className",styleText:"styleText"},Commit={$type:"Commit",id:"id",message:"message",tags:"tags",type:"type"};function isCommit(item){return reflection.isInstance(item,Commit.$type)}__name(isCommit,"isCommit");var Component={$type:"Component",decorator:"decorator",evolution:"evolution",inertia:"inertia",label:"label",name:"name",visibility:"visibility"},Curve={$type:"Curve",entries:"entries",label:"label",name:"name"},Deaccelerator={$type:"Deaccelerator",name:"name",x:"x",y:"y"},Decorator={$type:"Decorator",strategy:"strategy"},Direction={$type:"Direction",accDescr:"accDescr",accTitle:"accTitle",dir:"dir",statements:"statements",title:"title"},Edge={$type:"Edge",lhsDir:"lhsDir",lhsGroup:"lhsGroup",lhsId:"lhsId",lhsInto:"lhsInto",rhsDir:"rhsDir",rhsGroup:"rhsGroup",rhsId:"rhsId",rhsInto:"rhsInto",title:"title"},Entry={$type:"Entry",axis:"axis",value:"value"},Evolution={$type:"Evolution",stages:"stages"},EvolutionStage={$type:"EvolutionStage",boundary:"boundary",name:"name",secondName:"secondName"},Evolve={$type:"Evolve",component:"component",target:"target"},GitGraph={$type:"GitGraph",accDescr:"accDescr",accTitle:"accTitle",statements:"statements",title:"title"};function isGitGraph(item){return reflection.isInstance(item,GitGraph.$type)}__name(isGitGraph,"isGitGraph");var Group={$type:"Group",icon:"icon",id:"id",in:"in",title:"title"},Info={$type:"Info",accDescr:"accDescr",accTitle:"accTitle",title:"title"};function isInfo(item){return reflection.isInstance(item,Info.$type)}__name(isInfo,"isInfo");var Item={$type:"Item",classSelector:"classSelector",name:"name"},Junction={$type:"Junction",id:"id",in:"in"},Label={$type:"Label",negX:"negX",negY:"negY",offsetX:"offsetX",offsetY:"offsetY"},Leaf={$type:"Leaf",classSelector:"classSelector",name:"name",value:"value"},Link={$type:"Link",arrow:"arrow",from:"from",fromPort:"fromPort",linkLabel:"linkLabel",to:"to",toPort:"toPort"},Merge={$type:"Merge",branch:"branch",id:"id",tags:"tags",type:"type"};function isMerge(item){return reflection.isInstance(item,Merge.$type)}__name(isMerge,"isMerge");var Note={$type:"Note",evolution:"evolution",text:"text",visibility:"visibility"},Option2={$type:"Option",name:"name",value:"value"},Packet={$type:"Packet",accDescr:"accDescr",accTitle:"accTitle",blocks:"blocks",title:"title"};function isPacket(item){return reflection.isInstance(item,Packet.$type)}__name(isPacket,"isPacket");var PacketBlock={$type:"PacketBlock",bits:"bits",end:"end",label:"label",start:"start"};function isPacketBlock(item){return reflection.isInstance(item,PacketBlock.$type)}__name(isPacketBlock,"isPacketBlock");var Pie={$type:"Pie",accDescr:"accDescr",accTitle:"accTitle",sections:"sections",showData:"showData",title:"title"};function isPie(item){return reflection.isInstance(item,Pie.$type)}__name(isPie,"isPie");var PieSection={$type:"PieSection",label:"label",value:"value"};function isPieSection(item){return reflection.isInstance(item,PieSection.$type)}__name(isPieSection,"isPieSection");var Pipeline={$type:"Pipeline",components:"components",parent:"parent"},PipelineComponent={$type:"PipelineComponent",evolution:"evolution",label:"label",name:"name"},Radar={$type:"Radar",accDescr:"accDescr",accTitle:"accTitle",axes:"axes",curves:"curves",options:"options",title:"title"},Section={$type:"Section",classSelector:"classSelector",name:"name"},Service={$type:"Service",icon:"icon",iconText:"iconText",id:"id",in:"in",title:"title"},Size={$type:"Size",height:"height",width:"width"},Statement={$type:"Statement"},Treemap={$type:"Treemap",accDescr:"accDescr",accTitle:"accTitle",title:"title",TreemapRows:"TreemapRows"};function isTreemap(item){return reflection.isInstance(item,Treemap.$type)}__name(isTreemap,"isTreemap");var TreemapRow={$type:"TreemapRow",indent:"indent",item:"item"},TreeNode={$type:"TreeNode",indent:"indent",name:"name"},TreeView={$type:"TreeView",accDescr:"accDescr",accTitle:"accTitle",nodes:"nodes",title:"title"},Wardley={$type:"Wardley",accDescr:"accDescr",accelerators:"accelerators",accTitle:"accTitle",anchors:"anchors",annotation:"annotation",annotations:"annotations",components:"components",deaccelerators:"deaccelerators",evolution:"evolution",evolves:"evolves",links:"links",notes:"notes",pipelines:"pipelines",size:"size",title:"title"};function isWardley(item){return reflection.isInstance(item,Wardley.$type)}__name(isWardley,"isWardley");var _a,MermaidAstReflection=(_a=class extends AbstractAstReflection{constructor(){super(...arguments),this.types={Accelerator:{name:Accelerator.$type,properties:{name:{name:Accelerator.name},x:{name:Accelerator.x},y:{name:Accelerator.y}},superTypes:[]},Anchor:{name:Anchor.$type,properties:{evolution:{name:Anchor.evolution},name:{name:Anchor.name},visibility:{name:Anchor.visibility}},superTypes:[]},Annotation:{name:Annotation.$type,properties:{number:{name:Annotation.number},text:{name:Annotation.text},x:{name:Annotation.x},y:{name:Annotation.y}},superTypes:[]},Annotations:{name:Annotations.$type,properties:{x:{name:Annotations.x},y:{name:Annotations.y}},superTypes:[]},Architecture:{name:Architecture.$type,properties:{accDescr:{name:Architecture.accDescr},accTitle:{name:Architecture.accTitle},edges:{name:Architecture.edges,defaultValue:[]},groups:{name:Architecture.groups,defaultValue:[]},junctions:{name:Architecture.junctions,defaultValue:[]},services:{name:Architecture.services,defaultValue:[]},title:{name:Architecture.title}},superTypes:[]},Axis:{name:Axis.$type,properties:{label:{name:Axis.label},name:{name:Axis.name}},superTypes:[]},Branch:{name:Branch.$type,properties:{name:{name:Branch.name},order:{name:Branch.order}},superTypes:[Statement.$type]},Checkout:{name:Checkout.$type,properties:{branch:{name:Checkout.branch}},superTypes:[Statement.$type]},CherryPicking:{name:CherryPicking.$type,properties:{id:{name:CherryPicking.id},parent:{name:CherryPicking.parent},tags:{name:CherryPicking.tags,defaultValue:[]}},superTypes:[Statement.$type]},ClassDefStatement:{name:ClassDefStatement.$type,properties:{className:{name:ClassDefStatement.className},styleText:{name:ClassDefStatement.styleText}},superTypes:[]},Commit:{name:Commit.$type,properties:{id:{name:Commit.id},message:{name:Commit.message},tags:{name:Commit.tags,defaultValue:[]},type:{name:Commit.type}},superTypes:[Statement.$type]},Component:{name:Component.$type,properties:{decorator:{name:Component.decorator},evolution:{name:Component.evolution},inertia:{name:Component.inertia,defaultValue:!1},label:{name:Component.label},name:{name:Component.name},visibility:{name:Component.visibility}},superTypes:[]},Curve:{name:Curve.$type,properties:{entries:{name:Curve.entries,defaultValue:[]},label:{name:Curve.label},name:{name:Curve.name}},superTypes:[]},Deaccelerator:{name:Deaccelerator.$type,properties:{name:{name:Deaccelerator.name},x:{name:Deaccelerator.x},y:{name:Deaccelerator.y}},superTypes:[]},Decorator:{name:Decorator.$type,properties:{strategy:{name:Decorator.strategy}},superTypes:[]},Direction:{name:Direction.$type,properties:{accDescr:{name:Direction.accDescr},accTitle:{name:Direction.accTitle},dir:{name:Direction.dir},statements:{name:Direction.statements,defaultValue:[]},title:{name:Direction.title}},superTypes:[GitGraph.$type]},Edge:{name:Edge.$type,properties:{lhsDir:{name:Edge.lhsDir},lhsGroup:{name:Edge.lhsGroup,defaultValue:!1},lhsId:{name:Edge.lhsId},lhsInto:{name:Edge.lhsInto,defaultValue:!1},rhsDir:{name:Edge.rhsDir},rhsGroup:{name:Edge.rhsGroup,defaultValue:!1},rhsId:{name:Edge.rhsId},rhsInto:{name:Edge.rhsInto,defaultValue:!1},title:{name:Edge.title}},superTypes:[]},Entry:{name:Entry.$type,properties:{axis:{name:Entry.axis,referenceType:Axis.$type},value:{name:Entry.value}},superTypes:[]},Evolution:{name:Evolution.$type,properties:{stages:{name:Evolution.stages,defaultValue:[]}},superTypes:[]},EvolutionStage:{name:EvolutionStage.$type,properties:{boundary:{name:EvolutionStage.boundary},name:{name:EvolutionStage.name},secondName:{name:EvolutionStage.secondName}},superTypes:[]},Evolve:{name:Evolve.$type,properties:{component:{name:Evolve.component},target:{name:Evolve.target}},superTypes:[]},GitGraph:{name:GitGraph.$type,properties:{accDescr:{name:GitGraph.accDescr},accTitle:{name:GitGraph.accTitle},statements:{name:GitGraph.statements,defaultValue:[]},title:{name:GitGraph.title}},superTypes:[]},Group:{name:Group.$type,properties:{icon:{name:Group.icon},id:{name:Group.id},in:{name:Group.in},title:{name:Group.title}},superTypes:[]},Info:{name:Info.$type,properties:{accDescr:{name:Info.accDescr},accTitle:{name:Info.accTitle},title:{name:Info.title}},superTypes:[]},Item:{name:Item.$type,properties:{classSelector:{name:Item.classSelector},name:{name:Item.name}},superTypes:[]},Junction:{name:Junction.$type,properties:{id:{name:Junction.id},in:{name:Junction.in}},superTypes:[]},Label:{name:Label.$type,properties:{negX:{name:Label.negX,defaultValue:!1},negY:{name:Label.negY,defaultValue:!1},offsetX:{name:Label.offsetX},offsetY:{name:Label.offsetY}},superTypes:[]},Leaf:{name:Leaf.$type,properties:{classSelector:{name:Leaf.classSelector},name:{name:Leaf.name},value:{name:Leaf.value}},superTypes:[Item.$type]},Link:{name:Link.$type,properties:{arrow:{name:Link.arrow},from:{name:Link.from},fromPort:{name:Link.fromPort},linkLabel:{name:Link.linkLabel},to:{name:Link.to},toPort:{name:Link.toPort}},superTypes:[]},Merge:{name:Merge.$type,properties:{branch:{name:Merge.branch},id:{name:Merge.id},tags:{name:Merge.tags,defaultValue:[]},type:{name:Merge.type}},superTypes:[Statement.$type]},Note:{name:Note.$type,properties:{evolution:{name:Note.evolution},text:{name:Note.text},visibility:{name:Note.visibility}},superTypes:[]},Option:{name:Option2.$type,properties:{name:{name:Option2.name},value:{name:Option2.value,defaultValue:!1}},superTypes:[]},Packet:{name:Packet.$type,properties:{accDescr:{name:Packet.accDescr},accTitle:{name:Packet.accTitle},blocks:{name:Packet.blocks,defaultValue:[]},title:{name:Packet.title}},superTypes:[]},PacketBlock:{name:PacketBlock.$type,properties:{bits:{name:PacketBlock.bits},end:{name:PacketBlock.end},label:{name:PacketBlock.label},start:{name:PacketBlock.start}},superTypes:[]},Pie:{name:Pie.$type,properties:{accDescr:{name:Pie.accDescr},accTitle:{name:Pie.accTitle},sections:{name:Pie.sections,defaultValue:[]},showData:{name:Pie.showData,defaultValue:!1},title:{name:Pie.title}},superTypes:[]},PieSection:{name:PieSection.$type,properties:{label:{name:PieSection.label},value:{name:PieSection.value}},superTypes:[]},Pipeline:{name:Pipeline.$type,properties:{components:{name:Pipeline.components,defaultValue:[]},parent:{name:Pipeline.parent}},superTypes:[]},PipelineComponent:{name:PipelineComponent.$type,properties:{evolution:{name:PipelineComponent.evolution},label:{name:PipelineComponent.label},name:{name:PipelineComponent.name}},superTypes:[]},Radar:{name:Radar.$type,properties:{accDescr:{name:Radar.accDescr},accTitle:{name:Radar.accTitle},axes:{name:Radar.axes,defaultValue:[]},curves:{name:Radar.curves,defaultValue:[]},options:{name:Radar.options,defaultValue:[]},title:{name:Radar.title}},superTypes:[]},Section:{name:Section.$type,properties:{classSelector:{name:Section.classSelector},name:{name:Section.name}},superTypes:[Item.$type]},Service:{name:Service.$type,properties:{icon:{name:Service.icon},iconText:{name:Service.iconText},id:{name:Service.id},in:{name:Service.in},title:{name:Service.title}},superTypes:[]},Size:{name:Size.$type,properties:{height:{name:Size.height},width:{name:Size.width}},superTypes:[]},Statement:{name:Statement.$type,properties:{},superTypes:[]},TreeNode:{name:TreeNode.$type,properties:{indent:{name:TreeNode.indent},name:{name:TreeNode.name}},superTypes:[]},TreeView:{name:TreeView.$type,properties:{accDescr:{name:TreeView.accDescr},accTitle:{name:TreeView.accTitle},nodes:{name:TreeView.nodes,defaultValue:[]},title:{name:TreeView.title}},superTypes:[]},Treemap:{name:Treemap.$type,properties:{accDescr:{name:Treemap.accDescr},accTitle:{name:Treemap.accTitle},title:{name:Treemap.title},TreemapRows:{name:Treemap.TreemapRows,defaultValue:[]}},superTypes:[]},TreemapRow:{name:TreemapRow.$type,properties:{indent:{name:TreemapRow.indent},item:{name:TreemapRow.item}},superTypes:[]},Wardley:{name:Wardley.$type,properties:{accDescr:{name:Wardley.accDescr},accelerators:{name:Wardley.accelerators,defaultValue:[]},accTitle:{name:Wardley.accTitle},anchors:{name:Wardley.anchors,defaultValue:[]},annotation:{name:Wardley.annotation,defaultValue:[]},annotations:{name:Wardley.annotations,defaultValue:[]},components:{name:Wardley.components,defaultValue:[]},deaccelerators:{name:Wardley.deaccelerators,defaultValue:[]},evolution:{name:Wardley.evolution},evolves:{name:Wardley.evolves,defaultValue:[]},links:{name:Wardley.links,defaultValue:[]},notes:{name:Wardley.notes,defaultValue:[]},pipelines:{name:Wardley.pipelines,defaultValue:[]},size:{name:Wardley.size},title:{name:Wardley.title}},superTypes:[]}}}},__name(_a,"MermaidAstReflection"),_a),reflection=new MermaidAstReflection,loadedArchitectureGrammarGrammar,ArchitectureGrammarGrammar=__name(()=>loadedArchitectureGrammarGrammar??(loadedArchitectureGrammarGrammar=loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"ArchitectureGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Architecture","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"architecture-beta"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"groups","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"services","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"junctions","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Assignment","feature":"edges","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"LeftPort","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"lhsDir","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"RightPort","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"rhsDir","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Keyword","value":":"}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Arrow","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},{"$type":"Assignment","feature":"lhsInto","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"--"},{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]}},{"$type":"Keyword","value":"-"}]}]},{"$type":"Assignment","feature":"rhsInto","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Group","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"group"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"icon","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Service","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"service"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"iconText","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]}},{"$type":"Assignment","feature":"icon","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]}}],"cardinality":"?"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Junction","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"junction"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Edge","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"lhsId","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"lhsGroup","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"Assignment","feature":"rhsId","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"rhsGroup","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"ARROW_DIRECTION","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"L"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"R"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"T"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"B"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW_GROUP","definition":{"$type":"RegexToken","regex":"/\\\\{group\\\\}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW_INTO","definition":{"$type":"RegexToken","regex":"/<|>/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@18"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@19"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"ARCH_ICON","definition":{"$type":"RegexToken","regex":"/\\\\([\\\\w-:]+\\\\)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARCH_TITLE","definition":{"$type":"RegexToken","regex":"/\\\\[(?:\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'|[\\\\w ]+)\\\\]/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[],"types":[]}`)),"ArchitectureGrammarGrammar"),loadedGitGraphGrammarGrammar,GitGraphGrammarGrammar=__name(()=>loadedGitGraphGrammarGrammar??(loadedGitGraphGrammarGrammar=loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"GitGraphGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"GitGraph","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"Group","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"Keyword","value":":"}]},{"$type":"Keyword","value":"gitGraph:"},{"$type":"Group","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},{"$type":"Keyword","value":":"}]}]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},{"$type":"Assignment","feature":"statements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Direction","definition":{"$type":"Assignment","feature":"dir","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"LR"},{"$type":"Keyword","value":"TB"},{"$type":"Keyword","value":"BT"}]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Commit","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"commit"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"msg:","cardinality":"?"},{"$type":"Assignment","feature":"message","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"type:"},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"NORMAL"},{"$type":"Keyword","value":"REVERSE"},{"$type":"Keyword","value":"HIGHLIGHT"}]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Branch","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"branch"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"order:"},{"$type":"Assignment","feature":"order","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Merge","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"merge"},{"$type":"Assignment","feature":"branch","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"type:"},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"NORMAL"},{"$type":"Keyword","value":"REVERSE"},{"$type":"Keyword","value":"HIGHLIGHT"}]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Checkout","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"checkout"},{"$type":"Keyword","value":"switch"}]},{"$type":"Assignment","feature":"branch","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CherryPicking","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"cherry-pick"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"parent:"},{"$type":"Assignment","feature":"parent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@14"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@15"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"REFERENCE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\\\w([-\\\\./\\\\w]*[-\\\\w])?/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[],"types":[]}`)),"GitGraphGrammarGrammar"),loadedInfoGrammarGrammar,InfoGrammarGrammar=__name(()=>loadedInfoGrammarGrammar??(loadedInfoGrammarGrammar=loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"InfoGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Info","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"info"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"},{"$type":"Group","elements":[{"$type":"Keyword","value":"showInfo"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[],"cardinality":"?"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@7"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@8"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)),"InfoGrammarGrammar"),loadedPacketGrammarGrammar,PacketGrammarGrammar=__name(()=>loadedPacketGrammarGrammar??(loadedPacketGrammarGrammar=loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"PacketGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Packet","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"packet"},{"$type":"Keyword","value":"packet-beta"}]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},{"$type":"Assignment","feature":"blocks","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PacketBlock","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"start","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"end","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"+"},{"$type":"Assignment","feature":"bits","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}]}]},{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@8"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@9"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)),"PacketGrammarGrammar"),loadedPieGrammarGrammar,PieGrammarGrammar=__name(()=>loadedPieGrammarGrammar??(loadedPieGrammarGrammar=loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"PieGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Pie","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"pie"},{"$type":"Assignment","feature":"showData","operator":"?=","terminal":{"$type":"Keyword","value":"showData"},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"Assignment","feature":"sections","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PieSection","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"FLOAT_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/-?[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/-?(0|[1-9][0-9]*)(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@2"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@3"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@11"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@12"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)),"PieGrammarGrammar"),loadedRadarGrammarGrammar,RadarGrammarGrammar=__name(()=>loadedRadarGrammarGrammar??(loadedRadarGrammarGrammar=loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"RadarGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Radar","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"radar-beta"},{"$type":"Keyword","value":"radar-beta:"},{"$type":"Group","elements":[{"$type":"Keyword","value":"radar-beta"},{"$type":"Keyword","value":":"}]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Keyword","value":"axis"},{"$type":"Assignment","feature":"axes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"axes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"curve"},{"$type":"Assignment","feature":"curves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"curves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"options","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"options","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Label","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Axis","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Curve","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[],"cardinality":"?"},{"$type":"Keyword","value":"{"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Entries","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"}]}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"DetailedEntry","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"axis","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@2"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"NumberEntry","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Option","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"showLegend"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"ticks"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"max"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"min"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"graticule"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"GRATICULE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"circle"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"polygon"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@15"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@16"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[{"$type":"Interface","name":"Entry","attributes":[{"$type":"TypeAttribute","name":"axis","isOptional":true,"type":{"$type":"ReferenceType","referenceType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@2"}},"isMulti":false}},{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"number"},"isOptional":false}],"superTypes":[]}],"types":[]}`)),"RadarGrammarGrammar"),loadedTreemapGrammarGrammar,TreemapGrammarGrammar=__name(()=>loadedTreemapGrammarGrammar??(loadedTreemapGrammarGrammar=loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"TreemapGrammar","rules":[{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","entry":true,"name":"Treemap","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]},{"$type":"Assignment","feature":"TreemapRows","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"TREEMAP_KEYWORD","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"treemap-beta"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"treemap"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"CLASS_DEF","definition":{"$type":"RegexToken","regex":"/classDef\\\\s+([a-zA-Z_][a-zA-Z0-9_]+)(?:\\\\s+([^;\\\\r\\\\n]*))?(?:;)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STYLE_SEPARATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":":::"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"SEPARATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":":"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"COMMA","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":","},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INDENTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]{1,}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ML_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\%\\\\%[^\\\\n]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"NL","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false},{"$type":"ParserRule","name":"TreemapRow","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"indent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"item","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ClassDef","dataType":"string","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Item","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Section","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},{"$type":"Assignment","feature":"classSelector","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Leaf","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[],"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[],"cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},{"$type":"Assignment","feature":"classSelector","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"ID2","definition":{"$type":"RegexToken","regex":"/[a-zA-Z_][a-zA-Z0-9_]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER2","definition":{"$type":"RegexToken","regex":"/[0-9_\\\\.\\\\,]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"MyNumber","dataType":"number","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"STRING2","definition":{"$type":"RegexToken","regex":"/\\"[^\\"]*\\"|'[^']*'/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[{"$type":"Interface","name":"Item","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"classSelector","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]},{"$type":"Interface","name":"Section","superTypes":[{"$ref":"#/interfaces@0"}],"attributes":[]},{"$type":"Interface","name":"Leaf","superTypes":[{"$ref":"#/interfaces@0"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"number"},"isOptional":false}]},{"$type":"Interface","name":"ClassDefStatement","attributes":[{"$type":"TypeAttribute","name":"className","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"styleText","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"Treemap","attributes":[{"$type":"TypeAttribute","name":"TreemapRows","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@15"}}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]}],"imports":[],"types":[],"$comment":"/**\\n * Treemap grammar for Langium\\n * Converted from mindmap grammar\\n *\\n * The ML_COMMENT and NL hidden terminals handle whitespace, comments, and newlines\\n * before the treemap keyword, allowing for empty lines and comments before the\\n * treemap declaration.\\n */"}`)),"TreemapGrammarGrammar"),loadedTreeViewGrammarGrammar,TreeViewGrammarGrammar=__name(()=>loadedTreeViewGrammarGrammar??(loadedTreeViewGrammarGrammar=loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"TreeViewGrammar","rules":[{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","entry":true,"name":"TreeView","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"treeView-beta"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[],"cardinality":"?"},{"$type":"Assignment","feature":"nodes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"INDENTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]{1,}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ML_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\%\\\\%[^\\\\n]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"NL","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false},{"$type":"ParserRule","name":"TreeNode","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"indent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"STRING2","definition":{"$type":"RegexToken","regex":"/\\"[^\\"]*\\"|'[^']*'/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[{"$type":"Interface","name":"TreeView","attributes":[{"$type":"TypeAttribute","name":"nodes","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@9"}}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]}],"imports":[],"types":[],"$comment":"/**\\n * TreeView grammar for Langium\\n * Converted from treemap grammar\\n *\\n * The ML_COMMENT and NL hidden terminals handle whitespace, comments, and newlines\\n * before the treemap keyword, allowing for empty lines and comments before the\\n * treeView declaration.\\n */"}`)),"TreeViewGrammarGrammar"),loadedWardleyGrammarGrammar,WardleyGrammarGrammar=__name(()=>loadedWardleyGrammarGrammar??(loadedWardleyGrammarGrammar=loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"WardleyGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Wardley","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@42"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"size","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Assignment","feature":"anchors","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"components","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"links","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"evolves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}},{"$type":"Assignment","feature":"pipelines","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Assignment","feature":"notes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Assignment","feature":"annotations","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Assignment","feature":"annotation","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Assignment","feature":"accelerators","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"Assignment","feature":"deaccelerators","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Size","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@26"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"width","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"height","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Evolution","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@27"},"arguments":[]},{"$type":"Assignment","feature":"stages","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]},{"$type":"Assignment","feature":"stages","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}}],"cardinality":"+"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EvolutionStage","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"@"},{"$type":"Assignment","feature":"boundary","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}}],"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"/"},{"$type":"Assignment","feature":"secondName","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Anchor","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Component","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"decorator","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"inertia","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@31"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"inertia","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@31"},"arguments":[]}},{"$type":"Keyword","value":")"}]}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Label","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"negX","operator":"?=","terminal":{"$type":"Keyword","value":"-"},"cardinality":"?"},{"$type":"Assignment","feature":"offsetX","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"negY","operator":"?=","terminal":{"$type":"Keyword","value":"-"},"cardinality":"?"},{"$type":"Assignment","feature":"offsetY","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Decorator","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"strategy","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Link","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"from","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"fromPort","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"arrow","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}]},"cardinality":"?"},{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"toPort","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"linkLabel","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Evolve","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]},{"$type":"Assignment","feature":"component","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Pipeline","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@33"},"arguments":[]},{"$type":"Assignment","feature":"parent","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"{"},{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"+"},{"$type":"Assignment","feature":"components","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]},"cardinality":"+"},{"$type":"Keyword","value":"}"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PipelineComponent","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Note","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@34"},"arguments":[]},{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Annotations","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Annotation","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@36"},"arguments":[]},{"$type":"Assignment","feature":"number","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CoordinateValue","dataType":"number","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Accelerator","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@37"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Deaccelerator","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@38"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"WARDLEY_NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"->"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_PORT","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+<>"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+>"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+<"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_ARROW","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"-->"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"-.->"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":">"},"parenthesized":false}],"parenthesized":false},{"$type":"RegexToken","regex":"/\\\\+'[^']*'<>/","parenthesized":false}],"parenthesized":false},{"$type":"RegexToken","regex":"/\\\\+'[^']*'</","parenthesized":false}],"parenthesized":false},{"$type":"RegexToken","regex":"/\\\\+'[^']*'>/","parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_LABEL","definition":{"$type":"RegexToken","regex":"/;[^\\\\n\\\\r]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRATEGY","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"build"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"buy"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"outsource"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"market"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_WARDLEY","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"wardley-beta"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_SIZE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"size"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_EVOLUTION","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"evolution"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANCHOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"anchor"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_COMPONENT","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"component"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_LABEL","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"label"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_INERTIA","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"inertia"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_EVOLVE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"evolve"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_PIPELINE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"pipeline"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_NOTE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"note"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANNOTATIONS","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"annotations"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANNOTATION","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"annotation"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ACCELERATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"accelerator"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_DEACCELERATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"deaccelerator"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NAME_WITH_SPACES","definition":{"$type":"RegexToken","regex":"/(?!title\\\\s|accTitle|accDescr)[A-Za-z][A-Za-z0-9_()&]*(?:[ \\\\t]+[A-Za-z(][A-Za-z0-9_()&]*)*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@44"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@45"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@46"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@47"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@48"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)),"WardleyGrammarGrammar"),ArchitectureGrammarLanguageMetaData={languageId:"architecture",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},GitGraphGrammarLanguageMetaData={languageId:"gitGraph",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},InfoGrammarLanguageMetaData={languageId:"info",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},PacketGrammarLanguageMetaData={languageId:"packet",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},PieGrammarLanguageMetaData={languageId:"pie",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},RadarGrammarLanguageMetaData={languageId:"radar",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},TreemapGrammarLanguageMetaData={languageId:"treemap",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},TreeViewGrammarLanguageMetaData={languageId:"treeView",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},WardleyGrammarLanguageMetaData={languageId:"wardley",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},MermaidGeneratedSharedModule={AstReflection:__name(()=>new MermaidAstReflection,"AstReflection")},ArchitectureGrammarGeneratedModule={Grammar:__name(()=>ArchitectureGrammarGrammar(),"Grammar"),LanguageMetaData:__name(()=>ArchitectureGrammarLanguageMetaData,"LanguageMetaData"),parser:{}},GitGraphGrammarGeneratedModule={Grammar:__name(()=>GitGraphGrammarGrammar(),"Grammar"),LanguageMetaData:__name(()=>GitGraphGrammarLanguageMetaData,"LanguageMetaData"),parser:{}},InfoGrammarGeneratedModule={Grammar:__name(()=>InfoGrammarGrammar(),"Grammar"),LanguageMetaData:__name(()=>InfoGrammarLanguageMetaData,"LanguageMetaData"),parser:{}},PacketGrammarGeneratedModule={Grammar:__name(()=>PacketGrammarGrammar(),"Grammar"),LanguageMetaData:__name(()=>PacketGrammarLanguageMetaData,"LanguageMetaData"),parser:{}},PieGrammarGeneratedModule={Grammar:__name(()=>PieGrammarGrammar(),"Grammar"),LanguageMetaData:__name(()=>PieGrammarLanguageMetaData,"LanguageMetaData"),parser:{}},RadarGrammarGeneratedModule={Grammar:__name(()=>RadarGrammarGrammar(),"Grammar"),LanguageMetaData:__name(()=>RadarGrammarLanguageMetaData,"LanguageMetaData"),parser:{}},TreemapGrammarGeneratedModule={Grammar:__name(()=>TreemapGrammarGrammar(),"Grammar"),LanguageMetaData:__name(()=>TreemapGrammarLanguageMetaData,"LanguageMetaData"),parser:{}},TreeViewGrammarGeneratedModule={Grammar:__name(()=>TreeViewGrammarGrammar(),"Grammar"),LanguageMetaData:__name(()=>TreeViewGrammarLanguageMetaData,"LanguageMetaData"),parser:{}},WardleyGrammarGeneratedModule={Grammar:__name(()=>WardleyGrammarGrammar(),"Grammar"),LanguageMetaData:__name(()=>WardleyGrammarLanguageMetaData,"LanguageMetaData"),parser:{}},accessibilityDescrRegex=/accDescr(?:[\t ]*:([^\n\r]*)|\s*{([^}]*)})/,accessibilityTitleRegex=/accTitle[\t ]*:([^\n\r]*)/,titleRegex=/title([\t ][^\n\r]*|)/,rulesRegexes={ACC_DESCR:accessibilityDescrRegex,ACC_TITLE:accessibilityTitleRegex,TITLE:titleRegex},_a2,AbstractMermaidValueConverter=(_a2=class extends DefaultValueConverter{runConverter(rule,input,cstNode){let value=this.runCommonConverter(rule,input,cstNode);return value===void 0&&(value=this.runCustomConverter(rule,input,cstNode)),value===void 0?super.runConverter(rule,input,cstNode):value}runCommonConverter(rule,input,_cstNode){const regex=rulesRegexes[rule.name];if(regex===void 0)return;const match=regex.exec(input);if(match!==null){if(match[1]!==void 0)return match[1].trim().replace(/[\t ]{2,}/gm," ");if(match[2]!==void 0)return match[2].replace(/^\s*/gm,"").replace(/\s+$/gm,"").replace(/[\t ]{2,}/gm," ").replace(/[\n\r]{2,}/gm,`
160
+ `)}}},__name(_a2,"AbstractMermaidValueConverter"),_a2),_a3,CommonValueConverter=(_a3=class extends AbstractMermaidValueConverter{runCustomConverter(_rule,_input,_cstNode){}},__name(_a3,"CommonValueConverter"),_a3),_a4,AbstractMermaidTokenBuilder=(_a4=class extends DefaultTokenBuilder{constructor(keywords){super(),this.keywords=new Set(keywords)}buildKeywordTokens(rules,terminalTokens,options){const tokenTypes=super.buildKeywordTokens(rules,terminalTokens,options);return tokenTypes.forEach(tokenType=>{this.keywords.has(tokenType.name)&&tokenType.PATTERN!==void 0&&(tokenType.PATTERN=new RegExp(tokenType.PATTERN.toString()+"(?:(?=%%)|(?!\\S))"))}),tokenTypes}},__name(_a4,"AbstractMermaidTokenBuilder"),_a4),_a5;_a5=class extends AbstractMermaidTokenBuilder{},__name(_a5,"CommonTokenBuilder");var _a6,TreemapTokenBuilder=(_a6=class extends AbstractMermaidTokenBuilder{constructor(){super(["treemap"])}},__name(_a6,"TreemapTokenBuilder"),_a6),classDefRegex=/classDef\s+([A-Z_a-z]\w+)(?:\s+([^\n\r;]*))?;?/,_a7,TreemapValueConverter=(_a7=class extends AbstractMermaidValueConverter{runCustomConverter(rule,input,_cstNode){if(rule.name==="NUMBER2")return parseFloat(input.replace(/,/g,""));if(rule.name==="SEPARATOR")return input.substring(1,input.length-1);if(rule.name==="STRING2")return input.substring(1,input.length-1);if(rule.name==="INDENTATION")return input.length;if(rule.name==="ClassDef"){if(typeof input!="string")return input;const match=classDefRegex.exec(input);if(match)return{$type:"ClassDefStatement",className:match[1],styleText:match[2]||void 0}}}},__name(_a7,"TreemapValueConverter"),_a7);function registerValidationChecks(services){const validator=services.validation.TreemapValidator,registry=services.validation.ValidationRegistry;if(registry){const checks={Treemap:validator.checkSingleRoot.bind(validator)};registry.register(checks,validator)}}__name(registerValidationChecks,"registerValidationChecks");var _a8,TreemapValidator=(_a8=class{checkSingleRoot(doc,accept){let rootNodeIndentation;for(const row of doc.TreemapRows)row.item&&(rootNodeIndentation===void 0&&row.indent===void 0?rootNodeIndentation=0:row.indent===void 0?accept("error","Multiple root nodes are not allowed in a treemap.",{node:row,property:"item"}):rootNodeIndentation!==void 0&&rootNodeIndentation>=parseInt(row.indent,10)&&accept("error","Multiple root nodes are not allowed in a treemap.",{node:row,property:"item"}))}},__name(_a8,"TreemapValidator"),_a8),TreemapModule={parser:{TokenBuilder:__name(()=>new TreemapTokenBuilder,"TokenBuilder"),ValueConverter:__name(()=>new TreemapValueConverter,"ValueConverter")},validation:{TreemapValidator:__name(()=>new TreemapValidator,"TreemapValidator")}};function createTreemapServices(context=EmptyFileSystem){const shared=inject(createDefaultSharedCoreModule(context),MermaidGeneratedSharedModule),Treemap2=inject(createDefaultCoreModule({shared}),TreemapGrammarGeneratedModule,TreemapModule);return shared.ServiceRegistry.register(Treemap2),registerValidationChecks(Treemap2),{shared,Treemap:Treemap2}}__name(createTreemapServices,"createTreemapServices");var _a9,WardleyValueConverter=(_a9=class extends AbstractMermaidValueConverter{runCustomConverter(rule,input,_cstNode){switch(rule.name.toUpperCase()){case"LINK_LABEL":return input.substring(1).trim();default:return}}},__name(_a9,"WardleyValueConverter"),_a9),WardleyModule={parser:{ValueConverter:__name(()=>new WardleyValueConverter,"ValueConverter")}};function createWardleyServices(context=EmptyFileSystem){const shared=inject(createDefaultSharedCoreModule(context),MermaidGeneratedSharedModule),Wardley2=inject(createDefaultCoreModule({shared}),WardleyGrammarGeneratedModule,WardleyModule);return shared.ServiceRegistry.register(Wardley2),{shared,Wardley:Wardley2}}__name(createWardleyServices,"createWardleyServices");var _a10,GitGraphTokenBuilder=(_a10=class extends AbstractMermaidTokenBuilder{constructor(){super(["gitGraph"])}},__name(_a10,"GitGraphTokenBuilder"),_a10),GitGraphModule={parser:{TokenBuilder:__name(()=>new GitGraphTokenBuilder,"TokenBuilder"),ValueConverter:__name(()=>new CommonValueConverter,"ValueConverter")}};function createGitGraphServices(context=EmptyFileSystem){const shared=inject(createDefaultSharedCoreModule(context),MermaidGeneratedSharedModule),GitGraph2=inject(createDefaultCoreModule({shared}),GitGraphGrammarGeneratedModule,GitGraphModule);return shared.ServiceRegistry.register(GitGraph2),{shared,GitGraph:GitGraph2}}__name(createGitGraphServices,"createGitGraphServices");var _a11,InfoTokenBuilder=(_a11=class extends AbstractMermaidTokenBuilder{constructor(){super(["info","showInfo"])}},__name(_a11,"InfoTokenBuilder"),_a11),InfoModule={parser:{TokenBuilder:__name(()=>new InfoTokenBuilder,"TokenBuilder"),ValueConverter:__name(()=>new CommonValueConverter,"ValueConverter")}};function createInfoServices(context=EmptyFileSystem){const shared=inject(createDefaultSharedCoreModule(context),MermaidGeneratedSharedModule),Info2=inject(createDefaultCoreModule({shared}),InfoGrammarGeneratedModule,InfoModule);return shared.ServiceRegistry.register(Info2),{shared,Info:Info2}}__name(createInfoServices,"createInfoServices");var _a12,PacketTokenBuilder=(_a12=class extends AbstractMermaidTokenBuilder{constructor(){super(["packet"])}},__name(_a12,"PacketTokenBuilder"),_a12),PacketModule={parser:{TokenBuilder:__name(()=>new PacketTokenBuilder,"TokenBuilder"),ValueConverter:__name(()=>new CommonValueConverter,"ValueConverter")}};function createPacketServices(context=EmptyFileSystem){const shared=inject(createDefaultSharedCoreModule(context),MermaidGeneratedSharedModule),Packet2=inject(createDefaultCoreModule({shared}),PacketGrammarGeneratedModule,PacketModule);return shared.ServiceRegistry.register(Packet2),{shared,Packet:Packet2}}__name(createPacketServices,"createPacketServices");var _a13,PieTokenBuilder=(_a13=class extends AbstractMermaidTokenBuilder{constructor(){super(["pie","showData"])}},__name(_a13,"PieTokenBuilder"),_a13),_a14,PieValueConverter=(_a14=class extends AbstractMermaidValueConverter{runCustomConverter(rule,input,_cstNode){if(rule.name==="PIE_SECTION_LABEL")return input.replace(/"/g,"").trim()}},__name(_a14,"PieValueConverter"),_a14),PieModule={parser:{TokenBuilder:__name(()=>new PieTokenBuilder,"TokenBuilder"),ValueConverter:__name(()=>new PieValueConverter,"ValueConverter")}};function createPieServices(context=EmptyFileSystem){const shared=inject(createDefaultSharedCoreModule(context),MermaidGeneratedSharedModule),Pie2=inject(createDefaultCoreModule({shared}),PieGrammarGeneratedModule,PieModule);return shared.ServiceRegistry.register(Pie2),{shared,Pie:Pie2}}__name(createPieServices,"createPieServices");var _a15,TreeViewValueConverter=(_a15=class extends AbstractMermaidValueConverter{runCustomConverter(rule,input,_cstNode){if(rule.name==="INDENTATION")return(input==null?void 0:input.length)||0;if(rule.name==="STRING2")return input.substring(1,input.length-1)}},__name(_a15,"TreeViewValueConverter"),_a15),_a16,TreeViewTokenBuilder=(_a16=class extends AbstractMermaidTokenBuilder{constructor(){super(["treeView-beta"])}},__name(_a16,"TreeViewTokenBuilder"),_a16),TreeViewModule={parser:{TokenBuilder:__name(()=>new TreeViewTokenBuilder,"TokenBuilder"),ValueConverter:__name(()=>new TreeViewValueConverter,"ValueConverter")}};function createTreeViewServices(context=EmptyFileSystem){const shared=inject(createDefaultSharedCoreModule(context),MermaidGeneratedSharedModule),TreeView2=inject(createDefaultCoreModule({shared}),TreeViewGrammarGeneratedModule,TreeViewModule);return shared.ServiceRegistry.register(TreeView2),{shared,TreeView:TreeView2}}__name(createTreeViewServices,"createTreeViewServices");var _a17,ArchitectureTokenBuilder=(_a17=class extends AbstractMermaidTokenBuilder{constructor(){super(["architecture"])}},__name(_a17,"ArchitectureTokenBuilder"),_a17),_a18,ArchitectureValueConverter=(_a18=class extends AbstractMermaidValueConverter{runCustomConverter(rule,input,_cstNode){if(rule.name==="ARCH_ICON")return input.replace(/[()]/g,"").trim();if(rule.name==="ARCH_TEXT_ICON")return input.replace(/["()]/g,"");if(rule.name==="ARCH_TITLE"){let result=input.replace(/^\[|]$/g,"").trim();return(result.startsWith('"')&&result.endsWith('"')||result.startsWith("'")&&result.endsWith("'"))&&(result=result.slice(1,-1),result=result.replace(/\\"/g,'"').replace(/\\'/g,"'")),result.trim()}}},__name(_a18,"ArchitectureValueConverter"),_a18),ArchitectureModule={parser:{TokenBuilder:__name(()=>new ArchitectureTokenBuilder,"TokenBuilder"),ValueConverter:__name(()=>new ArchitectureValueConverter,"ValueConverter")}};function createArchitectureServices(context=EmptyFileSystem){const shared=inject(createDefaultSharedCoreModule(context),MermaidGeneratedSharedModule),Architecture2=inject(createDefaultCoreModule({shared}),ArchitectureGrammarGeneratedModule,ArchitectureModule);return shared.ServiceRegistry.register(Architecture2),{shared,Architecture:Architecture2}}__name(createArchitectureServices,"createArchitectureServices");var _a19,RadarTokenBuilder=(_a19=class extends AbstractMermaidTokenBuilder{constructor(){super(["radar-beta"])}},__name(_a19,"RadarTokenBuilder"),_a19),RadarModule={parser:{TokenBuilder:__name(()=>new RadarTokenBuilder,"TokenBuilder"),ValueConverter:__name(()=>new CommonValueConverter,"ValueConverter")}};function createRadarServices(context=EmptyFileSystem){const shared=inject(createDefaultSharedCoreModule(context),MermaidGeneratedSharedModule),Radar2=inject(createDefaultCoreModule({shared}),RadarGrammarGeneratedModule,RadarModule);return shared.ServiceRegistry.register(Radar2),{shared,Radar:Radar2}}__name(createRadarServices,"createRadarServices");var parsers={},initializers={info:__name(async()=>{const{createInfoServices:createInfoServices2}=await __vitePreload(async()=>{const{createInfoServices:createInfoServices22}=await Promise.resolve().then(()=>infoOMHHGYJF);return{createInfoServices:createInfoServices22}},void 0),parser=createInfoServices2().Info.parser.LangiumParser;parsers.info=parser},"info"),packet:__name(async()=>{const{createPacketServices:createPacketServices2}=await __vitePreload(async()=>{const{createPacketServices:createPacketServices22}=await Promise.resolve().then(()=>packet4T2RLAQJ);return{createPacketServices:createPacketServices22}},void 0),parser=createPacketServices2().Packet.parser.LangiumParser;parsers.packet=parser},"packet"),pie:__name(async()=>{const{createPieServices:createPieServices2}=await __vitePreload(async()=>{const{createPieServices:createPieServices22}=await Promise.resolve().then(()=>pieZZUOXDRM);return{createPieServices:createPieServices22}},void 0),parser=createPieServices2().Pie.parser.LangiumParser;parsers.pie=parser},"pie"),treeView:__name(async()=>{const{createTreeViewServices:createTreeViewServices2}=await __vitePreload(async()=>{const{createTreeViewServices:createTreeViewServices22}=await Promise.resolve().then(()=>treeViewSZITEDCU);return{createTreeViewServices:createTreeViewServices22}},void 0),parser=createTreeViewServices2().TreeView.parser.LangiumParser;parsers.treeView=parser},"treeView"),architecture:__name(async()=>{const{createArchitectureServices:createArchitectureServices2}=await __vitePreload(async()=>{const{createArchitectureServices:createArchitectureServices22}=await Promise.resolve().then(()=>architectureYZFGNWBL);return{createArchitectureServices:createArchitectureServices22}},void 0),parser=createArchitectureServices2().Architecture.parser.LangiumParser;parsers.architecture=parser},"architecture"),gitGraph:__name(async()=>{const{createGitGraphServices:createGitGraphServices2}=await __vitePreload(async()=>{const{createGitGraphServices:createGitGraphServices22}=await Promise.resolve().then(()=>gitGraph7Q5UKJZL);return{createGitGraphServices:createGitGraphServices22}},void 0),parser=createGitGraphServices2().GitGraph.parser.LangiumParser;parsers.gitGraph=parser},"gitGraph"),radar:__name(async()=>{const{createRadarServices:createRadarServices2}=await __vitePreload(async()=>{const{createRadarServices:createRadarServices22}=await Promise.resolve().then(()=>radarPYXPWWZC);return{createRadarServices:createRadarServices22}},void 0),parser=createRadarServices2().Radar.parser.LangiumParser;parsers.radar=parser},"radar"),treemap:__name(async()=>{const{createTreemapServices:createTreemapServices2}=await __vitePreload(async()=>{const{createTreemapServices:createTreemapServices22}=await Promise.resolve().then(()=>treemapW4RFUUIX);return{createTreemapServices:createTreemapServices22}},void 0),parser=createTreemapServices2().Treemap.parser.LangiumParser;parsers.treemap=parser},"treemap"),wardley:__name(async()=>{const{createWardleyServices:createWardleyServices2}=await __vitePreload(async()=>{const{createWardleyServices:createWardleyServices22}=await Promise.resolve().then(()=>wardleyRL74JXVD);return{createWardleyServices:createWardleyServices22}},void 0),parser=createWardleyServices2().Wardley.parser.LangiumParser;parsers.wardley=parser},"wardley")};async function parse(diagramType,text){const initializer=initializers[diagramType];if(!initializer)throw new Error(`Unknown diagram type: ${diagramType}`);parsers[diagramType]||await initializer();const result=parsers[diagramType].parse(text);if(result.lexerErrors.length>0||result.parserErrors.length>0)throw new MermaidParseError(result);return result.value}__name(parse,"parse");var _a20,MermaidParseError=(_a20=class extends Error{constructor(result){const lexerErrors=result.lexerErrors.map(err=>{const line=err.line!==void 0&&!isNaN(err.line)?err.line:"?",column=err.column!==void 0&&!isNaN(err.column)?err.column:"?";return`Lexer error on line ${line}, column ${column}: ${err.message}`}).join(`
161
+ `),parserErrors=result.parserErrors.map(err=>{const line=err.token.startLine!==void 0&&!isNaN(err.token.startLine)?err.token.startLine:"?",column=err.token.startColumn!==void 0&&!isNaN(err.token.startColumn)?err.token.startColumn:"?";return`Parse error on line ${line}, column ${column}: ${err.message}`}).join(`
162
+ `);super(`Parsing failed: ${lexerErrors} ${parserErrors}`),this.result=result}},__name(_a20,"MermaidParseError"),_a20);const infoOMHHGYJF=Object.freeze(Object.defineProperty({__proto__:null,InfoModule,createInfoServices},Symbol.toStringTag,{value:"Module"})),packet4T2RLAQJ=Object.freeze(Object.defineProperty({__proto__:null,PacketModule,createPacketServices},Symbol.toStringTag,{value:"Module"})),pieZZUOXDRM=Object.freeze(Object.defineProperty({__proto__:null,PieModule,createPieServices},Symbol.toStringTag,{value:"Module"})),treeViewSZITEDCU=Object.freeze(Object.defineProperty({__proto__:null,TreeViewModule,createTreeViewServices},Symbol.toStringTag,{value:"Module"})),architectureYZFGNWBL=Object.freeze(Object.defineProperty({__proto__:null,ArchitectureModule,createArchitectureServices},Symbol.toStringTag,{value:"Module"})),gitGraph7Q5UKJZL=Object.freeze(Object.defineProperty({__proto__:null,GitGraphModule,createGitGraphServices},Symbol.toStringTag,{value:"Module"})),radarPYXPWWZC=Object.freeze(Object.defineProperty({__proto__:null,RadarModule,createRadarServices},Symbol.toStringTag,{value:"Module"})),treemapW4RFUUIX=Object.freeze(Object.defineProperty({__proto__:null,TreemapModule,createTreemapServices},Symbol.toStringTag,{value:"Module"})),wardleyRL74JXVD=Object.freeze(Object.defineProperty({__proto__:null,WardleyModule,createWardleyServices},Symbol.toStringTag,{value:"Module"}));export{parse as p};