@likec4/mcp 1.60.0 → 1.61.0

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 (35) hide show
  1. package/README.md +104 -102
  2. package/dist/app/render-view-client.css +1 -1
  3. package/dist/app/render-view-client.js +375 -393
  4. package/dist/chunks/libs/@chenglou/pretext.mjs +9 -0
  5. package/dist/chunks/libs/@logtape/logtape.mjs +5 -5
  6. package/dist/chunks/libs/chevrotain.mjs +19 -19
  7. package/dist/chunks/libs/clone.mjs +1 -0
  8. package/dist/chunks/libs/eventemitter3.mjs +1 -1
  9. package/dist/chunks/libs/fast-equals.mjs +1 -0
  10. package/dist/chunks/libs/fontkit.mjs +1 -0
  11. package/dist/chunks/libs/fuse.js.mjs +1 -0
  12. package/dist/chunks/libs/graphology.mjs +1 -1
  13. package/dist/chunks/libs/hast-util-to-html.mjs +2 -2
  14. package/dist/chunks/libs/hastscript.mjs +1 -1
  15. package/dist/chunks/libs/immer.mjs +1 -1
  16. package/dist/chunks/libs/langium.mjs +2 -2
  17. package/dist/chunks/libs/markdown-table.mjs +1 -1
  18. package/dist/chunks/libs/mdast-util-find-and-replace.mjs +1 -1
  19. package/dist/chunks/libs/mdast-util-from-markdown.mjs +4 -4
  20. package/dist/chunks/libs/mdast-util-gfm.mjs +4 -4
  21. package/dist/chunks/libs/mdast-util-to-hast.mjs +3 -3
  22. package/dist/chunks/libs/micromark-extension-gfm.mjs +2 -2
  23. package/dist/chunks/libs/mnemonist.mjs +1 -1
  24. package/dist/chunks/libs/parse-entities.mjs +1 -1
  25. package/dist/chunks/libs/pathe.mjs +1 -1
  26. package/dist/chunks/libs/refractor.mjs +1 -1
  27. package/dist/chunks/libs/rehype-prism-plus.mjs +2 -2
  28. package/dist/chunks/libs/remark-github-blockquote-alert.mjs +1 -1
  29. package/dist/chunks/libs/remeda.mjs +1 -1
  30. package/dist/chunks/libs/unified.mjs +1 -1
  31. package/dist/chunks/libs/which.mjs +1 -1
  32. package/dist/chunks/rolldown-runtime.mjs +1 -1
  33. package/dist/chunks/src.mjs +193 -108
  34. package/dist/cli.mjs +1 -1
  35. package/package.json +27 -27
@@ -1 +1 @@
1
- import"../rolldown-runtime.mjs";var e=Symbol.for(`immer-nothing`),t=Symbol.for(`immer-draftable`),n=Symbol.for(`immer-state`);function die(e,...t){throw Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var r=Object,i=r.getPrototypeOf,a=`constructor`,o=`prototype`,s=`configurable`,c=`enumerable`,l=`writable`,u=`value`,isDraft=e=>!!e&&!!e[n];function isDraftable(e){return e?isPlainObject(e)||p(e)||!!e[t]||!!e[a]?.[t]||isMap(e)||isSet(e):!1}var d=r[o][a].toString(),f=/* @__PURE__ */ new WeakMap;function isPlainObject(e){if(!e||!isObjectish(e))return!1;let t=i(e);if(t===null||t===r[o])return!0;let n=r.hasOwnProperty.call(t,a)&&t[a];if(n===Object)return!0;if(!isFunction(n))return!1;let s=f.get(n);return s===void 0&&(s=Function.toString.call(n),f.set(n,s)),s===d}function each(e,t,n=!0){getArchtype(e)===0?(n?Reflect.ownKeys(e):r.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function getArchtype(e){let t=e[n];return t?t.type_:p(e)?1:isMap(e)?2:isSet(e)?3:0}var has=(e,t,n=getArchtype(e))=>n===2?e.has(t):r[o].hasOwnProperty.call(e,t),get=(e,t,n=getArchtype(e))=>n===2?e.get(t):e[t],set=(e,t,n,r=getArchtype(e))=>{r===2?e.set(t,n):r===3?e.add(n):e[t]=n};function is(e,t){return e===t?e!==0||1/e==1/t:e!==e&&t!==t}var p=Array.isArray,isMap=e=>e instanceof Map,isSet=e=>e instanceof Set,isObjectish=e=>typeof e==`object`,isFunction=e=>typeof e==`function`,isBoolean=e=>typeof e==`boolean`;function isArrayIndex(e){let t=+e;return Number.isInteger(t)&&String(t)===e}var latest=e=>e.copy_||e.base_,getFinalValue=e=>e.modified_?e.copy_:e.base_;function shallowCopy(e,t){if(isMap(e))return new Map(e);if(isSet(e))return new Set(e);if(p(e))return Array[o].slice.call(e);let a=isPlainObject(e);if(t===!0||t===`class_only`&&!a){let t=r.getOwnPropertyDescriptors(e);delete t[n];let a=Reflect.ownKeys(t);for(let n=0;n<a.length;n++){let r=a[n],i=t[r];i[l]===!1&&(i[l]=!0,i[s]=!0),(i.get||i.set)&&(t[r]={[s]:!0,[l]:!0,[c]:i[c],[u]:e[r]})}return r.create(i(e),t)}{let t=i(e);if(t!==null&&a)return{...e};let n=r.create(t);return r.assign(n,e)}}function freeze(e,t=!1){return isFrozen(e)||isDraft(e)||!isDraftable(e)||(getArchtype(e)>1&&r.defineProperties(e,{set:m,add:m,clear:m,delete:m}),r.freeze(e),t&&each(e,(e,t)=>{freeze(t,!0)},!1)),e}function dontMutateFrozenCollections(){die(2)}var m={[u]:dontMutateFrozenCollections};function isFrozen(e){return e===null||!isObjectish(e)||r.isFrozen(e)}var h=`MapSet`,g=`Patches`,_=`ArrayMethods`,v={};function getPlugin(e){let t=v[e];return t||die(0,e),t}var isPluginLoaded=e=>!!v[e],y,getCurrentScope=()=>y,createScope=(e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:/* @__PURE__ */ new Set,processedForPatches_:/* @__PURE__ */ new Set,mapSetPlugin_:isPluginLoaded(h)?getPlugin(h):void 0,arrayMethodsPlugin_:isPluginLoaded(_)?getPlugin(_):void 0});function usePatchesInScope(e,t){t&&(e.patchPlugin_=getPlugin(g),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function revokeScope(e){leaveScope(e),e.drafts_.forEach(revokeDraft),e.drafts_=null}function leaveScope(e){e===y&&(y=e.parent_)}var enterScope=e=>y=createScope(y,e);function revokeDraft(e){let t=e[n];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function processResult(t,r){r.unfinalizedDrafts_=r.drafts_.length;let i=r.drafts_[0];if(t!==void 0&&t!==i){i[n].modified_&&(revokeScope(r),die(4)),isDraftable(t)&&(t=finalize(r,t));let{patchPlugin_:e}=r;e&&e.generateReplacementPatches_(i[n].base_,t,r)}else t=finalize(r,i);return maybeFreeze(r,t,!0),revokeScope(r),r.patches_&&r.patchListener_(r.patches_,r.inversePatches_),t===e?void 0:t}function finalize(e,t){if(isFrozen(t))return t;let r=t[n];if(!r)return handleValue(t,e.handledSet_,e);if(!isSameScope(r,e))return t;if(!r.modified_)return r.base_;if(!r.finalized_){let{callbacks_:t}=r;if(t)for(;t.length>0;)t.pop()(e);generatePatchesAndFinalize(r,e)}return r.copy_}function maybeFreeze(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&freeze(t,n)}function markStateFinalized(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var isSameScope=(e,t)=>e.scope_===t,b=[];function updateDraftInParent(e,t,n,r){let i=latest(e),a=e.type_;if(r!==void 0&&get(i,r,a)===t){set(i,r,n,a);return}if(!e.draftLocations_){let t=e.draftLocations_=/* @__PURE__ */ new Map;each(i,(e,n)=>{if(isDraft(n)){let r=t.get(n)||[];r.push(e),t.set(n,r)}})}let o=e.draftLocations_.get(t)??b;for(let e of o)set(i,e,n,a)}function registerChildFinalizationCallback(e,t,n){e.callbacks_.push(function childCleanup(r){let i=t;if(!i||!isSameScope(i,r))return;r.mapSetPlugin_?.fixSetContents(i);let a=getFinalValue(i);updateDraftInParent(e,i.draft_??i,a,n),generatePatchesAndFinalize(i,r)})}function generatePatchesAndFinalize(e,t){if(e.modified_&&!e.finalized_&&(e.type_===3||e.type_===1&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){let{patchPlugin_:n}=t;if(n){let r=n.getPath(e);r&&n.generatePatches_(e,r,t)}markStateFinalized(e)}}function handleCrossReference(e,t,r){let{scope_:i}=e;if(isDraft(r)){let a=r[n];isSameScope(a,i)&&a.callbacks_.push(function crossReferenceCleanup(){prepareCopy(e),updateDraftInParent(e,r,getFinalValue(a),t)})}else isDraftable(r)&&e.callbacks_.push(function nestedDraftCleanup(){let n=latest(e);e.type_===3?n.has(r)&&handleValue(r,i.handledSet_,i):get(n,t,e.type_)===r&&i.drafts_.length>1&&(e.assigned_.get(t)??!1)===!0&&e.copy_&&handleValue(get(e.copy_,t,e.type_),i.handledSet_,i)})}function handleValue(e,t,r){return!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1||isDraft(e)||t.has(e)||!isDraftable(e)||isFrozen(e)||(t.add(e),each(e,(i,a)=>{if(isDraft(a)){let t=a[n];isSameScope(t,r)&&(set(e,i,getFinalValue(t),e.type_),markStateFinalized(t))}else isDraftable(a)&&handleValue(a,t,r)})),e}function createProxyProxy(e,t){let n=p(e),r={type_:+!!n,scope_:t?t.scope_:getCurrentScope(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0},i=r,a=x;n&&(i=[r],a=S);let{revoke:o,proxy:s}=Proxy.revocable(i,a);return r.draft_=s,r.revoke_=o,[s,r]}var x={get(e,t){if(t===n)return e;let r=e.scope_.arrayMethodsPlugin_,i=e.type_===1&&typeof t==`string`;if(i&&r?.isArrayOperationMethod(t))return r.createMethodInterceptor(e,t);let a=latest(e);if(!has(a,t,e.type_))return readPropFromProto(e,a,t);let o=a[t];if(e.finalized_||!isDraftable(o)||i&&e.operationMethod&&r?.isMutatingArrayMethod(e.operationMethod)&&isArrayIndex(t))return o;if(o===peek(e.base_,t)||isRelocatedBaseRef(e,t,o)){prepareCopy(e);let n=e.type_===1?+t:t,r=createProxy(e.scope_,o,e,n);return e.copy_[n]=r}return o},has(e,t){return t in latest(e)},ownKeys(e){return Reflect.ownKeys(latest(e))},set(e,t,r){let i=getDescriptorFromProto(latest(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){let i=peek(latest(e),t),a=i?.[n];if(a&&a.base_===r)return e.copy_[t]=r,e.assigned_.delete(t),!0;if(is(r,i)&&(r!==void 0||has(e.base_,t,e.type_)))return!0;prepareCopy(e),markChanged(e)}return e.copy_[t]===r&&(r!==void 0||has(e.copy_,t,e.type_))||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_.set(t,!0),handleCrossReference(e,t,r)),!0},deleteProperty(e,t){return prepareCopy(e),peek(e.base_,t)!==void 0||t in e.base_?(e.assigned_.set(t,!1),markChanged(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=latest(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{[l]:!0,[s]:e.type_!==1||t!==`length`,[c]:r[c],[u]:n[t]}},defineProperty(){die(11)},getPrototypeOf(e){return i(e.base_)},setPrototypeOf(){die(12)}},S={};for(let e in x){let t=x[e];S[e]=function(){let e=arguments;return e[0]=e[0][0],t.apply(this,e)}}S.deleteProperty=function(e,t){return S.set.call(this,e,t,void 0)},S.set=function(e,t,n){return x.set.call(this,e[0],t,n,e[0])};function peek(e,t){let r=e[n];return(r?latest(r):e)[t]}function isRelocatedBaseRef(e,t,r){return e.type_!==1||!e.allIndicesReassigned_||e.assigned_?.get(t)||!isDraftable(r)||r[n]?!1:e.baseRefs_.has(r)}function readPropFromProto(e,t,n){let r=getDescriptorFromProto(t,n);return r?u in r?r[u]:r.get?.call(e.draft_):void 0}function getDescriptorFromProto(e,t){if(!(t in e))return;let n=i(e);for(;n;){let e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=i(n)}}function markChanged(e){e.modified_||(e.modified_=!0,e.parent_&&markChanged(e.parent_))}function prepareCopy(e){e.copy_||=(e.assigned_=/* @__PURE__ */ new Map,shallowCopy(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Immer2=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(t,n,r)=>{if(isFunction(t)&&!isFunction(n)){let e=n;n=t;let r=this;return function curriedProduce(t=e,...i){return r.produce(t,e=>n.call(this,e,...i))}}isFunction(n)||die(6),r!==void 0&&!isFunction(r)&&die(7);let i;if(isDraftable(t)){let e=enterScope(this),a=createProxy(e,t,void 0),o=!0;try{i=n(a),o=!1}finally{o?revokeScope(e):leaveScope(e)}return usePatchesInScope(e,r),processResult(i,e)}if(!t||!isObjectish(t)){if(i=n(t),i===void 0&&(i=t),i===e&&(i=void 0),this.autoFreeze_&&freeze(i,!0),r){let e=[],n=[];getPlugin(g).generateReplacementPatches_(t,i,{patches_:e,inversePatches_:n}),r(e,n)}return i}die(1,t)},this.produceWithPatches=(e,t)=>{if(isFunction(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},isBoolean(t?.autoFreeze)&&this.setAutoFreeze(t.autoFreeze),isBoolean(t?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(t.useStrictShallowCopy),isBoolean(t?.useStrictIteration)&&this.setUseStrictIteration(t.useStrictIteration)}createDraft(e){isDraftable(e)||die(8),isDraft(e)&&(e=current(e));let t=enterScope(this),r=createProxy(t,e,void 0);return r[n].isManual_=!0,leaveScope(t),r}finishDraft(e,t){let r=e&&e[n];(!r||!r.isManual_)&&die(9);let{scope_:i}=r;return usePatchesInScope(i,t),processResult(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let r=t[n];if(r.path.length===0&&r.op===`replace`){e=r.value;break}}n>-1&&(t=t.slice(n+1));let r=getPlugin(g).applyPatches_;return isDraft(e)?r(e,t):this.produce(e,e=>r(e,t))}};function createProxy(e,t,n,r){let[i,a]=isMap(t)?getPlugin(h).proxyMap_(t,n):isSet(t)?getPlugin(h).proxySet_(t,n):createProxyProxy(t,n);return(n?.scope_??getCurrentScope()).drafts_.push(i),a.callbacks_=n?.callbacks_??[],a.key_=r,n&&r!==void 0?registerChildFinalizationCallback(n,a,r):a.callbacks_.push(function rootDraftCleanup(e){e.mapSetPlugin_?.fixSetContents(a);let{patchPlugin_:t}=e;a.modified_&&t&&t.generatePatches_(a,[],e)}),i}function current(e){return isDraft(e)||die(10,e),currentImpl(e)}function currentImpl(e){if(!isDraftable(e)||isFrozen(e))return e;let t=e[n],r,i=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=shallowCopy(e,t.scope_.immer_.useStrictShallowCopy_),i=t.scope_.immer_.shouldUseStrictIteration()}else r=shallowCopy(e,!0);return each(r,(e,t)=>{set(r,e,currentImpl(t))},i),t&&(t.finalized_=!1),r}globalThis.Iterator?.from;var C=new Immer2().produce,castDraft=e=>e;export{C as n,castDraft as t};
1
+ import"../rolldown-runtime.mjs";var e=Symbol.for(`immer-nothing`),t=Symbol.for(`immer-draftable`),n=Symbol.for(`immer-state`);function die(e,...t){throw Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var r=Object,i=r.getPrototypeOf,a=`constructor`,o=`prototype`,s=`configurable`,c=`enumerable`,l=`writable`,u=`value`,isDraft=e=>!!e&&!!e[n];function isDraftable(e){return e?isPlainObject(e)||p(e)||!!e[t]||!!e[a]?.[t]||isMap(e)||isSet(e):!1}var d=r[o][a].toString(),f=/* @__PURE__ */ new WeakMap;function isPlainObject(e){if(!e||!isObjectish(e))return!1;let t=i(e);if(t===null||t===r[o])return!0;let n=r.hasOwnProperty.call(t,a)&&t[a];if(n===Object)return!0;if(!isFunction(n))return!1;let s=f.get(n);return s===void 0&&(s=Function.toString.call(n),f.set(n,s)),s===d}function each(e,t,n=!0){getArchtype(e)===0?(n?Reflect.ownKeys(e):r.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function getArchtype(e){let t=e[n];return t?t.type_:p(e)?1:isMap(e)?2:isSet(e)?3:0}var has=(e,t,n=getArchtype(e))=>n===2?e.has(t):r[o].hasOwnProperty.call(e,t),get=(e,t,n=getArchtype(e))=>n===2?e.get(t):e[t],set=(e,t,n,r=getArchtype(e))=>{r===2?e.set(t,n):r===3?e.add(n):e[t]=n};function is(e,t){return e===t?e!==0||1/e==1/t:e!==e&&t!==t}var p=Array.isArray,isMap=e=>e instanceof Map,isSet=e=>e instanceof Set,isObjectish=e=>typeof e==`object`,isFunction=e=>typeof e==`function`,isBoolean=e=>typeof e==`boolean`;function isArrayIndex(e){let t=+e;return Number.isInteger(t)&&String(t)===e}var latest=e=>e.copy_||e.base_,getFinalValue=e=>e.modified_?e.copy_:e.base_;function shallowCopy(e,t){if(isMap(e))return new Map(e);if(isSet(e))return new Set(e);if(p(e))return Array[o].slice.call(e);let a=isPlainObject(e);if(t===!0||t===`class_only`&&!a){let t=r.getOwnPropertyDescriptors(e);delete t[n];let a=Reflect.ownKeys(t);for(let n=0;n<a.length;n++){let r=a[n],i=t[r];i[l]===!1&&(i[l]=!0,i[s]=!0),(i.get||i.set)&&(t[r]={[s]:!0,[l]:!0,[c]:i[c],[u]:e[r]})}return r.create(i(e),t)}{let t=i(e);if(t!==null&&a)return{...e};let n=r.create(t);return r.assign(n,e)}}function freeze(e,t=!1){return isFrozen(e)||isDraft(e)||!isDraftable(e)||(getArchtype(e)>1&&r.defineProperties(e,{set:m,add:m,clear:m,delete:m}),r.freeze(e),t&&each(e,(e,t)=>{freeze(t,!0)},!1)),e}function dontMutateFrozenCollections(){die(2)}var m={[u]:dontMutateFrozenCollections};function isFrozen(e){return e===null||!isObjectish(e)||r.isFrozen(e)}var h=`MapSet`,g=`Patches`,_=`ArrayMethods`,v={};function getPlugin(e){let t=v[e];return t||die(0,e),t}var isPluginLoaded=e=>!!v[e],y,getCurrentScope=()=>y,createScope=(e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:/* @__PURE__ */ new Set,processedForPatches_:/* @__PURE__ */ new Set,mapSetPlugin_:isPluginLoaded(h)?getPlugin(h):void 0,arrayMethodsPlugin_:isPluginLoaded(_)?getPlugin(_):void 0});function usePatchesInScope(e,t){t&&(e.patchPlugin_=getPlugin(g),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function revokeScope(e){leaveScope(e),e.drafts_.forEach(revokeDraft),e.drafts_=null}function leaveScope(e){e===y&&(y=e.parent_)}var enterScope=e=>y=createScope(y,e);function revokeDraft(e){let t=e[n];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function processResult(t,r){r.unfinalizedDrafts_=r.drafts_.length;let i=r.drafts_[0];if(t!==void 0&&t!==i){i[n].modified_&&(revokeScope(r),die(4)),isDraftable(t)&&(t=finalize(r,t));let{patchPlugin_:e}=r;e&&e.generateReplacementPatches_(i[n].base_,t,r)}else t=finalize(r,i);return maybeFreeze(r,t,!0),revokeScope(r),r.patches_&&r.patchListener_(r.patches_,r.inversePatches_),t===e?void 0:t}function finalize(e,t){if(isFrozen(t))return t;let r=t[n];if(!r)return handleValue(t,e.handledSet_,e);if(!isSameScope(r,e))return t;if(!r.modified_)return r.base_;if(!r.finalized_){let{callbacks_:t}=r;if(t)for(;t.length>0;)t.pop()(e);generatePatchesAndFinalize(r,e)}return r.copy_}function maybeFreeze(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&freeze(t,n)}function markStateFinalized(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var isSameScope=(e,t)=>e.scope_===t,b=[];function updateDraftInParent(e,t,n,r){let i=latest(e),a=e.type_;if(r!==void 0&&get(i,r,a)===t){set(i,r,n,a);return}if(!e.draftLocations_){let t=e.draftLocations_=/* @__PURE__ */ new Map;each(i,(e,n)=>{if(isDraft(n)){let r=t.get(n)||[];r.push(e),t.set(n,r)}})}let o=e.draftLocations_.get(t)??b;for(let e of o)set(i,e,n,a)}function registerChildFinalizationCallback(e,t,n){e.callbacks_.push(function childCleanup(r){let i=t;if(!i||!isSameScope(i,r))return;r.mapSetPlugin_?.fixSetContents(i);let a=getFinalValue(i);updateDraftInParent(e,i.draft_??i,a,n),generatePatchesAndFinalize(i,r)})}function generatePatchesAndFinalize(e,t){if(e.modified_&&!e.finalized_&&(e.type_===3||e.type_===1&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){let{patchPlugin_:n}=t;if(n){let r=n.getPath(e);r&&n.generatePatches_(e,r,t)}markStateFinalized(e)}}function handleCrossReference(e,t,r){let{scope_:i}=e;if(isDraft(r)){let a=r[n];isSameScope(a,i)&&a.callbacks_.push(function crossReferenceCleanup(){prepareCopy(e),updateDraftInParent(e,r,getFinalValue(a),t)})}else isDraftable(r)&&e.callbacks_.push(function nestedDraftCleanup(){let n=latest(e);e.type_===3?n.has(r)&&handleValue(r,i.handledSet_,i):get(n,t,e.type_)===r&&i.drafts_.length>1&&(e.assigned_.get(t)??!1)===!0&&e.copy_&&handleValue(get(e.copy_,t,e.type_),i.handledSet_,i)})}function handleValue(e,t,r){return!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1||isDraft(e)||t.has(e)||!isDraftable(e)||isFrozen(e)||(t.add(e),each(e,(i,a)=>{if(isDraft(a)){let t=a[n];isSameScope(t,r)&&(set(e,i,getFinalValue(t),e.type_),markStateFinalized(t))}else isDraftable(a)&&handleValue(a,t,r)})),e}function createProxyProxy(e,t){let n=p(e),r={type_:+!!n,scope_:t?t.scope_:getCurrentScope(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0},i=r,a=x;n&&(i=[r],a=S);let{revoke:o,proxy:s}=Proxy.revocable(i,a);return r.draft_=s,r.revoke_=o,[s,r]}var x={get(e,t){if(t===n)return e;let r=e.scope_.arrayMethodsPlugin_,i=e.type_===1&&typeof t==`string`;if(i&&r?.isArrayOperationMethod(t))return r.createMethodInterceptor(e,t);let a=latest(e);if(!has(a,t,e.type_))return readPropFromProto(e,a,t);let o=a[t];if(e.finalized_||!isDraftable(o)||i&&e.operationMethod&&r?.isMutatingArrayMethod(e.operationMethod)&&isArrayIndex(t))return o;if(o===peek(e.base_,t)||isRelocatedBaseRef(e,t,o)){prepareCopy(e);let n=e.type_===1?+t:t,r=createProxy(e.scope_,o,e,n);return e.copy_[n]=r}return o},has(e,t){return t in latest(e)},ownKeys(e){return Reflect.ownKeys(latest(e))},set(e,t,r){let i=getDescriptorFromProto(latest(e),t);if(i?.set)return i.set.call(e.draft_,r),!0;if(!e.modified_){let i=peek(latest(e),t),a=i?.[n];if(a&&a.base_===r)return e.copy_[t]=r,e.assigned_.delete(t),!0;if(is(r,i)&&(r!==void 0||has(e.base_,t,e.type_)))return!0;prepareCopy(e),markChanged(e)}return e.copy_[t]===r&&(r!==void 0||has(e.copy_,t,e.type_))||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_.set(t,!0),handleCrossReference(e,t,r)),!0},deleteProperty(e,t){return prepareCopy(e),peek(e.base_,t)!==void 0||t in e.base_?(e.assigned_.set(t,!1),markChanged(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=latest(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{[l]:!0,[s]:e.type_!==1||t!==`length`,[c]:r[c],[u]:n[t]}},defineProperty(){die(11)},getPrototypeOf(e){return i(e.base_)},setPrototypeOf(){die(12)}},S={};for(let e in x){let t=x[e];S[e]=function(){let e=arguments;return e[0]=e[0][0],t.apply(this,e)}}S.deleteProperty=function(e,t){return S.set.call(this,e,t,void 0)},S.set=function(e,t,n){return x.set.call(this,e[0],t,n,e[0])};function peek(e,t){let r=e[n];return(r?latest(r):e)[t]}function isRelocatedBaseRef(e,t,r){return e.type_!==1||!e.allIndicesReassigned_||e.assigned_?.get(t)||!isDraftable(r)||r[n]?!1:e.baseRefs_.has(r)}function readPropFromProto(e,t,n){let r=getDescriptorFromProto(t,n);return r?u in r?r[u]:r.get?.call(e.draft_):void 0}function getDescriptorFromProto(e,t){if(!(t in e))return;let n=i(e);for(;n;){let e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=i(n)}}function markChanged(e){e.modified_||(e.modified_=!0,e.parent_&&markChanged(e.parent_))}function prepareCopy(e){e.copy_||=(e.assigned_=/* @__PURE__ */ new Map,shallowCopy(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Immer2=class{constructor(t){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(t,n,r)=>{if(isFunction(t)&&!isFunction(n)){let e=n;n=t;let r=this;return function curriedProduce(t=e,...i){return r.produce(t,e=>n.call(this,e,...i))}}isFunction(n)||die(6),r!==void 0&&!isFunction(r)&&die(7);let i;if(isDraftable(t)){let e=enterScope(this),a=createProxy(e,t,void 0),o=!0;try{i=n(a),o=!1}finally{o?revokeScope(e):leaveScope(e)}return usePatchesInScope(e,r),processResult(i,e)}if(!t||!isObjectish(t)){if(i=n(t),i===void 0&&(i=t),i===e&&(i=void 0),this.autoFreeze_&&freeze(i,!0),r){let e=[],n=[];getPlugin(g).generateReplacementPatches_(t,i,{patches_:e,inversePatches_:n}),r(e,n)}return i}die(1,t)},this.produceWithPatches=(e,t)=>{if(isFunction(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},isBoolean(t?.autoFreeze)&&this.setAutoFreeze(t.autoFreeze),isBoolean(t?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(t.useStrictShallowCopy),isBoolean(t?.useStrictIteration)&&this.setUseStrictIteration(t.useStrictIteration)}createDraft(e){isDraftable(e)||die(8),isDraft(e)&&(e=current(e));let t=enterScope(this),r=createProxy(t,e,void 0);return r[n].isManual_=!0,leaveScope(t),r}finishDraft(e,t){let r=e&&e[n];r&&r.isManual_||die(9);let{scope_:i}=r;return usePatchesInScope(i,t),processResult(void 0,i)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let r=t[n];if(r.path.length===0&&r.op===`replace`){e=r.value;break}}n>-1&&(t=t.slice(n+1));let r=getPlugin(g).applyPatches_;return isDraft(e)?r(e,t):this.produce(e,e=>r(e,t))}};function createProxy(e,t,n,r){let[i,a]=isMap(t)?getPlugin(h).proxyMap_(t,n):isSet(t)?getPlugin(h).proxySet_(t,n):createProxyProxy(t,n);return(n?.scope_??getCurrentScope()).drafts_.push(i),a.callbacks_=n?.callbacks_??[],a.key_=r,n&&r!==void 0?registerChildFinalizationCallback(n,a,r):a.callbacks_.push(function rootDraftCleanup(e){e.mapSetPlugin_?.fixSetContents(a);let{patchPlugin_:t}=e;a.modified_&&t&&t.generatePatches_(a,[],e)}),i}function current(e){return isDraft(e)||die(10,e),currentImpl(e)}function currentImpl(e){if(!isDraftable(e)||isFrozen(e))return e;let t=e[n],r,i=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=shallowCopy(e,t.scope_.immer_.useStrictShallowCopy_),i=t.scope_.immer_.shouldUseStrictIteration()}else r=shallowCopy(e,!0);return each(r,(e,t)=>{set(r,e,currentImpl(t))},i),t&&(t.finalized_=!1),r}globalThis.Iterator?.from;var C=new Immer2().produce,castDraft=e=>e;export{C as n,castDraft as t};
@@ -8,10 +8,10 @@ import{i as e,r as t}from"../rolldown-runtime.mjs";import{n,t as r}from"./@chevr
8
8
  `)?`
9
9
  `:`
10
10
 
11
- `}var JSDocDocumentationProvider=class{constructor(e){this.indexManager=e.shared.workspace.IndexManager,this.commentProvider=e.documentation.CommentProvider}getDocumentation(e){let t=this.commentProvider.getComment(e);if(t&&isJSDoc(t))return parseJSDoc(t).toMarkdown({renderLink:(t,n)=>this.documentationLinkRenderer(e,t,n),renderTag:t=>this.documentationTagRenderer(e,t)})}documentationLinkRenderer(e,t,n){let r=this.findNameInLocalSymbols(e,t)??this.findNameInGlobalScope(e,t);if(r&&r.nameSegment){let e=r.nameSegment.range.start.line+1,t=r.nameSegment.range.start.character+1;return`[${n}](${r.documentUri.with({fragment:`L${e},${t}`}).toString()})`}}documentationTagRenderer(e,t){}findNameInLocalSymbols(e,t){let n=getDocument(e).localSymbols;if(!n)return;let r=e;do{let e=n.getStream(r).find(e=>e.name===t);if(e)return e;r=r.$container}while(r)}findNameInGlobalScope(e,t){return this.indexManager.allElements().find(e=>e.name===t)}},DefaultAsyncParser=class{constructor(e){this.syncParser=e.parser.LangiumParser}parse(e,t){return Promise.resolve(this.syncParser.parse(e))}},DefaultLexerErrorMessageProvider=class{buildUnexpectedCharactersMessage(e,t,n,r,i){return u.buildUnexpectedCharactersMessage(e,t,n,r,i)}buildUnableToPopLexerModeMessage(e){return u.buildUnableToPopLexerModeMessage(e)}};const St={mode:`full`};var DefaultLexer=class{constructor(e){this.errorMessageProvider=e.parser.LexerErrorMessageProvider,this.tokenBuilder=e.parser.TokenBuilder;let t=this.tokenBuilder.buildTokens(e.Grammar,{caseInsensitive:e.LanguageMetaData.caseInsensitive});this.tokenTypes=this.toTokenTypeDictionary(t);let n=isTokenTypeDictionary(t)?Object.values(t):t,r=e.LanguageMetaData.mode===`production`;this.chevrotainLexer=new a(n,{positionTracking:`full`,skipValidations:r,errorMessageProvider:this.errorMessageProvider})}get definition(){return this.tokenTypes}tokenize(e,t=St){let n=this.chevrotainLexer.tokenize(e);return{tokens:n.tokens,errors:n.errors,hidden:n.groups.hidden??[],report:this.tokenBuilder.flushLexingReport?.(e)}}toTokenTypeDictionary(e){if(isTokenTypeDictionary(e))return e;let t=isIMultiModeLexerDefinition(e)?Object.values(e.modes).flat():e,n={};return t.forEach(e=>n[e.name]=e),n}};function isTokenTypeArray(e){return Array.isArray(e)&&(e.length===0||`name`in e[0])}function isIMultiModeLexerDefinition(e){return e&&`modes`in e&&`defaultMode`in e}function isTokenTypeDictionary(e){return!isTokenTypeArray(e)&&!isIMultiModeLexerDefinition(e)}var DefaultHydrator=class{constructor(e){this.grammarElementIdMap=new BiMap,this.tokenTypeIdMap=new BiMap,this.cstNodeBuilder=new CstNodeBuilder,this.grammar=e.Grammar,this.lexer=e.parser.Lexer,this.linker=e.references.Linker}dehydrate(e){return{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport?this.dehydrateLexerReport(e.lexerReport):void 0,parserErrors:e.parserErrors.map(e=>({...e,message:e.message})),value:this.dehydrateAstNode(e.value,this.createDehyrationContext(e.value))}}dehydrateLexerReport(e){return e}createDehyrationContext(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let n of streamAst(e))t.set(n,{});if(e.$cstNode)for(let t of streamCst(e.$cstNode))n.set(t,{});return{astNodes:t,cstNodes:n}}dehydrateAstNode(e,t){let n=t.astNodes.get(e);n.$type=e.$type,n.$containerIndex=e.$containerIndex,n.$containerProperty=e.$containerProperty,e.$cstNode!==void 0&&(n.$cstNode=this.dehydrateCstNode(e.$cstNode,t));for(let[r,i]of Object.entries(e))if(!r.startsWith(`$`)){if(Array.isArray(i)){let e=[];n[r]=e;for(let n of i)isAstNode(n)?e.push(this.dehydrateAstNode(n,t)):isReference(n)?e.push(this.dehydrateReference(n,t)):e.push(n)}else isAstNode(i)?n[r]=this.dehydrateAstNode(i,t):isReference(i)?n[r]=this.dehydrateReference(i,t):i!==void 0&&(n[r]=i)}return n}dehydrateReference(e,t){let n={};return n.$refText=e.$refText,e.$refNode&&(n.$refNode=t.cstNodes.get(e.$refNode)),n}dehydrateCstNode(e,t){let n=t.cstNodes.get(e);if(isRootCstNode(e)?n.fullText=e.fullText:n.grammarSource=this.getGrammarElementId(e.grammarSource),n.hidden=e.hidden,isCompositeCstNode(e))n.content=e.content.map(e=>this.dehydrateCstNode(e,t));else if(isLeafCstNode(e)){n.tokenType=e.tokenType.name,n.offset=e.offset,n.length=e.length;let{start:t,end:r}=e.range;n.startLine=t.line,n.startColumn=t.character,n.endLine=r.line,n.endColumn=r.character}return n}hydrate(e){let t=e.value,n=this.createHydrationContext(t);return`$cstNode`in t&&this.hydrateCstNode(t.$cstNode,n),{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport,parserErrors:e.parserErrors,value:this.hydrateAstNode(t,n)}}createHydrationContext(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let n of streamAst(e))t.set(n,{});if(e.$cstNode)for(let t of streamCst(e.$cstNode)){let e;`fullText`in t?e=new RootCstNodeImpl(t.fullText):`content`in t?e=new CompositeCstNodeImpl:`tokenType`in t&&(e=this.hydrateCstLeafNode(t)),e&&n.set(t,e)}return{astNodes:t,cstNodes:n,linkedCstNodes:/* @__PURE__ */ new Set}}hydrateAstNode(e,t){let n=t.astNodes.get(e);if(n.$type=e.$type,n.$containerIndex=e.$containerIndex,n.$containerProperty=e.$containerProperty,e.$cstNode){let r=t.cstNodes.get(e.$cstNode);n.$cstNode=r,r&&!t.linkedCstNodes.has(r)&&(t.linkedCstNodes.add(r),r.astNode=n)}for(let[r,i]of Object.entries(e))if(!r.startsWith(`$`)){if(Array.isArray(i)){let e=[];n[r]=e;for(let a of i)isAstNode(a)?e.push(this.setParent(this.hydrateAstNode(a,t),n)):isReference(a)?e.push(this.hydrateReference(a,n,r,t)):e.push(a)}else isAstNode(i)?n[r]=this.setParent(this.hydrateAstNode(i,t),n):isReference(i)?n[r]=this.hydrateReference(i,n,r,t):i!==void 0&&(n[r]=i)}return n}setParent(e,t){return e.$container=t,e}hydrateReference(e,t,n,r){return this.linker.buildReference(t,n,r.cstNodes.get(e.$refNode),e.$refText)}hydrateCstNode(e,t,n=0){let r=t.cstNodes.get(e);if(typeof e.grammarSource==`number`&&(r.grammarSource=this.getGrammarElement(e.grammarSource)),isCompositeCstNode(r)){let i=[];for(let r of e.content)i.push(this.hydrateCstNode(r,t,n++));this.cstNodeBuilder.appendChildren(r,i)}return r}hydrateCstLeafNode(e){let t=this.getTokenType(e.tokenType);return new LeafCstNodeImpl(e.offset,e.length,e.startLine,e.startColumn,e.endLine,e.endColumn,t,e.hidden)}getTokenType(e){return this.lexer.definition[e]}getGrammarElementId(e){if(e)return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.get(e)}getGrammarElement(e){return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.getKey(e)}createGrammarElementIdMap(){let e=0;for(let t of streamAst(this.grammar))isAbstractElement(t)&&this.grammarElementIdMap.set(t,e++)}},Ct;(function(e){function create(e){return{dispose:async()=>await e()}}e.create=create})(Ct||={});var EmptyFileSystemProvider=class{stat(e){throw Error(`No file system is available.`)}statSync(e){throw Error(`No file system is available.`)}async exists(){return!1}existsSync(){return!1}readBinary(){throw Error(`No file system is available.`)}readBinarySync(){throw Error(`No file system is available.`)}readFile(){throw Error(`No file system is available.`)}readFileSync(){throw Error(`No file system is available.`)}async readDirectory(){return[]}readDirectorySync(){return[]}};const wt={fileSystemProvider:()=>new EmptyFileSystemProvider},Tt={Grammar:()=>void 0,LanguageMetaData:()=>({caseInsensitive:!1,fileExtensions:[`.langium`],languageId:`langium`})},Et={AstReflection:()=>new LangiumGrammarAstReflection};function createMinimalGrammarServices(){let e=inject(createDefaultSharedCoreModule(wt),Et),t=inject(createDefaultCoreModule({shared:e}),Tt);return e.ServiceRegistry.register(t),t}function loadGrammarFromJson(e){let t=createMinimalGrammarServices(),n=t.serializer.JsonSerializer.deserialize(e);return t.shared.workspace.LangiumDocumentFactory.fromModel(n,y.parse(`memory:/${n.name??`grammar`}.langium`)),n}var DefaultAstNodeDescriptionProvider=class{constructor(e){this.astNodeLocator=e.workspace.AstNodeLocator,this.nameProvider=e.references.NameProvider}createDescription(e,t,n){let r=n??getDocument(e);t??=this.nameProvider.getName(e);let i=this.astNodeLocator.getAstNodePath(e);if(!t)throw Error(`Node at path ${i} has no name.`);let a,nameSegmentGetter=()=>a??=toDocumentSegment(this.nameProvider.getNameNode(e)??e.$cstNode);return{node:e,name:t,get nameSegment(){return nameSegmentGetter()},selectionSegment:toDocumentSegment(e.$cstNode),type:e.$type,documentUri:r.uri,path:i}}},DefaultReferenceDescriptionProvider=class{constructor(e){this.nodeLocator=e.workspace.AstNodeLocator}async createDescriptions(e,t=b.None){let n=[],r=e.parseResult.value;for(let e of streamAst(r))await interruptAndCheck(t),streamReferences(e).forEach(e=>{e.reference.error||n.push(...this.createInfoDescriptions(e))});return n}createInfoDescriptions(e){let t=e.reference;if(t.error||!t.$refNode)return[];let n=[];isReference(t)&&t.$nodeDescription?n=[t.$nodeDescription]:isMultiReference(t)&&(n=t.items.map(e=>e.$nodeDescription).filter(e=>e!==void 0));let r=getDocument(e.container).uri,i=this.nodeLocator.getAstNodePath(e.container),a=[],o=toDocumentSegment(t.$refNode);for(let e of n)a.push({sourceUri:r,sourcePath:i,targetUri:e.documentUri,targetPath:e.path,segment:o,local:J.equals(e.documentUri,r)});return a}},DefaultAstNodeLocator=class{constructor(){this.segmentSeparator=`/`,this.indexSeparator=`@`}getAstNodePath(e){if(e.$container){let t=this.getAstNodePath(e.$container),n=this.getPathSegment(e);return t+this.segmentSeparator+n}return``}getPathSegment({$containerProperty:e,$containerIndex:t}){if(!e)throw Error(`Missing '$containerProperty' in AST node.`);return t===void 0?e:e+this.indexSeparator+t}getAstNode(e,t){return t.split(this.segmentSeparator).reduce((e,t)=>{if(!e||t.length===0)return e;let n=t.indexOf(this.indexSeparator);if(n>0){let r=t.substring(0,n),i=parseInt(t.substring(n+1));return e[r]?.[i]}return e[t]},e)}},DefaultConfigurationProvider=class{constructor(e){this._ready=new Deferred,this.onConfigurationSectionUpdateEmitter=new ge,this.settings={},this.workspaceConfig=!1,this.serviceRegistry=e.ServiceRegistry}get ready(){return this._ready.promise}initialize(e){this.workspaceConfig=e.capabilities.workspace?.configuration??!1}async initialized(e){if(this.workspaceConfig){if(e.register){let t=this.serviceRegistry.all;e.register({section:t.map(e=>this.toSectionName(e.LanguageMetaData.languageId))})}if(e.fetchConfiguration){let t=this.serviceRegistry.all.map(e=>({section:this.toSectionName(e.LanguageMetaData.languageId)})),n=await e.fetchConfiguration(t);t.forEach((e,t)=>{this.updateSectionConfiguration(e.section,n[t])})}}this._ready.resolve()}updateConfiguration(e){typeof e.settings==`object`&&e.settings!==null&&Object.entries(e.settings).forEach(([e,t])=>{this.updateSectionConfiguration(e,t),this.onConfigurationSectionUpdateEmitter.fire({section:e,configuration:t})})}updateSectionConfiguration(e,t){this.settings[e]=t}async getConfiguration(e,t){await this.ready;let n=this.toSectionName(e);if(this.settings[n])return this.settings[n][t]}toSectionName(e){return`${e}`}get onConfigurationSectionUpdate(){return this.onConfigurationSectionUpdateEmitter.event}},DefaultDocumentBuilder=class{constructor(e){this.updateBuildOptions={validation:{categories:[`built-in`,`fast`]}},this.updateListeners=[],this.buildPhaseListeners=new MultiMap,this.documentPhaseListeners=new MultiMap,this.buildState=/* @__PURE__ */ new Map,this.documentBuildWaiters=/* @__PURE__ */ new Map,this.currentState=X.Changed,this.langiumDocuments=e.workspace.LangiumDocuments,this.langiumDocumentFactory=e.workspace.LangiumDocumentFactory,this.textDocuments=e.workspace.TextDocuments,this.indexManager=e.workspace.IndexManager,this.fileSystemProvider=e.workspace.FileSystemProvider,this.workspaceManager=()=>e.workspace.WorkspaceManager,this.serviceRegistry=e.ServiceRegistry}async build(e,t={},n=b.None){for(let n of e){let e=n.uri.toString();if(n.state===X.Validated){if(typeof t.validation==`boolean`&&t.validation)this.resetToState(n,X.IndexedReferences);else if(typeof t.validation==`object`){let r=this.findMissingValidationCategories(n,t);r.length>0&&(this.buildState.set(e,{completed:!1,options:{validation:{categories:r}},result:this.buildState.get(e)?.result}),n.state=X.IndexedReferences)}}else this.buildState.delete(e)}this.currentState=X.Changed,await this.emitUpdate(e.map(e=>e.uri),[]),await this.buildDocuments(e,t,n)}async update(e,t,n=b.None){this.currentState=X.Changed;let r=[];for(let e of t){let t=this.langiumDocuments.deleteDocuments(e);for(let e of t)r.push(e.uri),this.cleanUpDeleted(e)}let i=(await Promise.all(e.map(e=>this.findChangedUris(e)))).flat();for(let e of i){let t=this.langiumDocuments.getDocument(e);t===void 0&&(t=this.langiumDocumentFactory.fromModel({$type:`INVALID`},e),t.state=X.Changed,this.langiumDocuments.addDocument(t)),this.resetToState(t,X.Changed)}let a=stream(i).concat(r).map(e=>e.toString()).toSet();this.langiumDocuments.all.filter(e=>!a.has(e.uri.toString())&&this.shouldRelink(e,a)).forEach(e=>this.resetToState(e,X.ComputedScopes)),await this.emitUpdate(i,r),await interruptAndCheck(n);let o=this.sortDocuments(this.langiumDocuments.all.filter(e=>e.state<X.Validated||!this.buildState.get(e.uri.toString())?.completed||this.resultsAreIncomplete(e,this.updateBuildOptions)).toArray());await this.buildDocuments(o,this.updateBuildOptions,n)}resultsAreIncomplete(e,t){return this.findMissingValidationCategories(e,t).length>=1}findMissingValidationCategories(e,t){let n=this.buildState.get(e.uri.toString()),r=this.serviceRegistry.getServices(e.uri).validation.ValidationRegistry.getAllValidationCategories(e),i=n?.result?.validationChecks?new Set(n?.result?.validationChecks):n?.completed?r:/* @__PURE__ */ new Set;return stream(t===void 0||t.validation===!0?r:typeof t.validation==`object`?t.validation.categories??r:[]).filter(e=>!i.has(e)).toArray()}async findChangedUris(e){if(this.langiumDocuments.getDocument(e)??this.textDocuments?.get(e))return[e];try{let t=await this.fileSystemProvider.stat(e);if(t.isDirectory)return await this.workspaceManager().searchFolder(e);if(this.workspaceManager().shouldIncludeEntry(t))return[e]}catch{}return[]}async emitUpdate(e,t){await Promise.all(this.updateListeners.map(n=>n(e,t)))}sortDocuments(e){let t=0,n=e.length-1;for(;t<n;){for(;t<e.length&&this.hasTextDocument(e[t]);)t++;for(;n>=0&&!this.hasTextDocument(e[n]);)n--;t<n&&([e[t],e[n]]=[e[n],e[t]])}return e}hasTextDocument(e){return!!this.textDocuments?.get(e.uri)}shouldRelink(e,t){return e.references.some(e=>e.error!==void 0)?!0:this.indexManager.isAffected(e,t)}onUpdate(e){return this.updateListeners.push(e),Ct.create(()=>{let t=this.updateListeners.indexOf(e);t>=0&&this.updateListeners.splice(t,1)})}resetToState(e,t){switch(t){case X.Changed:case X.Parsed:this.indexManager.removeContent(e.uri);case X.IndexedContent:e.localSymbols=void 0;case X.ComputedScopes:this.serviceRegistry.getServices(e.uri).references.Linker.unlink(e);case X.Linked:this.indexManager.removeReferences(e.uri);case X.IndexedReferences:e.diagnostics=void 0,this.buildState.delete(e.uri.toString());case X.Validated:}e.state>t&&(e.state=t)}cleanUpDeleted(e){this.buildState.delete(e.uri.toString()),this.indexManager.remove(e.uri),e.state=X.Changed}async buildDocuments(e,t,n){this.prepareBuild(e,t),await this.runCancelable(e,X.Parsed,n,e=>this.langiumDocumentFactory.update(e,n)),await this.runCancelable(e,X.IndexedContent,n,e=>this.indexManager.updateContent(e,n)),await this.runCancelable(e,X.ComputedScopes,n,async e=>{e.localSymbols=await this.serviceRegistry.getServices(e.uri).references.ScopeComputation.collectLocalSymbols(e,n)});let r=e.filter(e=>this.shouldLink(e));await this.runCancelable(r,X.Linked,n,e=>this.serviceRegistry.getServices(e.uri).references.Linker.link(e,n)),await this.runCancelable(r,X.IndexedReferences,n,e=>this.indexManager.updateReferences(e,n));let i=e.filter(e=>this.shouldValidate(e)?!0:(this.markAsCompleted(e),!1));await this.runCancelable(i,X.Validated,n,async e=>{await this.validate(e,n),this.markAsCompleted(e)})}markAsCompleted(e){let t=this.buildState.get(e.uri.toString());t&&(t.completed=!0)}prepareBuild(e,t){for(let n of e){let e=n.uri.toString(),r=this.buildState.get(e);(!r||r.completed)&&this.buildState.set(e,{completed:!1,options:t,result:r?.result})}}async runCancelable(e,t,n,r){for(let i of e)i.state<t&&(await interruptAndCheck(n),await r(i),i.state=t,await this.notifyDocumentPhase(i,t,n));let i=e.filter(e=>e.state===t);await this.notifyBuildPhase(i,t,n),this.currentState=t}onBuildPhase(e,t){return this.buildPhaseListeners.add(e,t),Ct.create(()=>{this.buildPhaseListeners.delete(e,t)})}onDocumentPhase(e,t){return this.documentPhaseListeners.add(e,t),Ct.create(()=>{this.documentPhaseListeners.delete(e,t)})}waitUntil(e,t,n){let r;return t&&`path`in t?r=t:n=t,n??=b.None,r?this.awaitDocumentState(e,r,n):this.awaitBuilderState(e,n)}awaitDocumentState(e,t,n){let r=this.langiumDocuments.getDocument(t);return r?r.state>=e?Promise.resolve(t):n.isCancellationRequested?Promise.reject(ft):this.currentState>=e&&e>r.state?Promise.reject(new ve(_e.RequestFailed,`Document state of ${t.toString()} is ${X[r.state]}, requiring ${X[e]}, but workspace state is already ${X[this.currentState]}. Returning undefined.`)):new Promise((r,i)=>{let a=this.onDocumentPhase(e,e=>{J.equals(e.uri,t)&&(a.dispose(),o.dispose(),r(e.uri))}),o=n.onCancellationRequested(()=>{a.dispose(),o.dispose(),i(ft)})}):Promise.reject(new ve(_e.ServerCancelled,`No document found for URI: ${t.toString()}`))}awaitBuilderState(e,t){return this.currentState>=e?Promise.resolve():t.isCancellationRequested?Promise.reject(ft):new Promise((n,r)=>{let i=this.onBuildPhase(e,()=>{i.dispose(),a.dispose(),n()}),a=t.onCancellationRequested(()=>{i.dispose(),a.dispose(),r(ft)})})}async notifyDocumentPhase(e,t,n){let r=this.documentPhaseListeners.get(t).slice();for(let t of r)try{await interruptAndCheck(n),await t(e,n)}catch(e){if(!isOperationCancelled(e))throw e}}async notifyBuildPhase(e,t,n){if(e.length===0)return;let r=this.buildPhaseListeners.get(t).slice();for(let t of r)await interruptAndCheck(n),await t(e,n)}shouldLink(e){return this.getBuildOptions(e).eagerLinking??!0}shouldValidate(e){return!!this.getBuildOptions(e).validation}async validate(e,t){let n=this.serviceRegistry.getServices(e.uri).validation.DocumentValidator,r=this.getBuildOptions(e),i=typeof r.validation==`object`?{...r.validation}:{};i.categories=this.findMissingValidationCategories(e,r);let a=await n.validateDocument(e,i,t);e.diagnostics?e.diagnostics.push(...a):e.diagnostics=a;let o=this.buildState.get(e.uri.toString());o&&(o.result??={},o.result.validationChecks?o.result.validationChecks=stream(o.result.validationChecks).concat(i.categories).distinct().toArray():o.result.validationChecks=[...i.categories])}getBuildOptions(e){return this.buildState.get(e.uri.toString())?.options??{}}},DefaultIndexManager=class{constructor(e){this.symbolIndex=/* @__PURE__ */ new Map,this.symbolByTypeIndex=new ContextCache,this.referenceIndex=/* @__PURE__ */ new Map,this.documents=e.workspace.LangiumDocuments,this.serviceRegistry=e.ServiceRegistry,this.astReflection=e.AstReflection}findAllReferences(e,t){let n=getDocument(e).uri,r=[];return this.referenceIndex.forEach(e=>{e.forEach(e=>{J.equals(e.targetUri,n)&&e.targetPath===t&&r.push(e)})}),stream(r)}allElements(e,t){let n=stream(this.symbolIndex.keys());return t&&(n=n.filter(e=>!t||t.has(e))),n.map(t=>this.getFileDescriptions(t,e)).flat()}getFileDescriptions(e,t){return t?this.symbolByTypeIndex.get(e,t,()=>(this.symbolIndex.get(e)??[]).filter(e=>this.astReflection.isSubtype(e.type,t))):this.symbolIndex.get(e)??[]}remove(e){this.removeContent(e),this.removeReferences(e)}removeContent(e){let t=e.toString();this.symbolIndex.delete(t),this.symbolByTypeIndex.clear(t)}removeReferences(e){let t=e.toString();this.referenceIndex.delete(t)}async updateContent(e,t=b.None){let n=await this.serviceRegistry.getServices(e.uri).references.ScopeComputation.collectExportedSymbols(e,t),r=e.uri.toString();this.symbolIndex.set(r,n),this.symbolByTypeIndex.clear(r)}async updateReferences(e,t=b.None){let n=await this.serviceRegistry.getServices(e.uri).workspace.ReferenceDescriptionProvider.createDescriptions(e,t);this.referenceIndex.set(e.uri.toString(),n)}isAffected(e,t){let n=this.referenceIndex.get(e.uri.toString());return n?n.some(e=>!e.local&&t.has(e.targetUri.toString())):!1}},Dt;(function(e){e[e.Normal=0]=`Normal`,e[e.Immediate=1]=`Immediate`})(Dt||={});var DefaultWorkspaceLock=class{constructor(){this.previousTokenSource=new pe,this.writeQueue=[],this.readQueue=[],this.immediateReads=[],this.done=!0}write(e){this.cancelWrite();let t=startCancelableOperation();return this.previousTokenSource=t,this.enqueue(this.writeQueue,e,t.token)}read(e,t=Dt.Normal){if(t===Dt.Immediate){let t=Promise.resolve().then(()=>e());this.immediateReads.push(t);let remove=()=>{this.immediateReads.splice(this.immediateReads.indexOf(t),1)};return t.then(remove,remove),t}return this.enqueue(this.readQueue,e)}enqueue(e,t,n=b.None){let r=new Deferred,i={action:t,deferred:r,cancellationToken:n};return e.push(i),this.performNextOperation(),r.promise}async performNextOperation(){if(!this.done)return;let e=[];if(this.writeQueue.length>0)for(e.push(this.writeQueue.shift()),this.done=!1;this.immediateReads.length>0;)await Promise.allSettled(this.immediateReads.slice());else if(this.readQueue.length>0)e.push(...this.readQueue.splice(0,this.readQueue.length)),this.done=!1;else return;await Promise.all(e.map(async({action:e,deferred:t,cancellationToken:n})=>{try{let r=await Promise.resolve().then(()=>e(n));t.resolve(r)}catch(e){isOperationCancelled(e)?t.resolve(void 0):t.reject(e)}})),this.done=!0,this.performNextOperation()}cancelWrite(){this.previousTokenSource.cancel()}},DefaultWorkspaceManager=class{constructor(e){this.initialBuildOptions={},this._ready=new Deferred,this.serviceRegistry=e.ServiceRegistry,this.langiumDocuments=e.workspace.LangiumDocuments,this.documentBuilder=e.workspace.DocumentBuilder,this.fileSystemProvider=e.workspace.FileSystemProvider,this.mutex=e.workspace.WorkspaceLock}get ready(){return this._ready.promise}get workspaceFolders(){return this.folders}initialize(e){this.folders=e.workspaceFolders??void 0}initialized(e){return this.mutex.write(e=>this.initializeWorkspace(this.folders??[],e))}async initializeWorkspace(e,t=b.None){let n=await this.performStartup(e);await interruptAndCheck(t),await this.documentBuilder.build(n,this.initialBuildOptions,t)}async performStartup(e){let t=[],collector=e=>{t.push(e),this.langiumDocuments.hasDocument(e.uri)||this.langiumDocuments.addDocument(e)};await this.loadAdditionalDocuments(e,collector);let n=[];await Promise.all(e.map(e=>this.getRootFolder(e)).map(async e=>this.traverseFolder(e,n)));let r=stream(n).distinct(e=>e.toString()).filter(e=>!this.langiumDocuments.hasDocument(e));return await this.loadWorkspaceDocuments(r,collector),this._ready.resolve(),t}async loadWorkspaceDocuments(e,t){await Promise.all(e.map(async e=>{t(await this.langiumDocuments.getOrCreateDocument(e))}))}loadAdditionalDocuments(e,t){return Promise.resolve()}getRootFolder(e){return y.parse(e.uri)}async traverseFolder(e,t){try{let n=await this.fileSystemProvider.readDirectory(e);await Promise.all(n.map(async e=>{this.shouldIncludeEntry(e)&&(e.isDirectory?await this.traverseFolder(e.uri,t):e.isFile&&t.push(e.uri))}))}catch(t){console.error(`Failure to read directory content of `+e.toString(!0),t)}}async searchFolder(e){let t=[];return await this.traverseFolder(e,t),t}shouldIncludeEntry(e){let t=J.basename(e.uri);return t.startsWith(`.`)?!1:e.isDirectory?t!==`node_modules`&&t!==`out`:e.isFile?this.serviceRegistry.hasServices(e.uri):!1}};function diagnosticData(e){return{code:e}}var Ot;(function(e){e.defaults=[`fast`,`slow`,`built-in`],e.all=e.defaults})(Ot||={});var ValidationRegistry=class{constructor(e){this.entries=new MultiMap,this.knownCategories=new Set(Ot.defaults),this.entriesBefore=[],this.entriesAfter=[],this.reflection=e.shared.AstReflection}register(e,t=this,n=`fast`){if(n===`built-in`)throw Error(`The 'built-in' category is reserved for lexer, parser, and linker errors.`);this.knownCategories.add(n);for(let[r,i]of Object.entries(e)){let e=i;if(Array.isArray(e))for(let i of e){let e={check:this.wrapValidationException(i,t),category:n};this.addEntry(r,e)}else if(typeof e==`function`){let i={check:this.wrapValidationException(e,t),category:n};this.addEntry(r,i)}else assertUnreachable(e)}}wrapValidationException(e,t){return async(n,r,i)=>{await this.handleException(()=>e.call(t,n,r,i),`An error occurred during validation`,r,n)}}async handleException(e,t,n,r){try{await e()}catch(e){if(isOperationCancelled(e))throw e;console.error(`${t}:`,e),e instanceof Error&&e.stack&&console.error(e.stack),n(`error`,`${t}: ${e instanceof Error?e.message:String(e)}`,{node:r})}}addEntry(e,t){if(e===`AstNode`)this.entries.add(`AstNode`,t);else for(let n of this.reflection.getAllSubTypes(e))this.entries.add(n,t)}getChecks(e,t){let n=stream(this.entries.get(e)).concat(this.entries.get(`AstNode`));return t&&(n=n.filter(e=>t.includes(e.category))),n.map(e=>e.check)}registerBeforeDocument(e,t=this){this.entriesBefore.push(this.wrapPreparationException(e,`An error occurred during set-up of the validation`,t))}registerAfterDocument(e,t=this){this.entriesAfter.push(this.wrapPreparationException(e,`An error occurred during tear-down of the validation`,t))}wrapPreparationException(e,t,n){return async(r,i,a,o)=>{await this.handleException(()=>e.call(n,r,i,a,o),t,i,r)}}get checksBefore(){return this.entriesBefore}get checksAfter(){return this.entriesAfter}getAllValidationCategories(e){return this.knownCategories}};const kt=Object.freeze({validateNode:!0,validateChildren:!0});var DefaultDocumentValidator=class{constructor(e){this.validationRegistry=e.validation.ValidationRegistry,this.metadata=e.LanguageMetaData,this.profiler=e.shared.profilers.LangiumProfiler,this.languageId=e.LanguageMetaData.languageId}async validateDocument(e,t={},n=b.None){let r=e.parseResult,i=[];if(await interruptAndCheck(n),(!t.categories||t.categories.includes(`built-in`))&&(this.processLexingErrors(r,i,t),t.stopAfterLexingErrors&&i.some(e=>e.data?.code===Z.LexingError)||(this.processParsingErrors(r,i,t),t.stopAfterParsingErrors&&i.some(e=>e.data?.code===Z.ParsingError))||(this.processLinkingErrors(e,i,t),t.stopAfterLinkingErrors&&i.some(e=>e.data?.code===Z.LinkingError))))return i;try{i.push(...await this.validateAst(r.value,t,n))}catch(e){if(isOperationCancelled(e))throw e;console.error(`An error occurred during validation:`,e)}return await interruptAndCheck(n),i}processLexingErrors(e,t,n){let r=[...e.lexerErrors,...e.lexerReport?.diagnostics??[]];for(let e of r){let n=e.severity??`error`,r={severity:toDiagnosticSeverity(n),range:{start:{line:e.line-1,character:e.column-1},end:{line:e.line-1,character:e.column+e.length-1}},message:e.message,data:toDiagnosticData(n),source:this.getSource()};t.push(r)}}processParsingErrors(e,t,n){for(let n of e.parserErrors){let e;if(isValidTokenRange(n.token))e=tokenToRange(n.token);else if(`previousToken`in n){let t=n.previousToken;if(isValidTokenRange(t)){let n={line:t.endLine-1,character:t.endColumn};e={start:n,end:n}}else{let t={line:0,character:0};e={start:t,end:t}}}if(e){let r={severity:toDiagnosticSeverity(`error`),range:e,message:n.message,data:diagnosticData(Z.ParsingError),source:this.getSource()};t.push(r)}}}processLinkingErrors(e,t,n){for(let n of e.references){let e=n.error;if(e){let r={node:e.info.container,range:n.$refNode?.range,property:e.info.property,index:e.info.index,data:{code:Z.LinkingError,containerType:e.info.container.$type,property:e.info.property,refText:e.info.reference.$refText}};t.push(this.toDiagnostic(`error`,e.message,r))}}}async validateAst(e,t,n=b.None){let r=[],acceptor=(e,t,n)=>{r.push(this.toDiagnostic(e,t,n))};return await this.validateAstBefore(e,t,acceptor,n),await this.validateAstNodes(e,t,acceptor,n),await this.validateAstAfter(e,t,acceptor,n),r}async validateAstBefore(e,t,n,r=b.None){let i=this.validationRegistry.checksBefore;for(let a of i)await interruptAndCheck(r),await a(e,n,t.categories??[],r)}async validateAstNodes(e,t,n,r=b.None){if(this.profiler?.isActive(`validating`)){let i=this.profiler.createTask(`validating`,this.languageId);i.start();try{let a=streamAst(e).iterator();for(let e of a){i.startSubTask(e.$type);let o=this.validateSingleNodeOptions(e,t);if(o.validateNode)try{let i=this.validationRegistry.getChecks(e.$type,t.categories);for(let t of i)await t(e,n,r)}finally{i.stopSubTask(e.$type)}o.validateChildren||a.prune()}}finally{i.stop()}}else{let i=streamAst(e).iterator();for(let e of i){await interruptAndCheck(r);let a=this.validateSingleNodeOptions(e,t);if(a.validateNode){let i=this.validationRegistry.getChecks(e.$type,t.categories);for(let t of i)await t(e,n,r)}a.validateChildren||i.prune()}}}validateSingleNodeOptions(e,t){return kt}async validateAstAfter(e,t,n,r=b.None){let i=this.validationRegistry.checksAfter;for(let a of i)await interruptAndCheck(r),await a(e,n,t.categories??[],r)}toDiagnostic(e,t,n){return{message:t,range:getDiagnosticRange(n),severity:toDiagnosticSeverity(e),code:n.code,codeDescription:n.codeDescription,tags:n.tags,relatedInformation:n.relatedInformation,data:n.data,source:this.getSource()}}getSource(){return this.metadata.languageId}};function getDiagnosticRange(e){if(e.range)return e.range;let t;return typeof e.property==`string`?t=findNodeForProperty(e.node.$cstNode,e.property,e.index):typeof e.keyword==`string`&&(t=findNodeForKeyword(e.node.$cstNode,e.keyword,e.index)),t??=e.node.$cstNode,t?t.range:{start:{line:0,character:0},end:{line:0,character:0}}}function toDiagnosticSeverity(e){switch(e){case`error`:return 1;case`warning`:return 2;case`info`:return 3;case`hint`:return 4;default:throw Error(`Invalid diagnostic severity: `+e)}}function toDiagnosticData(e){switch(e){case`error`:return diagnosticData(Z.LexingError);case`warning`:return diagnosticData(Z.LexingWarning);case`info`:return diagnosticData(Z.LexingInfo);case`hint`:return diagnosticData(Z.LexingHint);default:throw Error(`Invalid diagnostic severity: `+e)}}var Z;(function(e){e.LexingError=`lexing-error`,e.LexingWarning=`lexing-warning`,e.LexingInfo=`lexing-info`,e.LexingHint=`lexing-hint`,e.ParsingError=`parsing-error`,e.LinkingError=`linking-error`})(Z||={});function createDefaultCoreModule(e){return{documentation:{CommentProvider:e=>new DefaultCommentProvider(e),DocumentationProvider:e=>new JSDocDocumentationProvider(e)},parser:{AsyncParser:e=>new DefaultAsyncParser(e),GrammarConfig:e=>createGrammarConfig(e),LangiumParser:e=>createLangiumParser(e),CompletionParser:e=>createCompletionParser(e),ValueConverter:()=>new DefaultValueConverter,TokenBuilder:()=>new DefaultTokenBuilder,Lexer:e=>new DefaultLexer(e),ParserErrorMessageProvider:()=>new LangiumParserErrorMessageProvider,LexerErrorMessageProvider:()=>new DefaultLexerErrorMessageProvider},workspace:{AstNodeLocator:()=>new DefaultAstNodeLocator,AstNodeDescriptionProvider:e=>new DefaultAstNodeDescriptionProvider(e),ReferenceDescriptionProvider:e=>new DefaultReferenceDescriptionProvider(e)},references:{Linker:e=>new DefaultLinker(e),NameProvider:()=>new DefaultNameProvider,ScopeProvider:e=>new DefaultScopeProvider(e),ScopeComputation:e=>new DefaultScopeComputation(e),References:e=>new DefaultReferences(e)},serializer:{Hydrator:e=>new DefaultHydrator(e),JsonSerializer:e=>new DefaultJsonSerializer(e)},validation:{DocumentValidator:e=>new DefaultDocumentValidator(e),ValidationRegistry:e=>new ValidationRegistry(e)},shared:()=>e.shared}}function createDefaultSharedCoreModule(e){return{ServiceRegistry:e=>new DefaultServiceRegistry(e),workspace:{LangiumDocuments:e=>new DefaultLangiumDocuments(e),LangiumDocumentFactory:e=>new DefaultLangiumDocumentFactory(e),DocumentBuilder:e=>new DefaultDocumentBuilder(e),IndexManager:e=>new DefaultIndexManager(e),WorkspaceManager:e=>new DefaultWorkspaceManager(e),FileSystemProvider:t=>e.fileSystemProvider(t),WorkspaceLock:()=>new DefaultWorkspaceLock,ConfigurationProvider:e=>new DefaultConfigurationProvider(e)},profilers:{}}}var DefaultDocumentHighlightProvider=class{constructor(e){this.references=e.references.References,this.nameProvider=e.references.NameProvider,this.grammarConfig=e.parser.GrammarConfig}getDocumentHighlight(e,t,n){let r=e.parseResult.value.$cstNode;if(!r)return;let i=findDeclarationNodeAtOffset(r,e.textDocument.offsetAt(t.position),this.grammarConfig.nameRegexp);if(!i)return;let a=this.references.findDeclarations(i),o=[];for(let t of a){let n=J.equals(getDocument(t).uri,e.uri),r={documentUri:e.uri,includeDeclaration:n},i=this.references.findReferences(t,r);o.push(...i.map(e=>this.createDocumentHighlight(e)).toArray())}return o}createDocumentHighlight(e){return te.create(e.segment.range)}},DefaultDocumentSymbolProvider=class{constructor(e){this.nameProvider=e.references.NameProvider,this.nodeKindProvider=e.shared.lsp.NodeKindProvider}getSymbols(e,t,n){return this.getSymbol(e,e.parseResult.value)}getSymbol(e,t){let n=this.nameProvider.getNameNode(t);if(n&&t.$cstNode){let r=this.nameProvider.getName(t);return[this.createSymbol(e,t,t.$cstNode,n,r)]}return this.getChildSymbols(e,t)||[]}createSymbol(e,t,n,r,i){return{kind:this.nodeKindProvider.getSymbolKind(t),name:i||r.text,range:n.range,selectionRange:r.range,children:this.getChildSymbols(e,t)}}getChildSymbols(e,t){let n=[];for(let r of streamContents(t)){let t=this.getSymbol(e,r);n.push(...t)}if(n.length>0)return n}},DefaultDocumentUpdateHandler=class{constructor(e){this.onWatchedFilesChangeEmitter=new ge,this.workspaceManager=e.workspace.WorkspaceManager,this.documentBuilder=e.workspace.DocumentBuilder,this.workspaceLock=e.workspace.WorkspaceLock,this.serviceRegistry=e.ServiceRegistry;let t=!1;e.lsp.LanguageServer.onInitialize(e=>{t=!!e.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration}),e.lsp.LanguageServer.onInitialized(n=>{t&&this.registerFileWatcher(e)})}registerFileWatcher(e){let t=this.getWatchers();if(t.length>0){let n=e.lsp.Connection,r={watchers:t};n?.client.register(ee.type,r)}}getWatchers(){return[{globPattern:`**/*`}]}fireDocumentUpdate(e,t){this.workspaceManager.ready.then(()=>{this.workspaceLock.write(n=>this.documentBuilder.update(e,t,n))}).catch(e=>{console.error(`Workspace initialization failed. Could not perform document update.`,e)})}didChangeContent(e){this.fireDocumentUpdate([y.parse(e.document.uri)],[])}didChangeWatchedFiles(e){this.onWatchedFilesChangeEmitter.fire(e);let t=stream(e.changes).filter(e=>e.type!==ne.Deleted).distinct(e=>e.uri).map(e=>y.parse(e.uri)).toArray(),n=stream(e.changes).filter(e=>e.type===ne.Deleted).distinct(e=>e.uri).map(e=>y.parse(e.uri)).toArray();this.fireDocumentUpdate(t,n)}get onWatchedFilesChange(){return this.onWatchedFilesChangeEmitter.event}},DefaultFoldingRangeProvider=class{constructor(e){this.commentNames=e.parser.GrammarConfig.multilineCommentRules}getFoldingRanges(e,t,n){let r=[],acceptor=e=>r.push(e);return this.collectFolding(e,acceptor),r}collectFolding(e,t){let n=e.parseResult?.value;if(n){if(this.shouldProcessContent(n)){let r=streamAllContents(n).iterator(),i;do if(i=r.next(),!i.done){let n=i.value;this.shouldProcess(n)&&this.collectObjectFolding(e,n,t),this.shouldProcessContent(n)||r.prune()}while(!i.done)}this.collectCommentFolding(e,n,t)}}shouldProcess(e){return!0}shouldProcessContent(e){return!0}collectObjectFolding(e,t,n){let r=t.$cstNode;if(r){let t=this.toFoldingRange(e,r);t&&n(t)}}collectCommentFolding(e,t,n){let r=t.$cstNode;if(r){for(let t of flattenCst(r))if(this.commentNames.includes(t.tokenType.name)){let r=this.toFoldingRange(e,t,ie.Comment);r&&n(r)}}}toFoldingRange(e,t,n){let r=t.range,i=r.start,a=r.end;if(!(a.line-i.line<2))return this.includeLastFoldingLine(t,n)||(a=e.textDocument.positionAt(e.textDocument.offsetAt({line:a.line,character:0})-1)),re.create(i.line,a.line,i.character,a.character,n)}includeLastFoldingLine(e,t){if(t===ie.Comment)return!1;let n=e.root.fullText.charAt(e.end-1);return n!==`}`&&n!==`)`&&n!==`]`}},DefaultFuzzyMatcher=class{match(e,t){if(e.length===0)return!0;let n=!1,r,i=0,a=t.length;for(let o=0;o<a;o++){let a=t.charCodeAt(o),s=e.charCodeAt(i);if((a===s||this.toUpperCharCode(a)===this.toUpperCharCode(s))&&(n||=r===void 0||this.isWordTransition(r,a),n&&i++,i===e.length))return!0;r=a}return!1}isWordTransition(e,t){return At<=e&&e<=jt&&Mt<=t&&t<=Nt||e===Pt&&t!==Pt}toUpperCharCode(e){return At<=e&&e<=jt?e-32:e}};const At=97,jt=122,Mt=65,Nt=90,Pt=95;var AstNodeHoverProvider=class{constructor(e){this.references=e.references.References,this.grammarConfig=e.parser.GrammarConfig}async getHoverContent(e,t){let n=e.parseResult?.value?.$cstNode;if(n){let r=e.textDocument.offsetAt(t.position),i=findDeclarationNodeAtOffset(n,r,this.grammarConfig.nameRegexp);if(i&&i.offset+i.length>r){let e=[],t=this.references.findDeclarations(i);for(let n of t){let t=await this.getAstNodeHoverContent(n);typeof t==`string`&&e.push(t)}if(e.length>0)return{contents:{kind:`markdown`,value:e.join(` `)}};if(isKeyword(i.grammarSource))return this.getKeywordHoverContent(i.grammarSource)}}}getKeywordHoverContent(e){let t=isAstNodeWithComment(e)?e.$comment:void 0;if(t||=findCommentNode(e.$cstNode,[`ML_COMMENT`])?.text,t&&isJSDoc(t)){let e=parseJSDoc(t).toMarkdown();if(e)return{contents:{kind:`markdown`,value:e}}}}},MultilineCommentHoverProvider=class extends AstNodeHoverProvider{constructor(e){super(e),this.documentationProvider=e.documentation.DocumentationProvider}getAstNodeHoverContent(e){let t=this.documentationProvider.getDocumentation(e);if(t)return t}};const Ft={[v.class]:0,[v.comment]:1,[v.enum]:2,[v.enumMember]:3,[v.event]:4,[v.function]:5,[v.interface]:6,[v.keyword]:7,[v.macro]:8,[v.method]:9,[v.modifier]:10,[v.namespace]:11,[v.number]:12,[v.operator]:13,[v.parameter]:14,[v.property]:15,[v.regexp]:16,[v.string]:17,[v.struct]:18,[v.type]:19,[v.typeParameter]:20,[v.variable]:21,[v.decorator]:22},It={[_.abstract]:1,[_.async]:2,[_.declaration]:4,[_.defaultLibrary]:8,[_.definition]:16,[_.deprecated]:32,[_.documentation]:64,[_.modification]:128,[_.readonly]:256,[_.static]:512};Object.keys(Ft),Object.keys(It);function mergeSemanticTokenProviderOptions(e){let t=[],n=[],r=!0,i=!0,a=!0;for(let o of e)o&&(o.legend.tokenTypes.forEach((e,n)=>{let r=t[n];if(r&&r!==e)throw Error(`Cannot merge '${r}' and '${e}' token types. They use the same index ${n}.`);t[n]=e}),o.legend.tokenModifiers.forEach((e,t)=>{let r=n[t];if(r&&r!==e)throw Error(`Cannot merge '${r}' and '${e}' token modifier. They use the same index ${t}.`);n[t]=e}),o.full?typeof o.full==`object`&&!o.full.delta&&(i=!1):r=!1,o.range||(a=!1));return{legend:{tokenTypes:t,tokenModifiers:n},full:r&&{delta:i},range:a}}var SemanticTokensBuilder$1=class extends ce{static{e(this,`SemanticTokensBuilder`)}constructor(){super(...arguments),this._tokens=[]}push(e,t,n,r,i){this._tokens.push({line:e,char:t,length:n,tokenType:r,tokenModifiers:i})}build(){return this.applyTokens(),super.build()}buildEdits(){return this.applyTokens(),super.buildEdits()}flush(){this.previousResult(this.id)}applyTokens(){for(let e of this._tokens.sort(this.compareTokens))super.push(e.line,e.char,e.length,e.tokenType,e.tokenModifiers);this._tokens=[]}compareTokens(e,t){return e.line-t.line||e.char-t.char}},AbstractSemanticTokenProvider=class{constructor(e){this.tokensBuilders=/* @__PURE__ */ new Map,e.shared.workspace.TextDocuments.onDidClose(e=>{this.tokensBuilders.delete(e.document.uri)}),e.shared.lsp.LanguageServer.onInitialize(e=>{this.initialize(e.capabilities.textDocument?.semanticTokens)})}initialize(e){this.clientCapabilities=e}get tokenTypes(){return Ft}get tokenModifiers(){return It}get semanticTokensOptions(){return{legend:{tokenTypes:Object.keys(this.tokenTypes),tokenModifiers:Object.keys(this.tokenModifiers)},full:{delta:!1},range:!0}}async semanticHighlight(e,t,n=b.None){return this.currentRange=void 0,this.currentDocument=e,this.currentTokensBuilder=this.getDocumentTokensBuilder(e),this.currentTokensBuilder.flush(),await this.computeHighlighting(e,this.createAcceptor(),n),this.currentTokensBuilder.build()}async semanticHighlightRange(e,t,n=b.None){return this.currentRange=t.range,this.currentDocument=e,this.currentTokensBuilder=this.getDocumentTokensBuilder(e),this.currentTokensBuilder.flush(),await this.computeHighlighting(e,this.createAcceptor(),n),this.currentTokensBuilder.build()}async semanticHighlightDelta(e,t,n=b.None){return this.currentRange=void 0,this.currentDocument=e,this.currentTokensBuilder=this.getDocumentTokensBuilder(e),this.currentTokensBuilder.previousResult(t.previousResultId),await this.computeHighlighting(e,this.createAcceptor(),n),this.currentTokensBuilder.buildEdits()}createAcceptor(){let acceptor=e=>{`line`in e?this.highlightToken({range:{start:{line:e.line,character:e.char},end:{line:e.line,character:e.char+e.length}},type:e.type,modifier:e.modifier}):`range`in e?this.highlightToken(e):`keyword`in e?this.highlightKeyword(e):`property`in e?this.highlightProperty(e):this.highlightNode({node:e.cst,type:e.type,modifier:e.modifier})};return acceptor}getDocumentTokensBuilder(e){let t=this.tokensBuilders.get(e.uri.toString());if(t)return t;let n=new SemanticTokensBuilder$1;return this.tokensBuilders.set(e.uri.toString(),n),n}async computeHighlighting(e,t,n){let r=e.parseResult.value,i=streamAst(r,{range:this.currentRange}).iterator(),a;do if(a=i.next(),!a.done){await interruptAndCheck(n);let e=a.value;this.highlightElement(e,t)===`prune`&&i.prune()}while(!a.done)}highlightToken(e){let{range:t,type:n}=e,r=e.modifier;if(this.currentRange&&!inRange(t,this.currentRange)||!this.currentDocument||!this.currentTokensBuilder)return;let i=this.tokenTypes[n],a=0;if(r!==void 0){typeof r==`string`&&(r=[r]);for(let e of r){let t=this.tokenModifiers[e];a|=t}}let o=t.start.line,s=t.end.line;if(o===s){let e=t.start.character,n=t.end.character-e;this.currentTokensBuilder.push(o,e,n,i,a)}else if(this.clientCapabilities?.multilineTokenSupport){let e=t.start.character,n=this.currentDocument.textDocument.offsetAt(t.start),r=this.currentDocument.textDocument.offsetAt(t.end);this.currentTokensBuilder.push(o,e,r-n,i,a)}else{let e=t.start,n=this.currentDocument.textDocument.offsetAt({line:o+1,character:0});this.currentTokensBuilder.push(e.line,e.character,n-e.character-1,i,a);for(let e=o+1;e<s;e++){let t=n;n=this.currentDocument.textDocument.offsetAt({line:e+1,character:0}),this.currentTokensBuilder.push(e,0,n-t-1,i,a)}this.currentTokensBuilder.push(s,0,t.end.character,i,a)}}highlightProperty(e){let t=[];if(typeof e.index==`number`){let n=findNodeForProperty(e.node.$cstNode,e.property,e.index);n&&t.push(n)}else t.push(...findNodesForProperty(e.node.$cstNode,e.property));let{type:n,modifier:r}=e;for(let e of t)this.highlightNode({node:e,type:n,modifier:r})}highlightKeyword(e){let{node:t,keyword:n,type:r,index:i,modifier:a}=e,o=[];if(typeof i==`number`){let e=findNodeForKeyword(t.$cstNode,n,i);e&&o.push(e)}else o.push(...findNodesForKeyword(t.$cstNode,n));for(let e of o)this.highlightNode({node:e,type:r,modifier:a})}highlightNode(e){let{node:t,type:n,modifier:r}=e,i=t.range;this.highlightToken({range:i,type:n,modifier:r})}},Lt;(function(e){function decode(e,t,n){let r=/* @__PURE__ */ new Map;Object.entries(t).forEach(([e,t])=>r.set(t,e));let i=0,a=0;return sliceIntoChunks(e.data,5).map(e=>{i+=e[0],e[0]!==0&&(a=0),a+=e[1];let t=e[2];return{offset:n.textDocument.offsetAt({line:i,character:a}),tokenType:r.get(e[3]),tokenModifiers:e[4],text:n.textDocument.getText({start:{line:i,character:a},end:{line:i,character:a+t}})}})}e.decode=decode;function sliceIntoChunks(e,t){let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t);n.push(i)}return n}})(Lt||={});function mergeSignatureHelpOptions(e){let t=[],n=[];e.forEach(e=>{e?.triggerCharacters&&t.push(...e.triggerCharacters),e?.retriggerCharacters&&n.push(...e.retriggerCharacters)});let r={triggerCharacters:t.length>0?Array.from(new Set(t)).sort():void 0,retriggerCharacters:n.length>0?Array.from(new Set(n)).sort():void 0};return r.triggerCharacters?r:void 0}var DefaultLanguageServer=class{constructor(e){this.onInitializeEmitter=new he,this.onInitializedEmitter=new he,this.services=e}get onInitialize(){return this.onInitializeEmitter.event}get onInitialized(){return this.onInitializedEmitter.event}async initialize(e){return this.eagerLoadServices(),this.fireInitializeOnDefaultServices(e),this.onInitializeEmitter.fire(e),this.onInitializeEmitter.dispose(),this.buildInitializeResult(e)}eagerLoadServices(){eagerLoad(this.services),this.services.ServiceRegistry.all.forEach(e=>eagerLoad(e))}hasService(e){return this.services.ServiceRegistry.all.some(t=>e(t)!==void 0)}buildInitializeResult(e){let t=this.services.lsp.DocumentUpdateHandler,n=this.services.lsp.FileOperationHandler?.fileOperationOptions,r=this.services.ServiceRegistry.all,i=this.hasService(e=>e.lsp?.Formatter),a=r.map(e=>e.lsp?.Formatter?.formatOnTypeOptions).find(e=>!!e),o=this.hasService(e=>e.lsp?.CodeActionProvider),s=this.hasService(e=>e.lsp?.SemanticTokenProvider),c=mergeSemanticTokenProviderOptions(r.map(e=>e.lsp?.SemanticTokenProvider?.semanticTokensOptions)),l=this.services.lsp?.ExecuteCommandHandler?.commands,u=this.hasService(e=>e.lsp?.DocumentLinkProvider),d=mergeSignatureHelpOptions(r.map(e=>e.lsp?.SignatureHelp?.signatureHelpOptions)),f=this.hasService(e=>e.lsp?.TypeProvider),p=this.hasService(e=>e.lsp?.ImplementationProvider),m=this.hasService(e=>e.lsp?.CompletionProvider),ee=mergeCompletionProviderOptions(r.map(e=>e.lsp?.CompletionProvider?.completionOptions)),h=this.hasService(e=>e.lsp?.ReferencesProvider),te=this.hasService(e=>e.lsp?.DocumentSymbolProvider),g=this.hasService(e=>e.lsp?.DefinitionProvider),ne=this.hasService(e=>e.lsp?.DocumentHighlightProvider),re=this.hasService(e=>e.lsp?.FoldingRangeProvider),ie=this.hasService(e=>e.lsp?.HoverProvider),ae=this.hasService(e=>e.lsp?.RenameProvider),oe=this.hasService(e=>e.lsp?.CallHierarchyProvider),se=this.hasService(e=>e.lsp?.TypeHierarchyProvider),_=this.hasService(e=>e.lsp?.CodeLensProvider),v=this.hasService(e=>e.lsp?.DeclarationProvider),ce=this.hasService(e=>e.lsp?.InlayHintProvider),le=this.services.lsp?.WorkspaceSymbolProvider,ue=this.services.lsp?.TextDocumentContentProvider?.schemes;return{capabilities:{workspace:{workspaceFolders:{supported:!0},fileOperations:n,textDocumentContent:ue?{schemes:ue}:void 0},executeCommandProvider:l&&{commands:l},textDocumentSync:{change:ye.Incremental,openClose:!0,save:!!t.didSaveDocument,willSave:!!t.willSaveDocument,willSaveWaitUntil:!!t.willSaveDocumentWaitUntil},completionProvider:m?ee:void 0,referencesProvider:h,documentSymbolProvider:te,definitionProvider:g,typeDefinitionProvider:f,documentHighlightProvider:ne,codeActionProvider:o,documentFormattingProvider:i,documentRangeFormattingProvider:i,documentOnTypeFormattingProvider:a,foldingRangeProvider:re,hoverProvider:ie,renameProvider:ae?{prepareProvider:!0}:void 0,semanticTokensProvider:s?c:void 0,signatureHelpProvider:d,implementationProvider:p,callHierarchyProvider:oe?{}:void 0,typeHierarchyProvider:se?{}:void 0,documentLinkProvider:u?{resolveProvider:!1}:void 0,codeLensProvider:_?{resolveProvider:!1}:void 0,declarationProvider:v,inlayHintProvider:ce?{resolveProvider:!1}:void 0,workspaceSymbolProvider:le?{resolveProvider:!!le.resolveSymbol}:void 0}}}initialized(e){this.fireInitializedOnDefaultServices(e),this.onInitializedEmitter.fire(e),this.onInitializedEmitter.dispose()}fireInitializeOnDefaultServices(e){this.services.workspace.ConfigurationProvider.initialize(e),this.services.workspace.WorkspaceManager.initialize(e)}fireInitializedOnDefaultServices(e){let t=this.services.lsp.Connection,n=t?{...e,register:e=>t.client.register(me.type,e),fetchConfiguration:e=>t.workspace.getConfiguration(e)}:e;this.services.workspace.ConfigurationProvider.initialized(n).catch(e=>console.error(`Error in ConfigurationProvider initialization:`,e)),this.services.workspace.WorkspaceManager.initialized(e).catch(e=>console.error(`Error in WorkspaceManager initialization:`,e))}},Rt;(function(e){e.Parsed=Object.freeze({type:`workspace`,state:X.Parsed}),e.IndexedContent=Object.freeze({type:`workspace`,state:X.IndexedContent}),e.ComputedScopes=Object.freeze({type:`workspace`,state:X.ComputedScopes}),e.Linked=Object.freeze({type:`workspace`,state:X.Linked}),e.IndexedReferences=Object.freeze({type:`workspace`,state:X.IndexedReferences}),e.Validated=Object.freeze({type:`workspace`,state:X.Validated})})(Rt||={});var DefaultNodeKindProvider=class{getSymbolKind(e){return le.Field}getCompletionItemKind(e){return p.Reference}},DefaultReferencesProvider=class{constructor(e){this.nameProvider=e.references.NameProvider,this.references=e.references.References,this.grammarConfig=e.parser.GrammarConfig}findReferences(e,t,n){let r=e.parseResult.value.$cstNode;if(!r)return[];let i=findDeclarationNodeAtOffset(r,e.textDocument.offsetAt(t.position),this.grammarConfig.nameRegexp);return i?this.getReferences(i,t,e):[]}getReferences(e,t,n){let r=[],i=this.references.findDeclarations(e);for(let e of i){let n={includeDeclaration:t.context.includeDeclaration};this.references.findReferences(e,n).forEach(e=>{r.push(ae.create(e.sourceUri.toString(),e.segment.range))})}return r}},DefaultRenameProvider=class{constructor(e){this.references=e.references.References,this.nameProvider=e.references.NameProvider,this.grammarConfig=e.parser.GrammarConfig}async rename(e,t,n){let r={},i=e.parseResult.value.$cstNode;if(!i)return;let a=findDeclarationNodeAtOffset(i,e.textDocument.offsetAt(t.position),this.grammarConfig.nameRegexp);if(!a)return;let o=this.references.findDeclarations(a);if(o.length===0)return;let s=o[0],c=this.references.findReferences(s,{onlyLocal:!1,includeDeclaration:!0});for(let e of c){let n=xe.replace(e.segment.range,t.newName),i=e.sourceUri.toString();r[i]?r[i].push(n):r[i]=[n]}return{changes:r}}prepareRename(e,t,n){return this.renameNodeRange(e,t.position)}renameNodeRange(e,t){let n=e.parseResult.value.$cstNode,r=e.textDocument.offsetAt(t);if(n){let e=findDeclarationNodeAtOffset(n,r,this.grammarConfig.nameRegexp);if(!e)return;if(this.references.findDeclarations(e).length>0||this.isNameNode(e))return e.range}}isNameNode(e){return e?.astNode&&isNamed(e.astNode)&&e===this.nameProvider.getNameNode(e.astNode)}},DefaultWorkspaceSymbolProvider=class{constructor(e){this.indexManager=e.workspace.IndexManager,this.nodeKindProvider=e.lsp.NodeKindProvider,this.fuzzyMatcher=e.lsp.FuzzyMatcher}async getSymbols(e,t=b.None){let n=[],r=e.query.toLowerCase();for(let e of this.indexManager.allElements())if(await interruptAndCheck(t),this.fuzzyMatcher.match(r,e.name)){let t=this.getWorkspaceSymbol(e);t&&n.push(t)}return n}getWorkspaceSymbol(e){let t=e.nameSegment;if(t)return{kind:this.nodeKindProvider.getSymbolKind(e),name:e.name,location:{range:t.range,uri:e.documentUri.toString()}}}},NormalizedTextDocuments=class{constructor(e){this._configuration=e,this._syncedDocuments=/* @__PURE__ */ new Map,this._onDidChangeContent=new g,this._onDidOpen=new g,this._onDidClose=new g,this._onDidSave=new g,this._onWillSave=new g}get onDidOpen(){return this._onDidOpen.event}get onDidChangeContent(){return this._onDidChangeContent.event}get onWillSave(){return this._onWillSave.event}onWillSaveWaitUntil(e){this._willSaveWaitUntil=e}get onDidSave(){return this._onDidSave.event}get onDidClose(){return this._onDidClose.event}get(e){return this._syncedDocuments.get(J.normalize(e))}set(e){let t=J.normalize(e.uri),n=!0;this._syncedDocuments.has(t)&&(n=!1),this._syncedDocuments.set(t,e);let r=Object.freeze({document:e});return this._onDidOpen.fire(r),this._onDidChangeContent.fire(r),n}delete(e){let t=J.normalize(typeof e==`object`&&`uri`in e?e.uri:e),n=this._syncedDocuments.get(t);n!==void 0&&(this._syncedDocuments.delete(t),this._onDidClose.fire(Object.freeze({document:n})))}all(){return Array.from(this._syncedDocuments.values())}keys(){return Array.from(this._syncedDocuments.keys())}listen(e){e.__textDocumentSync=ue.Incremental;let t=[];return t.push(e.onDidOpenTextDocument(e=>{let t=e.textDocument,n=J.normalize(t.uri),r=this._configuration.create(n,t.languageId,t.version,t.text);this._syncedDocuments.set(n,r);let i=Object.freeze({document:r});this._onDidOpen.fire(i),this._onDidChangeContent.fire(i)})),t.push(e.onDidChangeTextDocument(e=>{let t=e.textDocument,n=e.contentChanges;if(n.length===0)return;let{version:r}=t;if(r==null)throw Error(`Received document change event for ${t.uri} without valid version identifier`);let i=J.normalize(t.uri),a=this._syncedDocuments.get(i);a!==void 0&&(a=this._configuration.update(a,n,r),this._syncedDocuments.set(i,a),this._onDidChangeContent.fire(Object.freeze({document:a})))})),t.push(e.onDidCloseTextDocument(e=>{let t=J.normalize(e.textDocument.uri),n=this._syncedDocuments.get(t);n!==void 0&&(this._syncedDocuments.delete(t),this._onDidClose.fire(Object.freeze({document:n})))})),t.push(e.onWillSaveTextDocument(e=>{let t=this._syncedDocuments.get(J.normalize(e.textDocument.uri));t!==void 0&&this._onWillSave.fire(Object.freeze({document:t,reason:e.reason}))})),t.push(e.onWillSaveTextDocumentWaitUntil((e,t)=>{let n=this._syncedDocuments.get(J.normalize(e.textDocument.uri));return n!==void 0&&this._willSaveWaitUntil?this._willSaveWaitUntil(Object.freeze({document:n,reason:e.reason}),t):[]})),t.push(e.onDidSaveTextDocument(e=>{let t=this._syncedDocuments.get(J.normalize(e.textDocument.uri));t!==void 0&&this._onDidSave.fire(Object.freeze({document:t}))})),h.create(()=>{t.forEach(e=>e.dispose())})}},NormalizedNotebookDocuments=class{constructor(e){this.notebookDocuments=/* @__PURE__ */ new Map,this.notebookCellMap=/* @__PURE__ */ new Map,this._onDidOpen=new g,this._onDidSave=new g,this._onDidChange=new g,this._onDidClose=new g,this._cellTextDocuments=`listen`in e?e:new NormalizedTextDocuments(e)}get cellTextDocuments(){return this._cellTextDocuments}getCellTextDocument(e){return this._cellTextDocuments.get(e.document)}getNotebookDocument(e){return this.notebookDocuments.get(J.normalize(e))}getNotebookCell(e){let t=this.notebookCellMap.get(J.normalize(e));return t&&t[0]}findNotebookDocumentForCell(e){let t=typeof e==`string`||`scheme`in e?e:e.document,n=this.notebookCellMap.get(J.normalize(t));return n&&n[1]}get onDidOpen(){return this._onDidOpen.event}get onDidSave(){return this._onDidSave.event}get onDidChange(){return this._onDidChange.event}get onDidClose(){return this._onDidClose.event}listen(e){let t=new zt,n=[];return n.push(this.cellTextDocuments.listen(t)),n.push(e.notebooks.synchronization.onDidOpenNotebookDocument(e=>{let n=J.normalize(e.notebookDocument.uri);this.notebookDocuments.set(n,e.notebookDocument);for(let n of e.cellTextDocuments)t.openTextDocument({textDocument:n});this.updateCellMap(e.notebookDocument),this._onDidOpen.fire(e.notebookDocument)})),n.push(e.notebooks.synchronization.onDidChangeNotebookDocument(e=>{let n=J.normalize(e.notebookDocument.uri),r=this.notebookDocuments.get(n);if(r===void 0)return;r.version=e.notebookDocument.version;let i=r.metadata,a=!1,o=e.change;o.metadata!==void 0&&(a=!0,r.metadata=o.metadata);let s=[],c=[],l=[],u=[];if(o.cells!==void 0){let e=o.cells;if(e.structure!==void 0){let n=e.structure.array;if(r.cells.splice(n.start,n.deleteCount,...n.cells===void 0?[]:n.cells),e.structure.didOpen!==void 0)for(let n of e.structure.didOpen)t.openTextDocument({textDocument:n}),s.push(n.uri);if(e.structure.didClose)for(let n of e.structure.didClose)t.closeTextDocument({textDocument:n}),c.push(n.uri)}if(e.data!==void 0){let t=new Map(e.data.map(e=>[e.document,e]));for(let e=0;e<=r.cells.length;e++){let n=t.get(r.cells[e].document);if(n!==void 0){let i=r.cells.splice(e,1,n);if(l.push({old:i[0],new:n}),t.delete(n.document),t.size===0)break}}}if(e.textContent!==void 0)for(let n of e.textContent)t.changeTextDocument({textDocument:n.document,contentChanges:n.changes}),u.push(n.document.uri)}this.updateCellMap(r);let d={notebookDocument:r};a&&(d.metadata={old:i,new:r.metadata});let f=[];for(let e of s)f.push(this.getNotebookCell(e));let p=[];for(let e of c)p.push(this.getNotebookCell(e));let m=[];for(let e of u)m.push(this.getNotebookCell(e));(f.length>0||p.length>0||l.length>0||m.length>0)&&(d.cells={added:f,removed:p,changed:{data:l,textContent:m}}),(d.metadata!==void 0||d.cells!==void 0)&&this._onDidChange.fire(d)})),n.push(e.notebooks.synchronization.onDidSaveNotebookDocument(e=>{let t=this.getNotebookDocument(e.notebookDocument.uri);t!==void 0&&this._onDidSave.fire(t)})),n.push(e.notebooks.synchronization.onDidCloseNotebookDocument(e=>{let n=J.normalize(e.notebookDocument.uri),r=this.notebookDocuments.get(n);if(r!==void 0){this._onDidClose.fire(r);for(let n of e.cellTextDocuments)t.closeTextDocument({textDocument:n});this.notebookDocuments.delete(n);for(let e of r.cells)this.notebookCellMap.delete(e.document)}})),h.create(()=>{n.forEach(e=>e.dispose())})}updateCellMap(e){for(let t of e.cells)this.notebookCellMap.set(t.document,[t,e])}},zt=class CellTextDocumentConnection{onDidOpenTextDocument(e){return this.openHandler=e,h.create(()=>{this.openHandler=void 0})}openTextDocument(e){this.openHandler&&this.openHandler(e)}onDidChangeTextDocument(e){return this.changeHandler=e,h.create(()=>{this.changeHandler=e})}changeTextDocument(e){this.changeHandler&&this.changeHandler(e)}onDidCloseTextDocument(e){return this.closeHandler=e,h.create(()=>{this.closeHandler=void 0})}closeTextDocument(e){this.closeHandler&&this.closeHandler(e)}onWillSaveTextDocument(){return CellTextDocumentConnection.NULL_DISPOSE}onWillSaveTextDocumentWaitUntil(){return CellTextDocumentConnection.NULL_DISPOSE}onDidSaveTextDocument(){return CellTextDocumentConnection.NULL_DISPOSE}};zt.NULL_DISPOSE=Object.freeze({dispose:()=>{}});function createDefaultModule(e){return ht.merge(createDefaultCoreModule(e),createDefaultLSPModule(e))}function createDefaultLSPModule(e){return{lsp:{CompletionProvider:e=>new DefaultCompletionProvider(e),DocumentSymbolProvider:e=>new DefaultDocumentSymbolProvider(e),HoverProvider:e=>new MultilineCommentHoverProvider(e),FoldingRangeProvider:e=>new DefaultFoldingRangeProvider(e),ReferencesProvider:e=>new DefaultReferencesProvider(e),DefinitionProvider:e=>new DefaultDefinitionProvider(e),DocumentHighlightProvider:e=>new DefaultDocumentHighlightProvider(e),RenameProvider:e=>new DefaultRenameProvider(e)},shared:()=>e.shared}}function createDefaultSharedModule(e){return ht.merge(createDefaultSharedCoreModule(e),createDefaultSharedLSPModule(e))}function createDefaultSharedLSPModule(e){return{lsp:{Connection:()=>e.connection,LanguageServer:e=>new DefaultLanguageServer(e),DocumentUpdateHandler:e=>new DefaultDocumentUpdateHandler(e),WorkspaceSymbolProvider:e=>new DefaultWorkspaceSymbolProvider(e),NodeKindProvider:()=>new DefaultNodeKindProvider,FuzzyMatcher:()=>new DefaultFuzzyMatcher},workspace:{TextDocuments:()=>new NormalizedTextDocuments(be),NotebookDocuments:e=>new NormalizedNotebookDocuments(e.workspace.TextDocuments)}}}var AbstractFormatter=class{constructor(){this.collector=()=>{}}getNodeFormatter(e){return new DefaultNodeFormatter(e,this.collector)}formatDocument(e,t){let n=e.parseResult;return n.lexerErrors.length===0&&n.parserErrors.length===0?this.doDocumentFormat(e,t.options):[]}isFormatRangeErrorFree(e,t){let n=e.parseResult;return n.lexerErrors.length||n.parserErrors.length?Math.min(...n.lexerErrors.map(e=>e.line??Number.MAX_VALUE),...n.parserErrors.map(e=>e.token.startLine??Number.MAX_VALUE))>t.end.line:!0}formatDocumentRange(e,t){return this.isFormatRangeErrorFree(e,t.range)?this.doDocumentFormat(e,t.options,t.range):[]}formatDocumentOnType(e,t){let n={start:{character:0,line:t.position.line},end:t.position};return this.isFormatRangeErrorFree(e,n)?this.doDocumentFormat(e,t.options,n):[]}get formatOnTypeOptions(){}doDocumentFormat(e,t,n){let r=/* @__PURE__ */ new Map,collector=(e,t,n)=>{let i=this.nodeModeToKey(e,t),a=r.get(i),o=n.options.priority??0,s=a?.options.priority??0;(!a||s<=o)&&r.set(i,n)};this.collector=collector,this.iterateAstFormatting(e,n);let i=this.iterateCstFormatting(e,r,t,n);return this.avoidOverlappingEdits(e.textDocument,i)}avoidOverlappingEdits(e,t){let n=[];for(let r of t){let t=n[n.length-1];for(;t&&e.offsetAt(r.range.start)<e.offsetAt(t.range.end);)n.pop(),t=n[n.length-1];n.push(r)}return n.filter(t=>this.isNecessary(t,e))}iterateAstFormatting(e,t){let n=e.parseResult.value;this.format(n);let r=streamAllContents(n).iterator(),i;do if(i=r.next(),!i.done){let e=i.value;this.insideRange(e.$cstNode.range,t)?this.format(e):r.prune()}while(!i.done)}nodeModeToKey(e,t){return`${e.offset}:${e.end}:${t}`}insideRange(e,t){return!t||e.start.line<=t.start.line&&e.end.line>=t.end.line||e.start.line>=t.start.line&&e.end.line<=t.end.line||e.start.line<=t.end.line&&e.end.line>=t.end.line}isNecessary(e,t){return e.newText!==t.getText(e.range).replace(/\r/g,``)}iterateCstFormatting(e,t,n,r){let i={indentation:0,options:n,document:e.textDocument},a=[],o=this.iterateCstTree(e,i).iterator(),s,c;do if(c=o.next(),!c.done){let e=c.value,n=isLeafCstNode(e),o=this.nodeModeToKey(e,`prepend`),l=t.get(o);if(t.delete(o),l){let t=this.createTextEdit(s,e,l,i);for(let e of t)e&&this.insideRange(e.range,r)&&a.push(e)}let u=this.nodeModeToKey(e,`append`),d=t.get(u);if(t.delete(u),d){let t=getNextNode(e);if(t){let n=this.createTextEdit(e,t,d,i);for(let e of n)e&&this.insideRange(e.range,r)&&a.push(e)}}if(!l&&e.hidden){let t=this.createHiddenTextEdits(s,e,void 0,i);for(let e of t)e&&this.insideRange(e.range,r)&&a.push(e)}n&&(s=e)}while(!c.done);return a}createHiddenTextEdits(e,t,n,r){let i=t.range.start,a=i.line;if(e&&e.range.end.line===a)return[];let o=[],s={start:{character:0,line:a},end:i},c=r.document.getText(s),l=this.findFittingMove(s,n?.moves??[],r),u=this.getExistingIndentationCharacterCount(c,r),d=this.getIndentationCharacterCount(r,l)-u;if(d===0)return[];let f=``;d>0&&(f=(r.options.insertSpaces?` `:` `).repeat(d));let p=t.text.split(`
11
+ `}var JSDocDocumentationProvider=class{constructor(e){this.indexManager=e.shared.workspace.IndexManager,this.commentProvider=e.documentation.CommentProvider}getDocumentation(e){let t=this.commentProvider.getComment(e);if(t&&isJSDoc(t))return parseJSDoc(t).toMarkdown({renderLink:(t,n)=>this.documentationLinkRenderer(e,t,n),renderTag:t=>this.documentationTagRenderer(e,t)})}documentationLinkRenderer(e,t,n){let r=this.findNameInLocalSymbols(e,t)??this.findNameInGlobalScope(e,t);if(r&&r.nameSegment){let e=r.nameSegment.range.start.line+1,t=r.nameSegment.range.start.character+1;return`[${n}](${r.documentUri.with({fragment:`L${e},${t}`}).toString()})`}}documentationTagRenderer(e,t){}findNameInLocalSymbols(e,t){let n=getDocument(e).localSymbols;if(!n)return;let r=e;do{let e=n.getStream(r).find(e=>e.name===t);if(e)return e;r=r.$container}while(r)}findNameInGlobalScope(e,t){return this.indexManager.allElements().find(e=>e.name===t)}},DefaultAsyncParser=class{constructor(e){this.syncParser=e.parser.LangiumParser}parse(e,t){return Promise.resolve(this.syncParser.parse(e))}},DefaultLexerErrorMessageProvider=class{buildUnexpectedCharactersMessage(e,t,n,r,i){return u.buildUnexpectedCharactersMessage(e,t,n,r,i)}buildUnableToPopLexerModeMessage(e){return u.buildUnableToPopLexerModeMessage(e)}};const St={mode:`full`};var DefaultLexer=class{constructor(e){this.errorMessageProvider=e.parser.LexerErrorMessageProvider,this.tokenBuilder=e.parser.TokenBuilder;let t=this.tokenBuilder.buildTokens(e.Grammar,{caseInsensitive:e.LanguageMetaData.caseInsensitive});this.tokenTypes=this.toTokenTypeDictionary(t);let n=isTokenTypeDictionary(t)?Object.values(t):t,r=e.LanguageMetaData.mode===`production`;this.chevrotainLexer=new a(n,{positionTracking:`full`,skipValidations:r,errorMessageProvider:this.errorMessageProvider})}get definition(){return this.tokenTypes}tokenize(e,t=St){let n=this.chevrotainLexer.tokenize(e);return{tokens:n.tokens,errors:n.errors,hidden:n.groups.hidden??[],report:this.tokenBuilder.flushLexingReport?.(e)}}toTokenTypeDictionary(e){if(isTokenTypeDictionary(e))return e;let t=isIMultiModeLexerDefinition(e)?Object.values(e.modes).flat():e,n={};return t.forEach(e=>n[e.name]=e),n}};function isTokenTypeArray(e){return Array.isArray(e)&&(e.length===0||`name`in e[0])}function isIMultiModeLexerDefinition(e){return e&&`modes`in e&&`defaultMode`in e}function isTokenTypeDictionary(e){return!isTokenTypeArray(e)&&!isIMultiModeLexerDefinition(e)}var DefaultHydrator=class{constructor(e){this.grammarElementIdMap=new BiMap,this.tokenTypeIdMap=new BiMap,this.cstNodeBuilder=new CstNodeBuilder,this.grammar=e.Grammar,this.lexer=e.parser.Lexer,this.linker=e.references.Linker}dehydrate(e){return{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport?this.dehydrateLexerReport(e.lexerReport):void 0,parserErrors:e.parserErrors.map(e=>({...e,message:e.message})),value:this.dehydrateAstNode(e.value,this.createDehyrationContext(e.value))}}dehydrateLexerReport(e){return e}createDehyrationContext(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let n of streamAst(e))t.set(n,{});if(e.$cstNode)for(let t of streamCst(e.$cstNode))n.set(t,{});return{astNodes:t,cstNodes:n}}dehydrateAstNode(e,t){let n=t.astNodes.get(e);n.$type=e.$type,n.$containerIndex=e.$containerIndex,n.$containerProperty=e.$containerProperty,e.$cstNode!==void 0&&(n.$cstNode=this.dehydrateCstNode(e.$cstNode,t));for(let[r,i]of Object.entries(e))if(!r.startsWith(`$`)){if(Array.isArray(i)){let e=[];n[r]=e;for(let n of i)isAstNode(n)?e.push(this.dehydrateAstNode(n,t)):isReference(n)?e.push(this.dehydrateReference(n,t)):e.push(n)}else isAstNode(i)?n[r]=this.dehydrateAstNode(i,t):isReference(i)?n[r]=this.dehydrateReference(i,t):i!==void 0&&(n[r]=i)}return n}dehydrateReference(e,t){let n={};return n.$refText=e.$refText,e.$refNode&&(n.$refNode=t.cstNodes.get(e.$refNode)),n}dehydrateCstNode(e,t){let n=t.cstNodes.get(e);if(isRootCstNode(e)?n.fullText=e.fullText:n.grammarSource=this.getGrammarElementId(e.grammarSource),n.hidden=e.hidden,isCompositeCstNode(e))n.content=e.content.map(e=>this.dehydrateCstNode(e,t));else if(isLeafCstNode(e)){n.tokenType=e.tokenType.name,n.offset=e.offset,n.length=e.length;let{start:t,end:r}=e.range;n.startLine=t.line,n.startColumn=t.character,n.endLine=r.line,n.endColumn=r.character}return n}hydrate(e){let t=e.value,n=this.createHydrationContext(t);return`$cstNode`in t&&this.hydrateCstNode(t.$cstNode,n),{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport,parserErrors:e.parserErrors,value:this.hydrateAstNode(t,n)}}createHydrationContext(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let n of streamAst(e))t.set(n,{});if(e.$cstNode)for(let t of streamCst(e.$cstNode)){let e;`fullText`in t?e=new RootCstNodeImpl(t.fullText):`content`in t?e=new CompositeCstNodeImpl:`tokenType`in t&&(e=this.hydrateCstLeafNode(t)),e&&n.set(t,e)}return{astNodes:t,cstNodes:n,linkedCstNodes:/* @__PURE__ */ new Set}}hydrateAstNode(e,t){let n=t.astNodes.get(e);if(n.$type=e.$type,n.$containerIndex=e.$containerIndex,n.$containerProperty=e.$containerProperty,e.$cstNode){let r=t.cstNodes.get(e.$cstNode);n.$cstNode=r,r&&!t.linkedCstNodes.has(r)&&(t.linkedCstNodes.add(r),r.astNode=n)}for(let[r,i]of Object.entries(e))if(!r.startsWith(`$`)){if(Array.isArray(i)){let e=[];n[r]=e;for(let a of i)isAstNode(a)?e.push(this.setParent(this.hydrateAstNode(a,t),n)):isReference(a)?e.push(this.hydrateReference(a,n,r,t)):e.push(a)}else isAstNode(i)?n[r]=this.setParent(this.hydrateAstNode(i,t),n):isReference(i)?n[r]=this.hydrateReference(i,n,r,t):i!==void 0&&(n[r]=i)}return n}setParent(e,t){return e.$container=t,e}hydrateReference(e,t,n,r){return this.linker.buildReference(t,n,r.cstNodes.get(e.$refNode),e.$refText)}hydrateCstNode(e,t,n=0){let r=t.cstNodes.get(e);if(typeof e.grammarSource==`number`&&(r.grammarSource=this.getGrammarElement(e.grammarSource)),isCompositeCstNode(r)){let i=[];for(let r of e.content)i.push(this.hydrateCstNode(r,t,n++));this.cstNodeBuilder.appendChildren(r,i)}return r}hydrateCstLeafNode(e){let t=this.getTokenType(e.tokenType);return new LeafCstNodeImpl(e.offset,e.length,e.startLine,e.startColumn,e.endLine,e.endColumn,t,e.hidden)}getTokenType(e){return this.lexer.definition[e]}getGrammarElementId(e){if(e)return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.get(e)}getGrammarElement(e){return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.getKey(e)}createGrammarElementIdMap(){let e=0;for(let t of streamAst(this.grammar))isAbstractElement(t)&&this.grammarElementIdMap.set(t,e++)}},Ct;(function(e){function create(e){return{dispose:async()=>await e()}}e.create=create})(Ct||={});var EmptyFileSystemProvider=class{stat(e){throw Error(`No file system is available.`)}statSync(e){throw Error(`No file system is available.`)}async exists(){return!1}existsSync(){return!1}readBinary(){throw Error(`No file system is available.`)}readBinarySync(){throw Error(`No file system is available.`)}readFile(){throw Error(`No file system is available.`)}readFileSync(){throw Error(`No file system is available.`)}async readDirectory(){return[]}readDirectorySync(){return[]}};const wt={fileSystemProvider:()=>new EmptyFileSystemProvider},Tt={Grammar:()=>void 0,LanguageMetaData:()=>({caseInsensitive:!1,fileExtensions:[`.langium`],languageId:`langium`})},Et={AstReflection:()=>new LangiumGrammarAstReflection};function createMinimalGrammarServices(){let e=inject(createDefaultSharedCoreModule(wt),Et),t=inject(createDefaultCoreModule({shared:e}),Tt);return e.ServiceRegistry.register(t),t}function loadGrammarFromJson(e){let t=createMinimalGrammarServices(),n=t.serializer.JsonSerializer.deserialize(e);return t.shared.workspace.LangiumDocumentFactory.fromModel(n,y.parse(`memory:/${n.name??`grammar`}.langium`)),n}var DefaultAstNodeDescriptionProvider=class{constructor(e){this.astNodeLocator=e.workspace.AstNodeLocator,this.nameProvider=e.references.NameProvider}createDescription(e,t,n){let r=n??getDocument(e);t??=this.nameProvider.getName(e);let i=this.astNodeLocator.getAstNodePath(e);if(!t)throw Error(`Node at path ${i} has no name.`);let a,nameSegmentGetter=()=>a??=toDocumentSegment(this.nameProvider.getNameNode(e)??e.$cstNode);return{node:e,name:t,get nameSegment(){return nameSegmentGetter()},selectionSegment:toDocumentSegment(e.$cstNode),type:e.$type,documentUri:r.uri,path:i}}},DefaultReferenceDescriptionProvider=class{constructor(e){this.nodeLocator=e.workspace.AstNodeLocator}async createDescriptions(e,t=b.None){let n=[],r=e.parseResult.value;for(let e of streamAst(r))await interruptAndCheck(t),streamReferences(e).forEach(e=>{e.reference.error||n.push(...this.createInfoDescriptions(e))});return n}createInfoDescriptions(e){let t=e.reference;if(t.error||!t.$refNode)return[];let n=[];isReference(t)&&t.$nodeDescription?n=[t.$nodeDescription]:isMultiReference(t)&&(n=t.items.map(e=>e.$nodeDescription).filter(e=>e!==void 0));let r=getDocument(e.container).uri,i=this.nodeLocator.getAstNodePath(e.container),a=[],o=toDocumentSegment(t.$refNode);for(let e of n)a.push({sourceUri:r,sourcePath:i,targetUri:e.documentUri,targetPath:e.path,segment:o,local:J.equals(e.documentUri,r)});return a}},DefaultAstNodeLocator=class{constructor(){this.segmentSeparator=`/`,this.indexSeparator=`@`}getAstNodePath(e){if(e.$container){let t=this.getAstNodePath(e.$container),n=this.getPathSegment(e);return t+this.segmentSeparator+n}return``}getPathSegment({$containerProperty:e,$containerIndex:t}){if(!e)throw Error(`Missing '$containerProperty' in AST node.`);return t===void 0?e:e+this.indexSeparator+t}getAstNode(e,t){return t.split(this.segmentSeparator).reduce((e,t)=>{if(!e||t.length===0)return e;let n=t.indexOf(this.indexSeparator);if(n>0){let r=t.substring(0,n),i=parseInt(t.substring(n+1));return e[r]?.[i]}return e[t]},e)}},DefaultConfigurationProvider=class{constructor(e){this._ready=new Deferred,this.onConfigurationSectionUpdateEmitter=new ge,this.settings={},this.workspaceConfig=!1,this.serviceRegistry=e.ServiceRegistry}get ready(){return this._ready.promise}initialize(e){this.workspaceConfig=e.capabilities.workspace?.configuration??!1}async initialized(e){if(this.workspaceConfig){if(e.register){let t=this.serviceRegistry.all;e.register({section:t.map(e=>this.toSectionName(e.LanguageMetaData.languageId))})}if(e.fetchConfiguration){let t=this.serviceRegistry.all.map(e=>({section:this.toSectionName(e.LanguageMetaData.languageId)})),n=await e.fetchConfiguration(t);t.forEach((e,t)=>{this.updateSectionConfiguration(e.section,n[t])})}}this._ready.resolve()}updateConfiguration(e){typeof e.settings==`object`&&e.settings!==null&&Object.entries(e.settings).forEach(([e,t])=>{this.updateSectionConfiguration(e,t),this.onConfigurationSectionUpdateEmitter.fire({section:e,configuration:t})})}updateSectionConfiguration(e,t){this.settings[e]=t}async getConfiguration(e,t){await this.ready;let n=this.toSectionName(e);if(this.settings[n])return this.settings[n][t]}toSectionName(e){return`${e}`}get onConfigurationSectionUpdate(){return this.onConfigurationSectionUpdateEmitter.event}},DefaultDocumentBuilder=class{constructor(e){this.updateBuildOptions={validation:{categories:[`built-in`,`fast`]}},this.updateListeners=[],this.buildPhaseListeners=new MultiMap,this.documentPhaseListeners=new MultiMap,this.buildState=/* @__PURE__ */ new Map,this.documentBuildWaiters=/* @__PURE__ */ new Map,this.currentState=X.Changed,this.langiumDocuments=e.workspace.LangiumDocuments,this.langiumDocumentFactory=e.workspace.LangiumDocumentFactory,this.textDocuments=e.workspace.TextDocuments,this.indexManager=e.workspace.IndexManager,this.fileSystemProvider=e.workspace.FileSystemProvider,this.workspaceManager=()=>e.workspace.WorkspaceManager,this.serviceRegistry=e.ServiceRegistry}async build(e,t={},n=b.None){for(let n of e){let e=n.uri.toString();if(n.state===X.Validated){if(typeof t.validation==`boolean`&&t.validation)this.resetToState(n,X.IndexedReferences);else if(typeof t.validation==`object`){let r=this.findMissingValidationCategories(n,t);r.length>0&&(this.buildState.set(e,{completed:!1,options:{validation:{categories:r}},result:this.buildState.get(e)?.result}),n.state=X.IndexedReferences)}}else this.buildState.delete(e)}this.currentState=X.Changed,await this.emitUpdate(e.map(e=>e.uri),[]),await this.buildDocuments(e,t,n)}async update(e,t,n=b.None){this.currentState=X.Changed;let r=[];for(let e of t){let t=this.langiumDocuments.deleteDocuments(e);for(let e of t)r.push(e.uri),this.cleanUpDeleted(e)}let i=(await Promise.all(e.map(e=>this.findChangedUris(e)))).flat();for(let e of i){let t=this.langiumDocuments.getDocument(e);t===void 0&&(t=this.langiumDocumentFactory.fromModel({$type:`INVALID`},e),t.state=X.Changed,this.langiumDocuments.addDocument(t)),this.resetToState(t,X.Changed)}let a=stream(i).concat(r).map(e=>e.toString()).toSet();this.langiumDocuments.all.filter(e=>!a.has(e.uri.toString())&&this.shouldRelink(e,a)).forEach(e=>this.resetToState(e,X.ComputedScopes)),await this.emitUpdate(i,r),await interruptAndCheck(n);let o=this.sortDocuments(this.langiumDocuments.all.filter(e=>e.state<X.Validated||!this.buildState.get(e.uri.toString())?.completed||this.resultsAreIncomplete(e,this.updateBuildOptions)).toArray());await this.buildDocuments(o,this.updateBuildOptions,n)}resultsAreIncomplete(e,t){return this.findMissingValidationCategories(e,t).length>=1}findMissingValidationCategories(e,t){let n=this.buildState.get(e.uri.toString()),r=this.serviceRegistry.getServices(e.uri).validation.ValidationRegistry.getAllValidationCategories(e),i=n?.result?.validationChecks?new Set(n?.result?.validationChecks):n?.completed?r:/* @__PURE__ */ new Set;return stream(t===void 0||t.validation===!0?r:typeof t.validation==`object`?t.validation.categories??r:[]).filter(e=>!i.has(e)).toArray()}async findChangedUris(e){if(this.langiumDocuments.getDocument(e)??this.textDocuments?.get(e))return[e];try{let t=await this.fileSystemProvider.stat(e);if(t.isDirectory)return await this.workspaceManager().searchFolder(e);if(this.workspaceManager().shouldIncludeEntry(t))return[e]}catch{}return[]}async emitUpdate(e,t){await Promise.all(this.updateListeners.map(n=>n(e,t)))}sortDocuments(e){let t=0,n=e.length-1;for(;t<n;){for(;t<e.length&&this.hasTextDocument(e[t]);)t++;for(;n>=0&&!this.hasTextDocument(e[n]);)n--;t<n&&([e[t],e[n]]=[e[n],e[t]])}return e}hasTextDocument(e){return!!this.textDocuments?.get(e.uri)}shouldRelink(e,t){return e.references.some(e=>e.error!==void 0)?!0:this.indexManager.isAffected(e,t)}onUpdate(e){return this.updateListeners.push(e),Ct.create(()=>{let t=this.updateListeners.indexOf(e);t>=0&&this.updateListeners.splice(t,1)})}resetToState(e,t){switch(t){case X.Changed:case X.Parsed:this.indexManager.removeContent(e.uri);case X.IndexedContent:e.localSymbols=void 0;case X.ComputedScopes:this.serviceRegistry.getServices(e.uri).references.Linker.unlink(e);case X.Linked:this.indexManager.removeReferences(e.uri);case X.IndexedReferences:e.diagnostics=void 0,this.buildState.delete(e.uri.toString());case X.Validated:}e.state>t&&(e.state=t)}cleanUpDeleted(e){this.buildState.delete(e.uri.toString()),this.indexManager.remove(e.uri),e.state=X.Changed}async buildDocuments(e,t,n){this.prepareBuild(e,t),await this.runCancelable(e,X.Parsed,n,e=>this.langiumDocumentFactory.update(e,n)),await this.runCancelable(e,X.IndexedContent,n,e=>this.indexManager.updateContent(e,n)),await this.runCancelable(e,X.ComputedScopes,n,async e=>{e.localSymbols=await this.serviceRegistry.getServices(e.uri).references.ScopeComputation.collectLocalSymbols(e,n)});let r=e.filter(e=>this.shouldLink(e));await this.runCancelable(r,X.Linked,n,e=>this.serviceRegistry.getServices(e.uri).references.Linker.link(e,n)),await this.runCancelable(r,X.IndexedReferences,n,e=>this.indexManager.updateReferences(e,n));let i=e.filter(e=>this.shouldValidate(e)?!0:(this.markAsCompleted(e),!1));await this.runCancelable(i,X.Validated,n,async e=>{await this.validate(e,n),this.markAsCompleted(e)})}markAsCompleted(e){let t=this.buildState.get(e.uri.toString());t&&(t.completed=!0)}prepareBuild(e,t){for(let n of e){let e=n.uri.toString(),r=this.buildState.get(e);(!r||r.completed)&&this.buildState.set(e,{completed:!1,options:t,result:r?.result})}}async runCancelable(e,t,n,r){for(let i of e)i.state<t&&(await interruptAndCheck(n),await r(i),i.state=t,await this.notifyDocumentPhase(i,t,n));let i=e.filter(e=>e.state===t);await this.notifyBuildPhase(i,t,n),this.currentState=t}onBuildPhase(e,t){return this.buildPhaseListeners.add(e,t),Ct.create(()=>{this.buildPhaseListeners.delete(e,t)})}onDocumentPhase(e,t){return this.documentPhaseListeners.add(e,t),Ct.create(()=>{this.documentPhaseListeners.delete(e,t)})}waitUntil(e,t,n){let r;return t&&`path`in t?r=t:n=t,n??=b.None,r?this.awaitDocumentState(e,r,n):this.awaitBuilderState(e,n)}awaitDocumentState(e,t,n){let r=this.langiumDocuments.getDocument(t);return r?r.state>=e?Promise.resolve(t):n.isCancellationRequested?Promise.reject(ft):this.currentState>=e&&e>r.state?Promise.reject(new ve(_e.RequestFailed,`Document state of ${t.toString()} is ${X[r.state]}, requiring ${X[e]}, but workspace state is already ${X[this.currentState]}. Returning undefined.`)):new Promise((r,i)=>{let a=this.onDocumentPhase(e,e=>{J.equals(e.uri,t)&&(a.dispose(),o.dispose(),r(e.uri))}),o=n.onCancellationRequested(()=>{a.dispose(),o.dispose(),i(ft)})}):Promise.reject(new ve(_e.ServerCancelled,`No document found for URI: ${t.toString()}`))}awaitBuilderState(e,t){return this.currentState>=e?Promise.resolve():t.isCancellationRequested?Promise.reject(ft):new Promise((n,r)=>{let i=this.onBuildPhase(e,()=>{i.dispose(),a.dispose(),n()}),a=t.onCancellationRequested(()=>{i.dispose(),a.dispose(),r(ft)})})}async notifyDocumentPhase(e,t,n){let r=this.documentPhaseListeners.get(t).slice();for(let t of r)try{await interruptAndCheck(n),await t(e,n)}catch(e){if(!isOperationCancelled(e))throw e}}async notifyBuildPhase(e,t,n){if(e.length===0)return;let r=this.buildPhaseListeners.get(t).slice();for(let t of r)await interruptAndCheck(n),await t(e,n)}shouldLink(e){return this.getBuildOptions(e).eagerLinking??!0}shouldValidate(e){return!!this.getBuildOptions(e).validation}async validate(e,t){let n=this.serviceRegistry.getServices(e.uri).validation.DocumentValidator,r=this.getBuildOptions(e),i=typeof r.validation==`object`?{...r.validation}:{};i.categories=this.findMissingValidationCategories(e,r);let a=await n.validateDocument(e,i,t);e.diagnostics?e.diagnostics.push(...a):e.diagnostics=a;let o=this.buildState.get(e.uri.toString());o&&(o.result??={},o.result.validationChecks?o.result.validationChecks=stream(o.result.validationChecks).concat(i.categories).distinct().toArray():o.result.validationChecks=[...i.categories])}getBuildOptions(e){return this.buildState.get(e.uri.toString())?.options??{}}},DefaultIndexManager=class{constructor(e){this.symbolIndex=/* @__PURE__ */ new Map,this.symbolByTypeIndex=new ContextCache,this.referenceIndex=/* @__PURE__ */ new Map,this.documents=e.workspace.LangiumDocuments,this.serviceRegistry=e.ServiceRegistry,this.astReflection=e.AstReflection}findAllReferences(e,t){let n=getDocument(e).uri,r=[];return this.referenceIndex.forEach(e=>{e.forEach(e=>{J.equals(e.targetUri,n)&&e.targetPath===t&&r.push(e)})}),stream(r)}allElements(e,t){let n=stream(this.symbolIndex.keys());return t&&(n=n.filter(e=>!t||t.has(e))),n.map(t=>this.getFileDescriptions(t,e)).flat()}getFileDescriptions(e,t){return t?this.symbolByTypeIndex.get(e,t,()=>(this.symbolIndex.get(e)??[]).filter(e=>this.astReflection.isSubtype(e.type,t))):this.symbolIndex.get(e)??[]}remove(e){this.removeContent(e),this.removeReferences(e)}removeContent(e){let t=e.toString();this.symbolIndex.delete(t),this.symbolByTypeIndex.clear(t)}removeReferences(e){let t=e.toString();this.referenceIndex.delete(t)}async updateContent(e,t=b.None){let n=await this.serviceRegistry.getServices(e.uri).references.ScopeComputation.collectExportedSymbols(e,t),r=e.uri.toString();this.symbolIndex.set(r,n),this.symbolByTypeIndex.clear(r)}async updateReferences(e,t=b.None){let n=await this.serviceRegistry.getServices(e.uri).workspace.ReferenceDescriptionProvider.createDescriptions(e,t);this.referenceIndex.set(e.uri.toString(),n)}isAffected(e,t){let n=this.referenceIndex.get(e.uri.toString());return n?n.some(e=>!e.local&&t.has(e.targetUri.toString())):!1}},Dt;(function(e){e[e.Normal=0]=`Normal`,e[e.Immediate=1]=`Immediate`})(Dt||={});var DefaultWorkspaceLock=class{constructor(){this.previousTokenSource=new pe,this.writeQueue=[],this.readQueue=[],this.immediateReads=[],this.done=!0}write(e){this.cancelWrite();let t=startCancelableOperation();return this.previousTokenSource=t,this.enqueue(this.writeQueue,e,t.token)}read(e,t=Dt.Normal){if(t===Dt.Immediate){let t=Promise.resolve().then(()=>e());this.immediateReads.push(t);let remove=()=>{this.immediateReads.splice(this.immediateReads.indexOf(t),1)};return t.then(remove,remove),t}return this.enqueue(this.readQueue,e)}enqueue(e,t,n=b.None){let r=new Deferred,i={action:t,deferred:r,cancellationToken:n};return e.push(i),this.performNextOperation(),r.promise}async performNextOperation(){if(!this.done)return;let e=[];if(this.writeQueue.length>0)for(e.push(this.writeQueue.shift()),this.done=!1;this.immediateReads.length>0;)await Promise.allSettled(this.immediateReads.slice());else if(this.readQueue.length>0)e.push(...this.readQueue.splice(0,this.readQueue.length)),this.done=!1;else return;await Promise.all(e.map(async({action:e,deferred:t,cancellationToken:n})=>{try{let r=await Promise.resolve().then(()=>e(n));t.resolve(r)}catch(e){isOperationCancelled(e)?t.resolve(void 0):t.reject(e)}})),this.done=!0,this.performNextOperation()}cancelWrite(){this.previousTokenSource.cancel()}},DefaultWorkspaceManager=class{constructor(e){this.initialBuildOptions={},this._ready=new Deferred,this.serviceRegistry=e.ServiceRegistry,this.langiumDocuments=e.workspace.LangiumDocuments,this.documentBuilder=e.workspace.DocumentBuilder,this.fileSystemProvider=e.workspace.FileSystemProvider,this.mutex=e.workspace.WorkspaceLock}get ready(){return this._ready.promise}get workspaceFolders(){return this.folders}initialize(e){this.folders=e.workspaceFolders??void 0}initialized(e){return this.mutex.write(e=>this.initializeWorkspace(this.folders??[],e))}async initializeWorkspace(e,t=b.None){let n=await this.performStartup(e);await interruptAndCheck(t),await this.documentBuilder.build(n,this.initialBuildOptions,t)}async performStartup(e){let t=[],collector=e=>{t.push(e),this.langiumDocuments.hasDocument(e.uri)||this.langiumDocuments.addDocument(e)};await this.loadAdditionalDocuments(e,collector);let n=[];await Promise.all(e.map(e=>this.getRootFolder(e)).map(async e=>this.traverseFolder(e,n)));let r=stream(n).distinct(e=>e.toString()).filter(e=>!this.langiumDocuments.hasDocument(e));return await this.loadWorkspaceDocuments(r,collector),this._ready.resolve(),t}async loadWorkspaceDocuments(e,t){await Promise.all(e.map(async e=>{t(await this.langiumDocuments.getOrCreateDocument(e))}))}loadAdditionalDocuments(e,t){return Promise.resolve()}getRootFolder(e){return y.parse(e.uri)}async traverseFolder(e,t){try{let n=await this.fileSystemProvider.readDirectory(e);await Promise.all(n.map(async e=>{this.shouldIncludeEntry(e)&&(e.isDirectory?await this.traverseFolder(e.uri,t):e.isFile&&t.push(e.uri))}))}catch(t){console.error(`Failure to read directory content of `+e.toString(!0),t)}}async searchFolder(e){let t=[];return await this.traverseFolder(e,t),t}shouldIncludeEntry(e){let t=J.basename(e.uri);return t.startsWith(`.`)?!1:e.isDirectory?t!==`node_modules`&&t!==`out`:e.isFile?this.serviceRegistry.hasServices(e.uri):!1}};function diagnosticData(e){return{code:e}}var Ot;(function(e){e.defaults=[`fast`,`slow`,`built-in`],e.all=e.defaults})(Ot||={});var ValidationRegistry=class{constructor(e){this.entries=new MultiMap,this.knownCategories=new Set(Ot.defaults),this.entriesBefore=[],this.entriesAfter=[],this.reflection=e.shared.AstReflection}register(e,t=this,n=`fast`){if(n===`built-in`)throw Error(`The 'built-in' category is reserved for lexer, parser, and linker errors.`);this.knownCategories.add(n);for(let[r,i]of Object.entries(e)){let e=i;if(Array.isArray(e))for(let i of e){let e={check:this.wrapValidationException(i,t),category:n};this.addEntry(r,e)}else if(typeof e==`function`){let i={check:this.wrapValidationException(e,t),category:n};this.addEntry(r,i)}else assertUnreachable(e)}}wrapValidationException(e,t){return async(n,r,i)=>{await this.handleException(()=>e.call(t,n,r,i),`An error occurred during validation`,r,n)}}async handleException(e,t,n,r){try{await e()}catch(e){if(isOperationCancelled(e))throw e;console.error(`${t}:`,e),e instanceof Error&&e.stack&&console.error(e.stack),n(`error`,`${t}: ${e instanceof Error?e.message:String(e)}`,{node:r})}}addEntry(e,t){if(e===`AstNode`)this.entries.add(`AstNode`,t);else for(let n of this.reflection.getAllSubTypes(e))this.entries.add(n,t)}getChecks(e,t){let n=stream(this.entries.get(e)).concat(this.entries.get(`AstNode`));return t&&(n=n.filter(e=>t.includes(e.category))),n.map(e=>e.check)}registerBeforeDocument(e,t=this){this.entriesBefore.push(this.wrapPreparationException(e,`An error occurred during set-up of the validation`,t))}registerAfterDocument(e,t=this){this.entriesAfter.push(this.wrapPreparationException(e,`An error occurred during tear-down of the validation`,t))}wrapPreparationException(e,t,n){return async(r,i,a,o)=>{await this.handleException(()=>e.call(n,r,i,a,o),t,i,r)}}get checksBefore(){return this.entriesBefore}get checksAfter(){return this.entriesAfter}getAllValidationCategories(e){return this.knownCategories}};const kt=Object.freeze({validateNode:!0,validateChildren:!0});var DefaultDocumentValidator=class{constructor(e){this.validationRegistry=e.validation.ValidationRegistry,this.metadata=e.LanguageMetaData,this.profiler=e.shared.profilers.LangiumProfiler,this.languageId=e.LanguageMetaData.languageId}async validateDocument(e,t={},n=b.None){let r=e.parseResult,i=[];if(await interruptAndCheck(n),(!t.categories||t.categories.includes(`built-in`))&&(this.processLexingErrors(r,i,t),t.stopAfterLexingErrors&&i.some(e=>e.data?.code===Z.LexingError)||(this.processParsingErrors(r,i,t),t.stopAfterParsingErrors&&i.some(e=>e.data?.code===Z.ParsingError))||(this.processLinkingErrors(e,i,t),t.stopAfterLinkingErrors&&i.some(e=>e.data?.code===Z.LinkingError))))return i;try{i.push(...await this.validateAst(r.value,t,n))}catch(e){if(isOperationCancelled(e))throw e;console.error(`An error occurred during validation:`,e)}return await interruptAndCheck(n),i}processLexingErrors(e,t,n){let r=[...e.lexerErrors,...e.lexerReport?.diagnostics??[]];for(let e of r){let n=e.severity??`error`,r={severity:toDiagnosticSeverity(n),range:{start:{line:e.line-1,character:e.column-1},end:{line:e.line-1,character:e.column+e.length-1}},message:e.message,data:toDiagnosticData(n),source:this.getSource()};t.push(r)}}processParsingErrors(e,t,n){for(let n of e.parserErrors){let e;if(isValidTokenRange(n.token))e=tokenToRange(n.token);else if(`previousToken`in n){let t=n.previousToken;if(isValidTokenRange(t)){let n={line:t.endLine-1,character:t.endColumn};e={start:n,end:n}}else{let t={line:0,character:0};e={start:t,end:t}}}if(e){let r={severity:toDiagnosticSeverity(`error`),range:e,message:n.message,data:diagnosticData(Z.ParsingError),source:this.getSource()};t.push(r)}}}processLinkingErrors(e,t,n){for(let n of e.references){let e=n.error;if(e){let r={node:e.info.container,range:n.$refNode?.range,property:e.info.property,index:e.info.index,data:{code:Z.LinkingError,containerType:e.info.container.$type,property:e.info.property,refText:e.info.reference.$refText}};t.push(this.toDiagnostic(`error`,e.message,r))}}}async validateAst(e,t,n=b.None){let r=[],acceptor=(e,t,n)=>{r.push(this.toDiagnostic(e,t,n))};return await this.validateAstBefore(e,t,acceptor,n),await this.validateAstNodes(e,t,acceptor,n),await this.validateAstAfter(e,t,acceptor,n),r}async validateAstBefore(e,t,n,r=b.None){let i=this.validationRegistry.checksBefore;for(let a of i)await interruptAndCheck(r),await a(e,n,t.categories??[],r)}async validateAstNodes(e,t,n,r=b.None){if(this.profiler?.isActive(`validating`)){let i=this.profiler.createTask(`validating`,this.languageId);i.start();try{let a=streamAst(e).iterator();for(let e of a){i.startSubTask(e.$type);let o=this.validateSingleNodeOptions(e,t);if(o.validateNode)try{let i=this.validationRegistry.getChecks(e.$type,t.categories);for(let t of i)await t(e,n,r)}finally{i.stopSubTask(e.$type)}o.validateChildren||a.prune()}}finally{i.stop()}}else{let i=streamAst(e).iterator();for(let e of i){await interruptAndCheck(r);let a=this.validateSingleNodeOptions(e,t);if(a.validateNode){let i=this.validationRegistry.getChecks(e.$type,t.categories);for(let t of i)await t(e,n,r)}a.validateChildren||i.prune()}}}validateSingleNodeOptions(e,t){return kt}async validateAstAfter(e,t,n,r=b.None){let i=this.validationRegistry.checksAfter;for(let a of i)await interruptAndCheck(r),await a(e,n,t.categories??[],r)}toDiagnostic(e,t,n){return{message:t,range:getDiagnosticRange(n),severity:toDiagnosticSeverity(e),code:n.code,codeDescription:n.codeDescription,tags:n.tags,relatedInformation:n.relatedInformation,data:n.data,source:this.getSource()}}getSource(){return this.metadata.languageId}};function getDiagnosticRange(e){if(e.range)return e.range;let t;return typeof e.property==`string`?t=findNodeForProperty(e.node.$cstNode,e.property,e.index):typeof e.keyword==`string`&&(t=findNodeForKeyword(e.node.$cstNode,e.keyword,e.index)),t??=e.node.$cstNode,t?t.range:{start:{line:0,character:0},end:{line:0,character:0}}}function toDiagnosticSeverity(e){switch(e){case`error`:return 1;case`warning`:return 2;case`info`:return 3;case`hint`:return 4;default:throw Error(`Invalid diagnostic severity: `+e)}}function toDiagnosticData(e){switch(e){case`error`:return diagnosticData(Z.LexingError);case`warning`:return diagnosticData(Z.LexingWarning);case`info`:return diagnosticData(Z.LexingInfo);case`hint`:return diagnosticData(Z.LexingHint);default:throw Error(`Invalid diagnostic severity: `+e)}}var Z;(function(e){e.LexingError=`lexing-error`,e.LexingWarning=`lexing-warning`,e.LexingInfo=`lexing-info`,e.LexingHint=`lexing-hint`,e.ParsingError=`parsing-error`,e.LinkingError=`linking-error`})(Z||={});function createDefaultCoreModule(e){return{documentation:{CommentProvider:e=>new DefaultCommentProvider(e),DocumentationProvider:e=>new JSDocDocumentationProvider(e)},parser:{AsyncParser:e=>new DefaultAsyncParser(e),GrammarConfig:e=>createGrammarConfig(e),LangiumParser:e=>createLangiumParser(e),CompletionParser:e=>createCompletionParser(e),ValueConverter:()=>new DefaultValueConverter,TokenBuilder:()=>new DefaultTokenBuilder,Lexer:e=>new DefaultLexer(e),ParserErrorMessageProvider:()=>new LangiumParserErrorMessageProvider,LexerErrorMessageProvider:()=>new DefaultLexerErrorMessageProvider},workspace:{AstNodeLocator:()=>new DefaultAstNodeLocator,AstNodeDescriptionProvider:e=>new DefaultAstNodeDescriptionProvider(e),ReferenceDescriptionProvider:e=>new DefaultReferenceDescriptionProvider(e)},references:{Linker:e=>new DefaultLinker(e),NameProvider:()=>new DefaultNameProvider,ScopeProvider:e=>new DefaultScopeProvider(e),ScopeComputation:e=>new DefaultScopeComputation(e),References:e=>new DefaultReferences(e)},serializer:{Hydrator:e=>new DefaultHydrator(e),JsonSerializer:e=>new DefaultJsonSerializer(e)},validation:{DocumentValidator:e=>new DefaultDocumentValidator(e),ValidationRegistry:e=>new ValidationRegistry(e)},shared:()=>e.shared}}function createDefaultSharedCoreModule(e){return{ServiceRegistry:e=>new DefaultServiceRegistry(e),workspace:{LangiumDocuments:e=>new DefaultLangiumDocuments(e),LangiumDocumentFactory:e=>new DefaultLangiumDocumentFactory(e),DocumentBuilder:e=>new DefaultDocumentBuilder(e),IndexManager:e=>new DefaultIndexManager(e),WorkspaceManager:e=>new DefaultWorkspaceManager(e),FileSystemProvider:t=>e.fileSystemProvider(t),WorkspaceLock:()=>new DefaultWorkspaceLock,ConfigurationProvider:e=>new DefaultConfigurationProvider(e)},profilers:{}}}var DefaultDocumentHighlightProvider=class{constructor(e){this.references=e.references.References,this.nameProvider=e.references.NameProvider,this.grammarConfig=e.parser.GrammarConfig}getDocumentHighlight(e,t,n){let r=e.parseResult.value.$cstNode;if(!r)return;let i=findDeclarationNodeAtOffset(r,e.textDocument.offsetAt(t.position),this.grammarConfig.nameRegexp);if(!i)return;let a=this.references.findDeclarations(i),o=[];for(let t of a){let n=J.equals(getDocument(t).uri,e.uri),r={documentUri:e.uri,includeDeclaration:n},i=this.references.findReferences(t,r);o.push(...i.map(e=>this.createDocumentHighlight(e)).toArray())}return o}createDocumentHighlight(e){return te.create(e.segment.range)}},DefaultDocumentSymbolProvider=class{constructor(e){this.nameProvider=e.references.NameProvider,this.nodeKindProvider=e.shared.lsp.NodeKindProvider}getSymbols(e,t,n){return this.getSymbol(e,e.parseResult.value)}getSymbol(e,t){let n=this.nameProvider.getNameNode(t);if(n&&t.$cstNode){let r=this.nameProvider.getName(t);return[this.createSymbol(e,t,t.$cstNode,n,r)]}return this.getChildSymbols(e,t)||[]}createSymbol(e,t,n,r,i){return{kind:this.nodeKindProvider.getSymbolKind(t),name:i||r.text,range:n.range,selectionRange:r.range,children:this.getChildSymbols(e,t)}}getChildSymbols(e,t){let n=[];for(let r of streamContents(t)){let t=this.getSymbol(e,r);n.push(...t)}if(n.length>0)return n}},DefaultDocumentUpdateHandler=class{constructor(e){this.onWatchedFilesChangeEmitter=new ge,this.workspaceManager=e.workspace.WorkspaceManager,this.documentBuilder=e.workspace.DocumentBuilder,this.workspaceLock=e.workspace.WorkspaceLock,this.serviceRegistry=e.ServiceRegistry;let t=!1;e.lsp.LanguageServer.onInitialize(e=>{t=!!e.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration}),e.lsp.LanguageServer.onInitialized(n=>{t&&this.registerFileWatcher(e)})}registerFileWatcher(e){let t=this.getWatchers();if(t.length>0){let n=e.lsp.Connection,r={watchers:t};n?.client.register(ee.type,r)}}getWatchers(){return[{globPattern:`**/*`}]}fireDocumentUpdate(e,t){this.workspaceManager.ready.then(()=>{this.workspaceLock.write(n=>this.documentBuilder.update(e,t,n))}).catch(e=>{console.error(`Workspace initialization failed. Could not perform document update.`,e)})}didChangeContent(e){this.fireDocumentUpdate([y.parse(e.document.uri)],[])}didChangeWatchedFiles(e){this.onWatchedFilesChangeEmitter.fire(e);let t=stream(e.changes).filter(e=>e.type!==ne.Deleted).distinct(e=>e.uri).map(e=>y.parse(e.uri)).toArray(),n=stream(e.changes).filter(e=>e.type===ne.Deleted).distinct(e=>e.uri).map(e=>y.parse(e.uri)).toArray();this.fireDocumentUpdate(t,n)}get onWatchedFilesChange(){return this.onWatchedFilesChangeEmitter.event}},DefaultFoldingRangeProvider=class{constructor(e){this.commentNames=e.parser.GrammarConfig.multilineCommentRules}getFoldingRanges(e,t,n){let r=[],acceptor=e=>r.push(e);return this.collectFolding(e,acceptor),r}collectFolding(e,t){let n=e.parseResult?.value;if(n){if(this.shouldProcessContent(n)){let r=streamAllContents(n).iterator(),i;do if(i=r.next(),!i.done){let n=i.value;this.shouldProcess(n)&&this.collectObjectFolding(e,n,t),this.shouldProcessContent(n)||r.prune()}while(!i.done)}this.collectCommentFolding(e,n,t)}}shouldProcess(e){return!0}shouldProcessContent(e){return!0}collectObjectFolding(e,t,n){let r=t.$cstNode;if(r){let t=this.toFoldingRange(e,r);t&&n(t)}}collectCommentFolding(e,t,n){let r=t.$cstNode;if(r){for(let t of flattenCst(r))if(this.commentNames.includes(t.tokenType.name)){let r=this.toFoldingRange(e,t,ie.Comment);r&&n(r)}}}toFoldingRange(e,t,n){let r=t.range,i=r.start,a=r.end;if(!(a.line-i.line<2))return this.includeLastFoldingLine(t,n)||(a=e.textDocument.positionAt(e.textDocument.offsetAt({line:a.line,character:0})-1)),re.create(i.line,a.line,i.character,a.character,n)}includeLastFoldingLine(e,t){if(t===ie.Comment)return!1;let n=e.root.fullText.charAt(e.end-1);return n!==`}`&&n!==`)`&&n!==`]`}},DefaultFuzzyMatcher=class{match(e,t){if(e.length===0)return!0;let n=!1,r,i=0,a=t.length;for(let o=0;o<a;o++){let a=t.charCodeAt(o),s=e.charCodeAt(i);if((a===s||this.toUpperCharCode(a)===this.toUpperCharCode(s))&&(n||=r===void 0||this.isWordTransition(r,a),n&&i++,i===e.length))return!0;r=a}return!1}isWordTransition(e,t){return At<=e&&e<=jt&&Mt<=t&&t<=Nt||e===Pt&&t!==Pt}toUpperCharCode(e){return At<=e&&e<=jt?e-32:e}};const At=97,jt=122,Mt=65,Nt=90,Pt=95;var AstNodeHoverProvider=class{constructor(e){this.references=e.references.References,this.grammarConfig=e.parser.GrammarConfig}async getHoverContent(e,t){let n=e.parseResult?.value?.$cstNode;if(n){let r=e.textDocument.offsetAt(t.position),i=findDeclarationNodeAtOffset(n,r,this.grammarConfig.nameRegexp);if(i&&i.offset+i.length>r){let e=[],t=this.references.findDeclarations(i);for(let n of t){let t=await this.getAstNodeHoverContent(n);typeof t==`string`&&e.push(t)}if(e.length>0)return{contents:{kind:`markdown`,value:e.join(` `)}};if(isKeyword(i.grammarSource))return this.getKeywordHoverContent(i.grammarSource)}}}getKeywordHoverContent(e){let t=isAstNodeWithComment(e)?e.$comment:void 0;if(t||=findCommentNode(e.$cstNode,[`ML_COMMENT`])?.text,t&&isJSDoc(t)){let e=parseJSDoc(t).toMarkdown();if(e)return{contents:{kind:`markdown`,value:e}}}}},MultilineCommentHoverProvider=class extends AstNodeHoverProvider{constructor(e){super(e),this.documentationProvider=e.documentation.DocumentationProvider}getAstNodeHoverContent(e){let t=this.documentationProvider.getDocumentation(e);if(t)return t}};const Ft={[v.class]:0,[v.comment]:1,[v.enum]:2,[v.enumMember]:3,[v.event]:4,[v.function]:5,[v.interface]:6,[v.keyword]:7,[v.macro]:8,[v.method]:9,[v.modifier]:10,[v.namespace]:11,[v.number]:12,[v.operator]:13,[v.parameter]:14,[v.property]:15,[v.regexp]:16,[v.string]:17,[v.struct]:18,[v.type]:19,[v.typeParameter]:20,[v.variable]:21,[v.decorator]:22},It={[_.abstract]:1,[_.async]:2,[_.declaration]:4,[_.defaultLibrary]:8,[_.definition]:16,[_.deprecated]:32,[_.documentation]:64,[_.modification]:128,[_.readonly]:256,[_.static]:512};Object.keys(Ft),Object.keys(It);function mergeSemanticTokenProviderOptions(e){let t=[],n=[],r=!0,i=!0,a=!0;for(let o of e)o&&(o.legend.tokenTypes.forEach((e,n)=>{let r=t[n];if(r&&r!==e)throw Error(`Cannot merge '${r}' and '${e}' token types. They use the same index ${n}.`);t[n]=e}),o.legend.tokenModifiers.forEach((e,t)=>{let r=n[t];if(r&&r!==e)throw Error(`Cannot merge '${r}' and '${e}' token modifier. They use the same index ${t}.`);n[t]=e}),o.full?typeof o.full==`object`&&!o.full.delta&&(i=!1):r=!1,o.range||(a=!1));return{legend:{tokenTypes:t,tokenModifiers:n},full:r&&{delta:i},range:a}}var SemanticTokensBuilder$1=class extends ce{static{e(this,`SemanticTokensBuilder`)}constructor(){super(...arguments),this._tokens=[]}push(e,t,n,r,i){this._tokens.push({line:e,char:t,length:n,tokenType:r,tokenModifiers:i})}build(){return this.applyTokens(),super.build()}buildEdits(){return this.applyTokens(),super.buildEdits()}flush(){this.previousResult(this.id)}applyTokens(){for(let e of this._tokens.sort(this.compareTokens))super.push(e.line,e.char,e.length,e.tokenType,e.tokenModifiers);this._tokens=[]}compareTokens(e,t){return e.line-t.line||e.char-t.char}},AbstractSemanticTokenProvider=class{constructor(e){this.tokensBuilders=/* @__PURE__ */ new Map,e.shared.workspace.TextDocuments.onDidClose(e=>{this.tokensBuilders.delete(e.document.uri)}),e.shared.lsp.LanguageServer.onInitialize(e=>{this.initialize(e.capabilities.textDocument?.semanticTokens)})}initialize(e){this.clientCapabilities=e}get tokenTypes(){return Ft}get tokenModifiers(){return It}get semanticTokensOptions(){return{legend:{tokenTypes:Object.keys(this.tokenTypes),tokenModifiers:Object.keys(this.tokenModifiers)},full:{delta:!1},range:!0}}async semanticHighlight(e,t,n=b.None){return this.currentRange=void 0,this.currentDocument=e,this.currentTokensBuilder=this.getDocumentTokensBuilder(e),this.currentTokensBuilder.flush(),await this.computeHighlighting(e,this.createAcceptor(),n),this.currentTokensBuilder.build()}async semanticHighlightRange(e,t,n=b.None){return this.currentRange=t.range,this.currentDocument=e,this.currentTokensBuilder=this.getDocumentTokensBuilder(e),this.currentTokensBuilder.flush(),await this.computeHighlighting(e,this.createAcceptor(),n),this.currentTokensBuilder.build()}async semanticHighlightDelta(e,t,n=b.None){return this.currentRange=void 0,this.currentDocument=e,this.currentTokensBuilder=this.getDocumentTokensBuilder(e),this.currentTokensBuilder.previousResult(t.previousResultId),await this.computeHighlighting(e,this.createAcceptor(),n),this.currentTokensBuilder.buildEdits()}createAcceptor(){let acceptor=e=>{`line`in e?this.highlightToken({range:{start:{line:e.line,character:e.char},end:{line:e.line,character:e.char+e.length}},type:e.type,modifier:e.modifier}):`range`in e?this.highlightToken(e):`keyword`in e?this.highlightKeyword(e):`property`in e?this.highlightProperty(e):this.highlightNode({node:e.cst,type:e.type,modifier:e.modifier})};return acceptor}getDocumentTokensBuilder(e){let t=this.tokensBuilders.get(e.uri.toString());if(t)return t;let n=new SemanticTokensBuilder$1;return this.tokensBuilders.set(e.uri.toString(),n),n}async computeHighlighting(e,t,n){let r=e.parseResult.value,i=streamAst(r,{range:this.currentRange}).iterator(),a;do if(a=i.next(),!a.done){await interruptAndCheck(n);let e=a.value;this.highlightElement(e,t)===`prune`&&i.prune()}while(!a.done)}highlightToken(e){let{range:t,type:n}=e,r=e.modifier;if(this.currentRange&&!inRange(t,this.currentRange)||!this.currentDocument||!this.currentTokensBuilder)return;let i=this.tokenTypes[n],a=0;if(r!==void 0){typeof r==`string`&&(r=[r]);for(let e of r){let t=this.tokenModifiers[e];a|=t}}let o=t.start.line,s=t.end.line;if(o===s){let e=t.start.character,n=t.end.character-e;this.currentTokensBuilder.push(o,e,n,i,a)}else if(this.clientCapabilities?.multilineTokenSupport){let e=t.start.character,n=this.currentDocument.textDocument.offsetAt(t.start),r=this.currentDocument.textDocument.offsetAt(t.end);this.currentTokensBuilder.push(o,e,r-n,i,a)}else{let e=t.start,n=this.currentDocument.textDocument.offsetAt({line:o+1,character:0});this.currentTokensBuilder.push(e.line,e.character,n-e.character-1,i,a);for(let e=o+1;e<s;e++){let t=n;n=this.currentDocument.textDocument.offsetAt({line:e+1,character:0}),this.currentTokensBuilder.push(e,0,n-t-1,i,a)}this.currentTokensBuilder.push(s,0,t.end.character,i,a)}}highlightProperty(e){let t=[];if(typeof e.index==`number`){let n=findNodeForProperty(e.node.$cstNode,e.property,e.index);n&&t.push(n)}else t.push(...findNodesForProperty(e.node.$cstNode,e.property));let{type:n,modifier:r}=e;for(let e of t)this.highlightNode({node:e,type:n,modifier:r})}highlightKeyword(e){let{node:t,keyword:n,type:r,index:i,modifier:a}=e,o=[];if(typeof i==`number`){let e=findNodeForKeyword(t.$cstNode,n,i);e&&o.push(e)}else o.push(...findNodesForKeyword(t.$cstNode,n));for(let e of o)this.highlightNode({node:e,type:r,modifier:a})}highlightNode(e){let{node:t,type:n,modifier:r}=e,i=t.range;this.highlightToken({range:i,type:n,modifier:r})}},Lt;(function(e){function decode(e,t,n){let r=/* @__PURE__ */ new Map;Object.entries(t).forEach(([e,t])=>r.set(t,e));let i=0,a=0;return sliceIntoChunks(e.data,5).map(e=>{i+=e[0],e[0]!==0&&(a=0),a+=e[1];let t=e[2];return{offset:n.textDocument.offsetAt({line:i,character:a}),tokenType:r.get(e[3]),tokenModifiers:e[4],text:n.textDocument.getText({start:{line:i,character:a},end:{line:i,character:a+t}})}})}e.decode=decode;function sliceIntoChunks(e,t){let n=[];for(let r=0;r<e.length;r+=t){let i=e.slice(r,r+t);n.push(i)}return n}})(Lt||={});function mergeSignatureHelpOptions(e){let t=[],n=[];e.forEach(e=>{e?.triggerCharacters&&t.push(...e.triggerCharacters),e?.retriggerCharacters&&n.push(...e.retriggerCharacters)});let r={triggerCharacters:t.length>0?Array.from(new Set(t)).sort():void 0,retriggerCharacters:n.length>0?Array.from(new Set(n)).sort():void 0};return r.triggerCharacters?r:void 0}var DefaultLanguageServer=class{constructor(e){this.onInitializeEmitter=new he,this.onInitializedEmitter=new he,this.services=e}get onInitialize(){return this.onInitializeEmitter.event}get onInitialized(){return this.onInitializedEmitter.event}async initialize(e){return this.eagerLoadServices(),this.fireInitializeOnDefaultServices(e),this.onInitializeEmitter.fire(e),this.onInitializeEmitter.dispose(),this.buildInitializeResult(e)}eagerLoadServices(){eagerLoad(this.services),this.services.ServiceRegistry.all.forEach(e=>eagerLoad(e))}hasService(e){return this.services.ServiceRegistry.all.some(t=>e(t)!==void 0)}buildInitializeResult(e){let t=this.services.lsp.DocumentUpdateHandler,n=this.services.lsp.FileOperationHandler?.fileOperationOptions,r=this.services.ServiceRegistry.all,i=this.hasService(e=>e.lsp?.Formatter),a=r.map(e=>e.lsp?.Formatter?.formatOnTypeOptions).find(e=>!!e),o=this.hasService(e=>e.lsp?.CodeActionProvider),s=this.hasService(e=>e.lsp?.SemanticTokenProvider),c=mergeSemanticTokenProviderOptions(r.map(e=>e.lsp?.SemanticTokenProvider?.semanticTokensOptions)),l=this.services.lsp?.ExecuteCommandHandler?.commands,u=this.hasService(e=>e.lsp?.DocumentLinkProvider),d=mergeSignatureHelpOptions(r.map(e=>e.lsp?.SignatureHelp?.signatureHelpOptions)),f=this.hasService(e=>e.lsp?.TypeProvider),p=this.hasService(e=>e.lsp?.ImplementationProvider),m=this.hasService(e=>e.lsp?.CompletionProvider),ee=mergeCompletionProviderOptions(r.map(e=>e.lsp?.CompletionProvider?.completionOptions)),h=this.hasService(e=>e.lsp?.ReferencesProvider),te=this.hasService(e=>e.lsp?.DocumentSymbolProvider),g=this.hasService(e=>e.lsp?.DefinitionProvider),ne=this.hasService(e=>e.lsp?.DocumentHighlightProvider),re=this.hasService(e=>e.lsp?.FoldingRangeProvider),ie=this.hasService(e=>e.lsp?.HoverProvider),ae=this.hasService(e=>e.lsp?.RenameProvider),oe=this.hasService(e=>e.lsp?.CallHierarchyProvider),se=this.hasService(e=>e.lsp?.TypeHierarchyProvider),_=this.hasService(e=>e.lsp?.CodeLensProvider),v=this.hasService(e=>e.lsp?.DeclarationProvider),ce=this.hasService(e=>e.lsp?.InlayHintProvider),le=this.services.lsp?.WorkspaceSymbolProvider,ue=this.services.lsp?.TextDocumentContentProvider?.schemes;return{capabilities:{workspace:{workspaceFolders:{supported:!0},fileOperations:n,textDocumentContent:ue?{schemes:ue}:void 0},executeCommandProvider:l&&{commands:l},textDocumentSync:{change:ye.Incremental,openClose:!0,save:!!t.didSaveDocument,willSave:!!t.willSaveDocument,willSaveWaitUntil:!!t.willSaveDocumentWaitUntil},completionProvider:m?ee:void 0,referencesProvider:h,documentSymbolProvider:te,definitionProvider:g,typeDefinitionProvider:f,documentHighlightProvider:ne,codeActionProvider:o,documentFormattingProvider:i,documentRangeFormattingProvider:i,documentOnTypeFormattingProvider:a,foldingRangeProvider:re,hoverProvider:ie,renameProvider:ae?{prepareProvider:!0}:void 0,semanticTokensProvider:s?c:void 0,signatureHelpProvider:d,implementationProvider:p,callHierarchyProvider:oe?{}:void 0,typeHierarchyProvider:se?{}:void 0,documentLinkProvider:u?{resolveProvider:!1}:void 0,codeLensProvider:_?{resolveProvider:!1}:void 0,declarationProvider:v,inlayHintProvider:ce?{resolveProvider:!1}:void 0,workspaceSymbolProvider:le?{resolveProvider:!!le.resolveSymbol}:void 0}}}initialized(e){this.fireInitializedOnDefaultServices(e),this.onInitializedEmitter.fire(e),this.onInitializedEmitter.dispose()}fireInitializeOnDefaultServices(e){this.services.workspace.ConfigurationProvider.initialize(e),this.services.workspace.WorkspaceManager.initialize(e)}fireInitializedOnDefaultServices(e){let t=this.services.lsp.Connection,n=t?{...e,register:e=>t.client.register(me.type,e),fetchConfiguration:e=>t.workspace.getConfiguration(e)}:e;this.services.workspace.ConfigurationProvider.initialized(n).catch(e=>console.error(`Error in ConfigurationProvider initialization:`,e)),this.services.workspace.WorkspaceManager.initialized(e).catch(e=>console.error(`Error in WorkspaceManager initialization:`,e))}},Rt;(function(e){e.Parsed=Object.freeze({type:`workspace`,state:X.Parsed}),e.IndexedContent=Object.freeze({type:`workspace`,state:X.IndexedContent}),e.ComputedScopes=Object.freeze({type:`workspace`,state:X.ComputedScopes}),e.Linked=Object.freeze({type:`workspace`,state:X.Linked}),e.IndexedReferences=Object.freeze({type:`workspace`,state:X.IndexedReferences}),e.Validated=Object.freeze({type:`workspace`,state:X.Validated})})(Rt||={});var DefaultNodeKindProvider=class{getSymbolKind(e){return le.Field}getCompletionItemKind(e){return p.Reference}},DefaultReferencesProvider=class{constructor(e){this.nameProvider=e.references.NameProvider,this.references=e.references.References,this.grammarConfig=e.parser.GrammarConfig}findReferences(e,t,n){let r=e.parseResult.value.$cstNode;if(!r)return[];let i=findDeclarationNodeAtOffset(r,e.textDocument.offsetAt(t.position),this.grammarConfig.nameRegexp);return i?this.getReferences(i,t,e):[]}getReferences(e,t,n){let r=[],i=this.references.findDeclarations(e);for(let e of i){let n={includeDeclaration:t.context.includeDeclaration};this.references.findReferences(e,n).forEach(e=>{r.push(ae.create(e.sourceUri.toString(),e.segment.range))})}return r}},DefaultRenameProvider=class{constructor(e){this.references=e.references.References,this.nameProvider=e.references.NameProvider,this.grammarConfig=e.parser.GrammarConfig}async rename(e,t,n){let r={},i=e.parseResult.value.$cstNode;if(!i)return;let a=findDeclarationNodeAtOffset(i,e.textDocument.offsetAt(t.position),this.grammarConfig.nameRegexp);if(!a)return;let o=this.references.findDeclarations(a);if(o.length===0)return;let s=o[0],c=this.references.findReferences(s,{onlyLocal:!1,includeDeclaration:!0});for(let e of c){let n=xe.replace(e.segment.range,t.newName),i=e.sourceUri.toString();r[i]?r[i].push(n):r[i]=[n]}return{changes:r}}prepareRename(e,t,n){return this.renameNodeRange(e,t.position)}renameNodeRange(e,t){let n=e.parseResult.value.$cstNode,r=e.textDocument.offsetAt(t);if(n){let e=findDeclarationNodeAtOffset(n,r,this.grammarConfig.nameRegexp);if(!e)return;if(this.references.findDeclarations(e).length>0||this.isNameNode(e))return e.range}}isNameNode(e){return e?.astNode&&isNamed(e.astNode)&&e===this.nameProvider.getNameNode(e.astNode)}},DefaultWorkspaceSymbolProvider=class{constructor(e){this.indexManager=e.workspace.IndexManager,this.nodeKindProvider=e.lsp.NodeKindProvider,this.fuzzyMatcher=e.lsp.FuzzyMatcher}async getSymbols(e,t=b.None){let n=[],r=e.query.toLowerCase();for(let e of this.indexManager.allElements())if(await interruptAndCheck(t),this.fuzzyMatcher.match(r,e.name)){let t=this.getWorkspaceSymbol(e);t&&n.push(t)}return n}getWorkspaceSymbol(e){let t=e.nameSegment;if(t)return{kind:this.nodeKindProvider.getSymbolKind(e),name:e.name,location:{range:t.range,uri:e.documentUri.toString()}}}},NormalizedTextDocuments=class{constructor(e){this._configuration=e,this._syncedDocuments=/* @__PURE__ */ new Map,this._onDidChangeContent=new g,this._onDidOpen=new g,this._onDidClose=new g,this._onDidSave=new g,this._onWillSave=new g}get onDidOpen(){return this._onDidOpen.event}get onDidChangeContent(){return this._onDidChangeContent.event}get onWillSave(){return this._onWillSave.event}onWillSaveWaitUntil(e){this._willSaveWaitUntil=e}get onDidSave(){return this._onDidSave.event}get onDidClose(){return this._onDidClose.event}get(e){return this._syncedDocuments.get(J.normalize(e))}set(e){let t=J.normalize(e.uri),n=!0;this._syncedDocuments.has(t)&&(n=!1),this._syncedDocuments.set(t,e);let r=Object.freeze({document:e});return this._onDidOpen.fire(r),this._onDidChangeContent.fire(r),n}delete(e){let t=J.normalize(typeof e==`object`&&`uri`in e?e.uri:e),n=this._syncedDocuments.get(t);n!==void 0&&(this._syncedDocuments.delete(t),this._onDidClose.fire(Object.freeze({document:n})))}all(){return Array.from(this._syncedDocuments.values())}keys(){return Array.from(this._syncedDocuments.keys())}listen(e){e.__textDocumentSync=ue.Incremental;let t=[];return t.push(e.onDidOpenTextDocument(e=>{let t=e.textDocument,n=J.normalize(t.uri),r=this._configuration.create(n,t.languageId,t.version,t.text);this._syncedDocuments.set(n,r);let i=Object.freeze({document:r});this._onDidOpen.fire(i),this._onDidChangeContent.fire(i)})),t.push(e.onDidChangeTextDocument(e=>{let t=e.textDocument,n=e.contentChanges;if(n.length===0)return;let{version:r}=t;if(r==null)throw Error(`Received document change event for ${t.uri} without valid version identifier`);let i=J.normalize(t.uri),a=this._syncedDocuments.get(i);a!==void 0&&(a=this._configuration.update(a,n,r),this._syncedDocuments.set(i,a),this._onDidChangeContent.fire(Object.freeze({document:a})))})),t.push(e.onDidCloseTextDocument(e=>{let t=J.normalize(e.textDocument.uri),n=this._syncedDocuments.get(t);n!==void 0&&(this._syncedDocuments.delete(t),this._onDidClose.fire(Object.freeze({document:n})))})),t.push(e.onWillSaveTextDocument(e=>{let t=this._syncedDocuments.get(J.normalize(e.textDocument.uri));t!==void 0&&this._onWillSave.fire(Object.freeze({document:t,reason:e.reason}))})),t.push(e.onWillSaveTextDocumentWaitUntil((e,t)=>{let n=this._syncedDocuments.get(J.normalize(e.textDocument.uri));return n!==void 0&&this._willSaveWaitUntil?this._willSaveWaitUntil(Object.freeze({document:n,reason:e.reason}),t):[]})),t.push(e.onDidSaveTextDocument(e=>{let t=this._syncedDocuments.get(J.normalize(e.textDocument.uri));t!==void 0&&this._onDidSave.fire(Object.freeze({document:t}))})),h.create(()=>{t.forEach(e=>e.dispose())})}},NormalizedNotebookDocuments=class{constructor(e){this.notebookDocuments=/* @__PURE__ */ new Map,this.notebookCellMap=/* @__PURE__ */ new Map,this._onDidOpen=new g,this._onDidSave=new g,this._onDidChange=new g,this._onDidClose=new g,this._cellTextDocuments=`listen`in e?e:new NormalizedTextDocuments(e)}get cellTextDocuments(){return this._cellTextDocuments}getCellTextDocument(e){return this._cellTextDocuments.get(e.document)}getNotebookDocument(e){return this.notebookDocuments.get(J.normalize(e))}getNotebookCell(e){let t=this.notebookCellMap.get(J.normalize(e));return t&&t[0]}findNotebookDocumentForCell(e){let t=typeof e==`string`||`scheme`in e?e:e.document,n=this.notebookCellMap.get(J.normalize(t));return n&&n[1]}get onDidOpen(){return this._onDidOpen.event}get onDidSave(){return this._onDidSave.event}get onDidChange(){return this._onDidChange.event}get onDidClose(){return this._onDidClose.event}listen(e){let t=new zt,n=[];return n.push(this.cellTextDocuments.listen(t)),n.push(e.notebooks.synchronization.onDidOpenNotebookDocument(e=>{let n=J.normalize(e.notebookDocument.uri);this.notebookDocuments.set(n,e.notebookDocument);for(let n of e.cellTextDocuments)t.openTextDocument({textDocument:n});this.updateCellMap(e.notebookDocument),this._onDidOpen.fire(e.notebookDocument)})),n.push(e.notebooks.synchronization.onDidChangeNotebookDocument(e=>{let n=J.normalize(e.notebookDocument.uri),r=this.notebookDocuments.get(n);if(r===void 0)return;r.version=e.notebookDocument.version;let i=r.metadata,a=!1,o=e.change;o.metadata!==void 0&&(a=!0,r.metadata=o.metadata);let s=[],c=[],l=[],u=[];if(o.cells!==void 0){let e=o.cells;if(e.structure!==void 0){let n=e.structure.array;if(r.cells.splice(n.start,n.deleteCount,...n.cells===void 0?[]:n.cells),e.structure.didOpen!==void 0)for(let n of e.structure.didOpen)t.openTextDocument({textDocument:n}),s.push(n.uri);if(e.structure.didClose)for(let n of e.structure.didClose)t.closeTextDocument({textDocument:n}),c.push(n.uri)}if(e.data!==void 0){let t=new Map(e.data.map(e=>[e.document,e]));for(let e=0;e<=r.cells.length;e++){let n=t.get(r.cells[e].document);if(n!==void 0){let i=r.cells.splice(e,1,n);if(l.push({old:i[0],new:n}),t.delete(n.document),t.size===0)break}}}if(e.textContent!==void 0)for(let n of e.textContent)t.changeTextDocument({textDocument:n.document,contentChanges:n.changes}),u.push(n.document.uri)}this.updateCellMap(r);let d={notebookDocument:r};a&&(d.metadata={old:i,new:r.metadata});let f=[];for(let e of s)f.push(this.getNotebookCell(e));let p=[];for(let e of c)p.push(this.getNotebookCell(e));let m=[];for(let e of u)m.push(this.getNotebookCell(e));(f.length>0||p.length>0||l.length>0||m.length>0)&&(d.cells={added:f,removed:p,changed:{data:l,textContent:m}}),(d.metadata!==void 0||d.cells!==void 0)&&this._onDidChange.fire(d)})),n.push(e.notebooks.synchronization.onDidSaveNotebookDocument(e=>{let t=this.getNotebookDocument(e.notebookDocument.uri);t!==void 0&&this._onDidSave.fire(t)})),n.push(e.notebooks.synchronization.onDidCloseNotebookDocument(e=>{let n=J.normalize(e.notebookDocument.uri),r=this.notebookDocuments.get(n);if(r!==void 0){this._onDidClose.fire(r);for(let n of e.cellTextDocuments)t.closeTextDocument({textDocument:n});this.notebookDocuments.delete(n);for(let e of r.cells)this.notebookCellMap.delete(e.document)}})),h.create(()=>{n.forEach(e=>e.dispose())})}updateCellMap(e){for(let t of e.cells)this.notebookCellMap.set(t.document,[t,e])}},zt=class CellTextDocumentConnection{onDidOpenTextDocument(e){return this.openHandler=e,h.create(()=>{this.openHandler=void 0})}openTextDocument(e){this.openHandler&&this.openHandler(e)}onDidChangeTextDocument(e){return this.changeHandler=e,h.create(()=>{this.changeHandler=e})}changeTextDocument(e){this.changeHandler&&this.changeHandler(e)}onDidCloseTextDocument(e){return this.closeHandler=e,h.create(()=>{this.closeHandler=void 0})}closeTextDocument(e){this.closeHandler&&this.closeHandler(e)}onWillSaveTextDocument(){return CellTextDocumentConnection.NULL_DISPOSE}onWillSaveTextDocumentWaitUntil(){return CellTextDocumentConnection.NULL_DISPOSE}onDidSaveTextDocument(){return CellTextDocumentConnection.NULL_DISPOSE}};zt.NULL_DISPOSE=Object.freeze({dispose:()=>{}});function createDefaultModule(e){return ht.merge(createDefaultCoreModule(e),createDefaultLSPModule(e))}function createDefaultLSPModule(e){return{lsp:{CompletionProvider:e=>new DefaultCompletionProvider(e),DocumentSymbolProvider:e=>new DefaultDocumentSymbolProvider(e),HoverProvider:e=>new MultilineCommentHoverProvider(e),FoldingRangeProvider:e=>new DefaultFoldingRangeProvider(e),ReferencesProvider:e=>new DefaultReferencesProvider(e),DefinitionProvider:e=>new DefaultDefinitionProvider(e),DocumentHighlightProvider:e=>new DefaultDocumentHighlightProvider(e),RenameProvider:e=>new DefaultRenameProvider(e)},shared:()=>e.shared}}function createDefaultSharedModule(e){return ht.merge(createDefaultSharedCoreModule(e),createDefaultSharedLSPModule(e))}function createDefaultSharedLSPModule(e){return{lsp:{Connection:()=>e.connection,LanguageServer:e=>new DefaultLanguageServer(e),DocumentUpdateHandler:e=>new DefaultDocumentUpdateHandler(e),WorkspaceSymbolProvider:e=>new DefaultWorkspaceSymbolProvider(e),NodeKindProvider:()=>new DefaultNodeKindProvider,FuzzyMatcher:()=>new DefaultFuzzyMatcher},workspace:{TextDocuments:()=>new NormalizedTextDocuments(be),NotebookDocuments:e=>new NormalizedNotebookDocuments(e.workspace.TextDocuments)}}}var AbstractExecuteCommandHandler=class{get commands(){return Array.from(this.registeredCommands.keys())}constructor(){this.registeredCommands=/* @__PURE__ */ new Map,this.registerCommands(this.createCommandAcceptor())}async executeCommand(e,t,n=b.None){let r=this.registeredCommands.get(e);if(r)return r(t,n)}createCommandAcceptor(){return(e,t)=>this.registeredCommands.set(e,t)}},AbstractFormatter=class{constructor(){this.collector=()=>{}}getNodeFormatter(e){return new DefaultNodeFormatter(e,this.collector)}formatDocument(e,t){let n=e.parseResult;return n.lexerErrors.length===0&&n.parserErrors.length===0?this.doDocumentFormat(e,t.options):[]}isFormatRangeErrorFree(e,t){let n=e.parseResult;return n.lexerErrors.length||n.parserErrors.length?Math.min(...n.lexerErrors.map(e=>e.line??Number.MAX_VALUE),...n.parserErrors.map(e=>e.token.startLine??Number.MAX_VALUE))>t.end.line:!0}formatDocumentRange(e,t){return this.isFormatRangeErrorFree(e,t.range)?this.doDocumentFormat(e,t.options,t.range):[]}formatDocumentOnType(e,t){let n={start:{character:0,line:t.position.line},end:t.position};return this.isFormatRangeErrorFree(e,n)?this.doDocumentFormat(e,t.options,n):[]}get formatOnTypeOptions(){}doDocumentFormat(e,t,n){let r=/* @__PURE__ */ new Map,collector=(e,t,n)=>{let i=this.nodeModeToKey(e,t),a=r.get(i),o=n.options.priority??0,s=a?.options.priority??0;(!a||s<=o)&&r.set(i,n)};this.collector=collector,this.iterateAstFormatting(e,n);let i=this.iterateCstFormatting(e,r,t,n);return this.avoidOverlappingEdits(e.textDocument,i)}avoidOverlappingEdits(e,t){let n=[];for(let r of t){let t=n[n.length-1];for(;t&&e.offsetAt(r.range.start)<e.offsetAt(t.range.end);)n.pop(),t=n[n.length-1];n.push(r)}return n.filter(t=>this.isNecessary(t,e))}iterateAstFormatting(e,t){let n=e.parseResult.value;this.format(n);let r=streamAllContents(n).iterator(),i;do if(i=r.next(),!i.done){let e=i.value;this.insideRange(e.$cstNode.range,t)?this.format(e):r.prune()}while(!i.done)}nodeModeToKey(e,t){return`${e.offset}:${e.end}:${t}`}insideRange(e,t){return!t||e.start.line<=t.start.line&&e.end.line>=t.end.line||e.start.line>=t.start.line&&e.end.line<=t.end.line||e.start.line<=t.end.line&&e.end.line>=t.end.line}isNecessary(e,t){return e.newText!==t.getText(e.range).replace(/\r/g,``)}iterateCstFormatting(e,t,n,r){let i={indentation:0,options:n,document:e.textDocument},a=[],o=this.iterateCstTree(e,i).iterator(),s,c;do if(c=o.next(),!c.done){let e=c.value,n=isLeafCstNode(e),o=this.nodeModeToKey(e,`prepend`),l=t.get(o);if(t.delete(o),l){let t=this.createTextEdit(s,e,l,i);for(let e of t)e&&this.insideRange(e.range,r)&&a.push(e)}let u=this.nodeModeToKey(e,`append`),d=t.get(u);if(t.delete(u),d){let t=getNextNode(e);if(t){let n=this.createTextEdit(e,t,d,i);for(let e of n)e&&this.insideRange(e.range,r)&&a.push(e)}}if(!l&&e.hidden){let t=this.createHiddenTextEdits(s,e,void 0,i);for(let e of t)e&&this.insideRange(e.range,r)&&a.push(e)}n&&(s=e)}while(!c.done);return a}createHiddenTextEdits(e,t,n,r){let i=t.range.start,a=i.line;if(e&&e.range.end.line===a)return[];let o=[],s={start:{character:0,line:a},end:i},c=r.document.getText(s),l=this.findFittingMove(s,n?.moves??[],r),u=this.getExistingIndentationCharacterCount(c,r),d=this.getIndentationCharacterCount(r,l)-u;if(d===0)return[];let f=``;d>0&&(f=(r.options.insertSpaces?` `:` `).repeat(d));let p=t.text.split(`
12
12
  `);p[0]=c+p[0];for(let e=0;e<p.length;e++){let t=a+e,n={character:0,line:t};if(d>0)o.push({newText:f,range:{start:n,end:n}});else{let r=p[e],i=0;for(;i<r.length;i++){let e=r.charAt(i);if(e!==` `&&e!==` `)break}o.push({newText:``,range:{start:n,end:{line:t,character:Math.min(i,Math.abs(d))}}})}}return o}getExistingIndentationCharacterCount(e,t){let n=` `.repeat(t.options.tabSize),r=``,i;return t.options.insertSpaces?(i=/* @__PURE__ */ RegExp(`\\t`,`g`),r=n):(i=new RegExp(n,`g`),r=` `),e.replace(i,r).length}getIndentationCharacterCount(e,t){let n=e.indentation;return t&&t.tabs&&(n+=t.tabs),(e.options.insertSpaces?e.options.tabSize:1)*n}createTextEdit(e,t,n,r){if(t.hidden)return this.createHiddenTextEdits(e,t,n,r);let i=e?.range.end,a=t.range.start;if(i&&(i.line>a.line||i.line===a.line&&i.character>a.character))return[];let o={start:i??{character:0,line:0},end:a},s=this.findFittingMove(o,n.moves,r);if(!s)return[];let c=s.characters,l=s.lines,u=s.tabs,d=r.indentation;r.indentation+=u??0;let f=[];return c===void 0?l===void 0?u!==void 0&&f.push(this.createTabTextEdit(o,!!e,r)):f.push(this.createLineTextEdit(o,l,r,n.options)):e?.hidden||f.push(this.createSpaceTextEdit(o,c,n.options)),isLeafCstNode(t)&&(r.indentation=d),f}createSpaceTextEdit(e,t,n){if(e.start.line===e.end.line){let r=e.end.character-e.start.character;t=this.fitIntoOptions(t,r,n)}return{newText:` `.repeat(t),range:e}}createLineTextEdit(e,t,n,r){let i=e.end.line-e.start.line;t=this.fitIntoOptions(t,i,r);let a=(n.options.insertSpaces?` `.repeat(n.options.tabSize):` `).repeat(n.indentation);return{newText:`${`
13
13
  `.repeat(t)}${a}`,range:e}}createTabTextEdit(e,t,n){let r=(n.options.insertSpaces?` `.repeat(n.options.tabSize):` `).repeat(n.indentation),i=+!!t,a=Math.max(e.end.line-e.start.line,i);return{newText:`${`
14
14
  `.repeat(a)}${r}`,range:e}}fitIntoOptions(e,t,n){return n.allowMore?e=Math.max(t,e):n.allowLess&&(e=Math.min(t,e)),e}findFittingMove(e,t,n){if(t.length===0)return;if(t.length===1)return t[0];let r=e.end.line-e.start.line;for(let e of t)if(e.lines!==void 0&&r<=e.lines)return e;else if(e.lines===void 0&&r===0)return e;return t[t.length-1]}iterateCstTree(e,t){let n=e.parseResult.value.$cstNode;return n?new TreeStreamImpl(n,e=>this.iterateCst(e,t)):G}iterateCst(e,t){if(!isCompositeCstNode(e))return G;let n=t.indentation;return new W(()=>({index:0}),r=>r.index<e.content.length?{done:!1,value:e.content[r.index++]}:(t.indentation=n,K))}},DefaultNodeFormatter=class{constructor(e,t){this.astNode=e,this.collector=t}node(e){return new Q(e.$cstNode?[e.$cstNode]:[],this.collector)}nodes(...e){let t=[];for(let n of e)n.$cstNode&&t.push(n.$cstNode);return new Q(t,this.collector)}property(e,t){let n=findNodeForProperty(this.astNode.$cstNode,e,t);return new Q(n?[n]:[],this.collector)}properties(...e){let t=[];for(let n of e){let e=findNodesForProperty(this.astNode.$cstNode,n);t.push(...e)}return new Q(t,this.collector)}keyword(e,t){let n=findNodeForKeyword(this.astNode.$cstNode,e,t);return new Q(n?[n]:[],this.collector)}keywords(...e){let t=[];for(let n of e){let e=findNodesForKeyword(this.astNode.$cstNode,n);t.push(...e)}return new Q(t,this.collector)}cst(e){return new Q([...e],this.collector)}interior(e,t){let n=e.nodes,r=t.nodes;if(n.length!==1||r.length!==1)return new Q([],this.collector);let i=n[0],a=r[0];if(i.offset>a.offset){let e=i;i=a,a=e}return new Q(getInteriorNodes(i,a),this.collector)}},Q=class FormattingRegion{constructor(e,t){this.nodes=e,this.collector=t}prepend(e){for(let t of this.nodes)this.collector(t,`prepend`,e);return this}append(e){for(let t of this.nodes)this.collector(t,`append`,e);return this}surround(e){for(let t of this.nodes)this.collector(t,`prepend`,e),this.collector(t,`append`,e);return this}slice(e,t){return new FormattingRegion(this.nodes.slice(e,t),this.collector)}},Bt;(function(e){function fit(...e){return{options:{},moves:e.flatMap(e=>e.moves).sort(compareMoves)}}e.fit=fit;function noSpace(e){return spaces(0,e)}e.noSpace=noSpace;function oneSpace(e){return spaces(1,e)}e.oneSpace=oneSpace;function spaces(e,t){return{options:t??{},moves:[{characters:e}]}}e.spaces=spaces;function newLine(e){return newLines(1,e)}e.newLine=newLine;function newLines(e,t){return{options:t??{},moves:[{lines:e}]}}e.newLines=newLines;function indent(e){return{options:e??{},moves:[{tabs:1,lines:1}]}}e.indent=indent;function noIndent(e){return{options:e??{},moves:[{tabs:0}]}}e.noIndent=noIndent;function compareMoves(e,t){let n=e.lines??0,r=t.lines??0,i=e.tabs??0,a=t.tabs??0,o=e.characters??0,s=t.characters??0;return n<r?-1:n>r?1:i<a?-1:i>a?1:o<s?-1:+(o>s)}})(Bt||={});var NodeFileSystemProvider=class{constructor(){this.encoding=`utf-8`}async stat(e){let t=await f.promises.stat(e.fsPath);return{isFile:t.isFile(),isDirectory:t.isDirectory(),uri:e}}statSync(e){let t=f.statSync(e.fsPath);return{isFile:t.isFile(),isDirectory:t.isDirectory(),uri:e}}exists(e){return new Promise(t=>{f.stat(e.fsPath,e=>{t(!e)})})}existsSync(e){return f.existsSync(e.fsPath)}readBinary(e){return f.promises.readFile(e.fsPath)}readBinarySync(e){return f.readFileSync(e.fsPath)}readFile(e){return f.promises.readFile(e.fsPath,this.encoding)}readFileSync(e){return f.readFileSync(e.fsPath,this.encoding)}async readDirectory(e){return(await f.promises.readdir(e.fsPath,{withFileTypes:!0})).map(t=>({dirent:t,isFile:t.isFile(),isDirectory:t.isDirectory(),uri:J.joinPath(e,t.name)}))}readDirectorySync(e){return f.readdirSync(e.fsPath,{withFileTypes:!0}).map(t=>({dirent:t,isFile:t.isFile(),isDirectory:t.isDirectory(),uri:J.joinPath(e,t.name)}))}};function getSourceRegion(e){if(e){if(`astNode`in e)return getSourceRegionOfAstNode(e);if(Array.isArray(e))return e.reduce(mergeDocumentSegment,void 0);{let t=e;return copyDocumentSegment(t,isCstNode(t)?getDocumentURIOrUndefined(t?.root?.astNode??t?.astNode):void 0)}}}function isCstNode(e){return e!==void 0&&`element`in e&&`text`in e}function getDocumentURIOrUndefined(e){try{return getDocument(e).uri.toString()}catch{return}}function getSourceRegionOfAstNode(e){let{astNode:t,property:n,index:r}=e??{},i=t?.$cstNode??t?.$textRegion;if(t!==void 0&&i!==void 0){if(n===void 0)return copyDocumentSegment(i,getDocumentURI(t));{let getSingleOrCompoundRegion=e=>r!==void 0&&r>-1&&Array.isArray(t[n])?r<e.length?e[r]:void 0:e.reduce(mergeDocumentSegment,void 0);if(i.assignments?.[n]){let e=getSingleOrCompoundRegion(i.assignments[n]);return e&&copyDocumentSegment(e,getDocumentURI(t))}if(t.$cstNode){let e=getSingleOrCompoundRegion(findNodesForProperty(t.$cstNode,n));return e&&copyDocumentSegment(e,getDocumentURI(t))}return}}}function getDocumentURI(e){if(e.$cstNode)return getDocument(e)?.uri?.toString();if(e.$textRegion)return e.$textRegion.documentURI||new TreeStreamImpl(e,e=>e.$container?[e.$container]:[]).find(e=>e.$textRegion?.documentURI)?.$textRegion?.documentURI}function copyDocumentSegment(e,t){let n={offset:e.offset,end:e.end??e.offset+e.length,length:e.length??e.end-e.offset};return e.range&&(n.range=e.range),t??=e.fileURI,t&&(n.fileURI=t),n}function mergeDocumentSegment(e,t){if(!e)return t&&copyDocumentSegment(t);if(!t)return e&&copyDocumentSegment(e);let n=e.end??e.offset+e.length,r=t.end??t.offset+t.length,i=Math.min(e.offset,t.offset),a=Math.max(n,r),o={offset:i,end:a,length:a-i};if(e.range&&t.range&&(o.range={start:t.range.start.line<e.range.start.line||t.range.start.line===e.range.start.line&&t.range.start.character<e.range.start.character?t.range.start:e.range.start,end:t.range.end.line>e.range.end.line||t.range.end.line===e.range.end.line&&t.range.end.character>e.range.end.character?t.range.end:e.range.end}),e.fileURI||t.fileURI){let n=e.fileURI,r=t.fileURI;o.fileURI=n&&r&&n!==r?`<unmergable text regions of ${n}, ${r}>`:n??r}return o}var Context=class{constructor(e){this.defaultIndentation=` `,this.pendingIndent=!0,this.currentIndents=[],this.recentNonImmediateIndents=[],this.traceData=[],this.lines=[[]],this.length=0,typeof e==`string`?this.defaultIndentation=e:typeof e==`number`&&(this.defaultIndentation=``.padStart(e))}get content(){return this.lines.map(e=>e.join(``)).join(``)}get contentLength(){return this.length}get currentLineNumber(){return this.lines.length-1}get currentLineContent(){return this.lines[this.currentLineNumber].join(``)}get currentPosition(){return{offset:this.contentLength,line:this.currentLineNumber,character:this.currentLineContent.length}}append(e,t){if(e.length>0){let n=t&&this.currentPosition;this.lines[this.currentLineNumber].push(e),this.length+=e.length,n&&this.indentPendingTraceRegions(n)}}indentPendingTraceRegions(e){for(let t=this.traceData.length-1;t>=0;t--){let n=this.traceData[t];n.targetStart&&n.targetStart.offset===e.offset&&(n.targetStart=this.currentPosition)}}increaseIndent(e){this.currentIndents.push(e),e.indentImmediately||this.recentNonImmediateIndents.push(e)}decreaseIndent(){this.currentIndents.pop()}get relevantIndents(){return this.currentIndents.filter(e=>!this.recentNonImmediateIndents.includes(e))}resetCurrentLine(){this.length-=this.lines[this.currentLineNumber].join(``).length,this.lines[this.currentLineNumber]=[],this.pendingIndent=!0,this.recentNonImmediateIndents.length=0}addNewLine(){this.lines.push([]),this.pendingIndent=!0,this.recentNonImmediateIndents.length=0}pushTraceRegion(e){let t=createTraceRegion(e,this.currentPosition,e=>this.traceData[this.traceData.length-1]?.children?.push(e));return this.traceData.push(t),t}popTraceRegion(e){let t=this.traceData.pop();return this.assertTrue(t===e,`Trace region mismatch!`),t}getParentTraceSourceFileURI(){for(let e=this.traceData.length-1;e>-1;e--){let t=this.traceData[e].sourceRegion?.fileURI;if(t)return t}}assertTrue(e,t){if(!e)throw Error(t)}};function createTraceRegion(e,t,n){let r={sourceRegion:e,targetRegion:void 0,children:[],targetStart:t,complete:e=>(r.targetRegion={offset:r.targetStart.offset,end:e.offset,length:e.offset-r.targetStart.offset,range:{start:{line:r.targetStart.line,character:r.targetStart.character},end:{line:e.line,character:e.character}}},delete r.targetStart,r.children?.length===0&&delete r.children,r.targetRegion?.length&&n(r),delete r.complete,r)};return r}function processGeneratorNode(e,t){let n=new Context(t),r=n.pushTraceRegion(void 0);processNodeInternal(e,n),n.popTraceRegion(r),r.complete&&r.complete(n.currentPosition);let i=r.children&&r.children.length===1?r.children[0]:void 0,a=i?.targetRegion,o=r.targetRegion;return a&&i.sourceRegion&&a.offset===o.offset&&a.length===o.length?{text:n.content,trace:i}:{text:n.content,trace:r}}function processNodeInternal(e,t){typeof e==`string`?processStringNode(e,t):e instanceof IndentNode?processIndentNode(e,t):e instanceof $?processCompositeNode(e,t):e instanceof NewLineNode&&processNewLineNode(e,t)}function hasContent(e,t){return typeof e==`string`?e.length!==0:e instanceof $?e.contents.some(e=>hasContent(e,t)):e instanceof NewLineNode&&!(e.ifNotEmpty&&t.currentLineContent.length===0)}function processStringNode(e,t){e&&(handlePendingIndent(t,!1),t.append(e))}function handlePendingIndent(e,t){if(e.pendingIndent){let n=``;for(let r of e.relevantIndents.filter(e=>e.indentEmptyLines||!t))n+=r.indentation??e.defaultIndentation;e.append(n,!0),e.pendingIndent=!1}}function processCompositeNode(e,t){let n,r=getSourceRegion(e.tracedSource);r&&(n=t.pushTraceRegion(r));for(let n of e.contents)processNodeInternal(n,t);if(n){t.popTraceRegion(n);let e=t.getParentTraceSourceFileURI();e&&r?.fileURI===e&&delete r.fileURI,n.complete&&n.complete(t.currentPosition)}}function processIndentNode(e,t){if(hasContent(e,t)){e.indentImmediately&&!t.pendingIndent&&t.append(e.indentation??t.defaultIndentation,!0);try{t.increaseIndent(e),processCompositeNode(e,t)}finally{t.decreaseIndent()}}}function processNewLineNode(e,t){if(e.ifNotEmpty&&!hasNonWhitespace(t.currentLineContent))t.resetCurrentLine();else{handlePendingIndent(t,!0);let n=e.count;for(;n-->0;)t.append(e.lineDelimiter),t.addNewLine()}}function hasNonWhitespace(e){return e.trimStart()!==``}Object.freeze(`__«SKIP^NEW^LINE^IF^EMPTY»__`);const Vt=/\S|$/;function findIndentation(e){let t=e.filter(e=>e.length>0).map(e=>e.search(Vt)),n=t.length===0?0:Math.min(...t);return Math.max(0,n)}function expandToNode(e,...t){return composeFinalGeneratorNode(splitTemplateLinesAndMergeWithSubstitutions(e,t,findIndentationAndTemplateStructure(e)))}function expandTracedToNode(e,t,n){return(r,...i)=>traceToNode(e,t,n)(expandToNode(r,...i))}function findIndentationAndTemplateStructure(e){let t=e.join(`_`).split(rt),n=t.length>1&&t[0].trim().length===0,r=n&&t.length>1&&t[t.length-1].trim().length===0;if(t.length===1||t.length!==0&&t[0].trim().length!==0||t.length===2&&t[1].trim().length===0)return{indentation:0,omitFirstLine:n,omitLastLine:r,trimLastLine:t.length!==1&&t[t.length-1].trim().length===0};{let e=n?t.slice(1):t;e=r?e.slice(0,e.length-1):e,e=e.filter(e=>e.length!==0);let i=findIndentation(e);return{indentation:i,omitFirstLine:n,omitLastLine:r&&(t[t.length-1].length<i||!t[t.length-1].startsWith(e[0].substring(0,i)))}}}function splitTemplateLinesAndMergeWithSubstitutions(e,t,{indentation:n,omitFirstLine:r,omitLastLine:i,trimLastLine:a}){let o=[];e.forEach((e,i)=>{o.push(...e.split(rt).map((e,t)=>t===0||e.length<n?e:e.substring(n)).reduce(i===0?(e,t,n)=>n===0?r?[]:[t]:n===1&&e.length===0?[t]:e.concat(Ht,t):(e,t,n)=>n===0?[t]:e.concat(Ht,t),[]).filter(e=>typeof e!=`string`||e.length!==0).concat(isGeneratorNode(t[i])?t[i]:t[i]===void 0?i<t.length?Ut:[]:{content:String(t[i])}))});let s=o.length,c=s===0?void 0:o[s-1];return(i||a)&&typeof c==`string`&&c.trim().length===0?r&&s!==1&&o[s-2]===Ht?o.slice(0,s-2):o.slice(0,s-1):o}const Ht={isNewLine:!0},Ut={isUndefinedSegment:!0},isNewLineMarker=e=>e===Ht,isUndefinedSegmentMarker=e=>e===Ut,isSubstitutionWrapper=e=>e.content!==void 0;function composeFinalGeneratorNode(e){return e.reduce((t,n,r)=>isUndefinedSegmentMarker(n)?t:isNewLineMarker(n)?{node:r!==0&&(isUndefinedSegmentMarker(e[r-1])||isGeneratorNode(e[r-1]))||r>1&&typeof e[r-1]==`string`&&(isUndefinedSegmentMarker(e[r-2])||isGeneratorNode(e[r-2]))?t.node.appendNewLineIfNotEmpty():t.node.appendNewLine()}:(()=>{let i=(r===0||isNewLineMarker(e[r-1]))&&typeof n==`string`&&n.length!==0?n.substring(0,n.length-n.trimStart().length):``,a=isSubstitutionWrapper(n)?n.content:n,o;return{node:t.indented?t.node:i.length===0?t.node.append(a):t.node.indent({indentation:i,indentImmediately:!1,indentedChildren:e=>o=e.append(a)}),indented:o??t.indented?.append(a)}})(),{node:new $}).node}const Wt=typeof process>`u`?`
15
15
  `:process.platform===`win32`?`\r
16
16
  `:`
17
- `;function isGeneratorNode(e){return e instanceof $||e instanceof IndentNode||e instanceof NewLineNode}function toString(e,t){return isGeneratorNode(e)?processGeneratorNode(e,t).text:String(e)}var $=class CompositeGeneratorNode{constructor(...e){this.contents=[],this.append(...e)}isEmpty(){return this.contents.length===0}trace(e,t,n){if(isAstNode(e)){if(this.tracedSource={astNode:e,property:t,index:n},this.tracedSource.property===void 0&&this.tracedSource.index!==void 0&&this.tracedSource.index>-1)throw Error(`Generation support: 'property' argument must not be 'undefined' if a non-negative value is assigned to 'index' in 'CompositeGeneratorNode.trace(...)'.`)}else this.tracedSource=e;return this}append(...e){for(let t of e)typeof t==`function`?t(this):t&&this.contents.push(t);return this}prepend(...e){return this.contents.unshift(...e.filter(e=>e!==void 0)),this}appendIf(e,...t){return e?this.append(...t):this}prependIf(e,...t){return e?this.prepend(...t):this}appendNewLine(){return this.append(Gt)}appendNewLineIf(e){return e?this.append(Gt):this}appendNewLineIfNotEmpty(){return this.append(Kt)}appendNewLineIfNotEmptyIf(e){return e?this.appendNewLineIfNotEmpty():this}appendTemplate(e,...t){return this.append(expandToNode(e,...t))}appendTemplateIf(e){return e?(e,...t)=>this.appendTemplate(e,...t):()=>this}indent(e){let{indentedChildren:t,indentation:n,indentEmptyLines:r,indentImmediately:i}=Array.isArray(e)||typeof e==`function`?{indentedChildren:e}:typeof e==`object`?e:{},a=new IndentNode(n,i,r);return this.contents.push(a),Array.isArray(t)?a.append(...t):t&&a.append(t),this}appendTraced(e,t,n){return r=>this.append(new CompositeGeneratorNode().trace(e,t,n).append(r))}appendTracedIf(e,t,n,r){return e?this.appendTraced(typeof t==`function`?t():t,n,r):()=>this}appendTracedTemplate(e,t,n){return(r,...i)=>this.append(expandTracedToNode(e,t,n)(r,...i))}appendTracedTemplateIf(e,t,n,r){return e?this.appendTracedTemplate(typeof t==`function`?t():t,n,r):()=>this}};function traceToNode(e,t,n){return r=>r instanceof $&&r.tracedSource===void 0?r.trace(e,t,n):new $().trace(e,t,n).append(r)}var IndentNode=class extends ${constructor(e,t=!0,n=!1){super(),typeof e==`string`?this.indentation=e:typeof e==`number`&&(this.indentation=``.padStart(e)),this.indentImmediately=t,this.indentEmptyLines=n}},NewLineNode=class{constructor(e=Wt,t=!1,n=1){this.lineDelimiter=e,this.ifNotEmpty=t,this.count=n}};const Gt=new NewLineNode,Kt=new NewLineNode(void 0,!0),defaultToGenerated=e=>e===void 0||typeof e==`string`||isGeneratorNode(e)?e:String(e);function joinToNode(e,t=defaultToGenerated,n={}){let r=typeof t==`function`?t:defaultToGenerated,{filter:i,prefix:a,suffix:o,separator:s,appendNewLineIfNotEmpty:c,skipNewLineAfterLastItem:l}=typeof t==`object`?t:n,u=typeof a==`function`?a:(()=>a),d=typeof o==`function`?o:(()=>o),doAppendNewLines=e=>{e.isEmpty()||(c===!0||c===1?e.appendNewLineIfNotEmpty():e.append(new NewLineNode(void 0,!0,c)))};return reduceWithIsLast(e,(e,t,n,a)=>{if(i&&!i(t,n,a))return e;let o=r(t,n,a);return o===void 0?e:(e??=new $).appendIf(!e.isEmpty(),s).appendIf(c!==void 0,doAppendNewLines).append(u(t,n,a)).append(o).append(d(t,n,a))})?.appendIf(!l&&c!==void 0,doAppendNewLines)}function reduceWithIsLast(e,t,n){let r=e[Symbol.iterator](),i=r.next(),a=0,o=n;for(;!i.done;){let e=r.next();o=t(o,i.value,a,!!e.done),i=e,a++}return o}export{G as $,DefaultNameProvider as A,J as B,SimpleCache as C,StreamScope as D,MapScope as E,interruptAndCheck as F,st as G,findNodeForKeyword as H,isOperationCancelled as I,getDocument as J,nt as K,DefaultValueConverter as L,DefaultLangiumDocuments as M,X as N,DefaultScopeComputation as O,be as P,findCommentNode as Q,Y as R,ContextCache as S,mt as T,findNodeForProperty as U,DefaultCompletionProvider as V,findNodesForProperty as W,streamAllContents as X,hasContainerOfType as Y,et as Z,loadGrammarFromJson as _,NodeFileSystemProvider as a,isAstNode as at,inject as b,createDefaultModule as c,AbstractSemanticTokenProvider as d,stream as et,AstNodeHoverProvider as f,DefaultIndexManager as g,DefaultWorkspaceManager as h,toString as i,AbstractAstReflection as it,isNamed as j,MultiMap as k,createDefaultSharedModule as l,DefaultDocumentValidator as m,$ as n,isKeyword as nt,AbstractFormatter as o,DefaultDocumentHighlightProvider as p,getContainerOfType as q,NewLineNode as r,isRuleCall as rt,Bt as s,joinToNode as t,isCrossReference as tt,DefaultWorkspaceSymbolProvider as u,Ct as v,WorkspaceCache as w,DefaultScopeProvider as x,JSDocDocumentationProvider as y,y as z};
17
+ `;function isGeneratorNode(e){return e instanceof $||e instanceof IndentNode||e instanceof NewLineNode}function toString(e,t){return isGeneratorNode(e)?processGeneratorNode(e,t).text:String(e)}var $=class CompositeGeneratorNode{constructor(...e){this.contents=[],this.append(...e)}isEmpty(){return this.contents.length===0}trace(e,t,n){if(isAstNode(e)){if(this.tracedSource={astNode:e,property:t,index:n},this.tracedSource.property===void 0&&this.tracedSource.index!==void 0&&this.tracedSource.index>-1)throw Error(`Generation support: 'property' argument must not be 'undefined' if a non-negative value is assigned to 'index' in 'CompositeGeneratorNode.trace(...)'.`)}else this.tracedSource=e;return this}append(...e){for(let t of e)typeof t==`function`?t(this):t&&this.contents.push(t);return this}prepend(...e){return this.contents.unshift(...e.filter(e=>e!==void 0)),this}appendIf(e,...t){return e?this.append(...t):this}prependIf(e,...t){return e?this.prepend(...t):this}appendNewLine(){return this.append(Gt)}appendNewLineIf(e){return e?this.append(Gt):this}appendNewLineIfNotEmpty(){return this.append(Kt)}appendNewLineIfNotEmptyIf(e){return e?this.appendNewLineIfNotEmpty():this}appendTemplate(e,...t){return this.append(expandToNode(e,...t))}appendTemplateIf(e){return e?(e,...t)=>this.appendTemplate(e,...t):()=>this}indent(e){let{indentedChildren:t,indentation:n,indentEmptyLines:r,indentImmediately:i}=Array.isArray(e)||typeof e==`function`?{indentedChildren:e}:typeof e==`object`?e:{},a=new IndentNode(n,i,r);return this.contents.push(a),Array.isArray(t)?a.append(...t):t&&a.append(t),this}appendTraced(e,t,n){return r=>this.append(new CompositeGeneratorNode().trace(e,t,n).append(r))}appendTracedIf(e,t,n,r){return e?this.appendTraced(typeof t==`function`?t():t,n,r):()=>this}appendTracedTemplate(e,t,n){return(r,...i)=>this.append(expandTracedToNode(e,t,n)(r,...i))}appendTracedTemplateIf(e,t,n,r){return e?this.appendTracedTemplate(typeof t==`function`?t():t,n,r):()=>this}};function traceToNode(e,t,n){return r=>r instanceof $&&r.tracedSource===void 0?r.trace(e,t,n):new $().trace(e,t,n).append(r)}var IndentNode=class extends ${constructor(e,t=!0,n=!1){super(),typeof e==`string`?this.indentation=e:typeof e==`number`&&(this.indentation=``.padStart(e)),this.indentImmediately=t,this.indentEmptyLines=n}},NewLineNode=class{constructor(e=Wt,t=!1,n=1){this.lineDelimiter=e,this.ifNotEmpty=t,this.count=n}};const Gt=new NewLineNode,Kt=new NewLineNode(void 0,!0),defaultToGenerated=e=>e===void 0||typeof e==`string`||isGeneratorNode(e)?e:String(e);function joinToNode(e,t=defaultToGenerated,n={}){let r=typeof t==`function`?t:defaultToGenerated,{filter:i,prefix:a,suffix:o,separator:s,appendNewLineIfNotEmpty:c,skipNewLineAfterLastItem:l}=typeof t==`object`?t:n,u=typeof a==`function`?a:(()=>a),d=typeof o==`function`?o:(()=>o),doAppendNewLines=e=>{e.isEmpty()||(c===!0||c===1?e.appendNewLineIfNotEmpty():e.append(new NewLineNode(void 0,!0,c)))};return reduceWithIsLast(e,(e,t,n,a)=>{if(i&&!i(t,n,a))return e;let o=r(t,n,a);return o===void 0?e:(e??=new $).appendIf(!e.isEmpty(),s).appendIf(c!==void 0,doAppendNewLines).append(u(t,n,a)).append(o).append(d(t,n,a))})?.appendIf(!l&&c!==void 0,doAppendNewLines)}function reduceWithIsLast(e,t,n){let r=e[Symbol.iterator](),i=r.next(),a=0,o=n;for(;!i.done;){let e=r.next();o=t(o,i.value,a,!!e.done),i=e,a++}return o}export{getDocument as $,MapScope as A,isOperationCancelled as B,JSDocDocumentationProvider as C,SimpleCache as D,ContextCache as E,isNamed as F,J as G,Y as H,DefaultLangiumDocuments as I,findNodeForProperty as J,DefaultCompletionProvider as K,X as L,DefaultScopeComputation as M,MultiMap as N,WorkspaceCache as O,DefaultNameProvider as P,getContainerOfType as Q,be as R,ge as S,DefaultScopeProvider as T,DefaultDefinitionProvider as U,DefaultValueConverter as V,y as W,st as X,findNodesForProperty as Y,nt as Z,DefaultWorkspaceManager as _,NodeFileSystemProvider as a,G as at,loadGrammarFromJson as b,AbstractExecuteCommandHandler as c,isKeyword as ct,DefaultWorkspaceSymbolProvider as d,isAstNode as dt,hasContainerOfType as et,AbstractSemanticTokenProvider as f,DefaultDocumentValidator as g,DefaultDocumentHighlightProvider as h,toString as i,findLeafNodeAtOffset as it,StreamScope as j,mt as k,createDefaultModule as l,isRuleCall as lt,DefaultDocumentUpdateHandler as m,$ as n,streamAst as nt,AbstractFormatter as o,stream as ot,AstNodeHoverProvider as p,findNodeForKeyword as q,NewLineNode as r,et as rt,Bt as s,isCrossReference as st,joinToNode as t,streamAllContents as tt,createDefaultSharedModule as u,AbstractAstReflection as ut,DefaultIndexManager as v,inject as w,Ct as x,DefaultDocumentBuilder as y,interruptAndCheck as z};
@@ -1,2 +1,2 @@
1
- import"../rolldown-runtime.mjs";function defaultStringLength(e){return e.length}function markdownTable(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||defaultStringLength,a=[],o=[],s=[],c=[],l=0,u=-1;for(;++u<e.length;){let t=[],r=[],a=-1;for(e[u].length>l&&(l=e[u].length);++a<e[u].length;){let o=serialize(e[u][a]);if(n.alignDelimiters!==!1){let e=i(o);r[a]=e,(c[a]===void 0||e>c[a])&&(c[a]=e)}t.push(o)}o[u]=t,s[u]=r}let d=-1;if(typeof r==`object`&&`length`in r)for(;++d<l;)a[d]=toAlignment(r[d]);else{let e=toAlignment(r);for(;++d<l;)a[d]=e}d=-1;let f=[],p=[];for(;++d<l;){let e=a[d],t=``,r=``;e===99?(t=`:`,r=`:`):e===108?t=`:`:e===114&&(r=`:`);let i=n.alignDelimiters===!1?1:Math.max(1,c[d]-t.length-r.length),o=t+`-`.repeat(i)+r;n.alignDelimiters!==!1&&(i=t.length+i+r.length,i>c[d]&&(c[d]=i),p[d]=i),f[d]=o}o.splice(1,0,f),s.splice(1,0,p),u=-1;let m=[];for(;++u<o.length;){let e=o[u],t=s[u];d=-1;let r=[];for(;++d<l;){let i=e[d]||``,o=``,s=``;if(n.alignDelimiters!==!1){let e=c[d]-(t[d]||0),n=a[d];n===114?o=` `.repeat(e):n===99?e%2?(o=` `.repeat(e/2+.5),s=` `.repeat(e/2-.5)):(o=` `.repeat(e/2),s=o):s=` `.repeat(e)}n.delimiterStart!==!1&&!d&&r.push(`|`),n.padding!==!1&&(n.alignDelimiters!==!1||i!==``)&&(n.delimiterStart!==!1||d)&&r.push(` `),n.alignDelimiters!==!1&&r.push(o),r.push(i),n.alignDelimiters!==!1&&r.push(s),n.padding!==!1&&r.push(` `),(n.delimiterEnd!==!1||d!==l-1)&&r.push(`|`)}m.push(n.delimiterEnd===!1?r.join(``).replace(/ +$/,``):r.join(``))}return m.join(`
1
+ import"../rolldown-runtime.mjs";function defaultStringLength(e){return e.length}function markdownTable(e,t){let n=t||{},r=(n.align||[]).concat(),i=n.stringLength||defaultStringLength,a=[],o=[],s=[],c=[],l=0,u=-1;for(;++u<e.length;){let t=[],r=[],a=-1;for(e[u].length>l&&(l=e[u].length);++a<e[u].length;){let o=serialize(e[u][a]);if(n.alignDelimiters!==!1){let e=i(o);r[a]=e,(c[a]===void 0||e>c[a])&&(c[a]=e)}t.push(o)}o[u]=t,s[u]=r}let d=-1;if(typeof r==`object`&&`length`in r)for(;++d<l;)a[d]=toAlignment(r[d]);else{let e=toAlignment(r);for(;++d<l;)a[d]=e}d=-1;let f=[],p=[];for(;++d<l;){let e=a[d],t=``,r=``;e===99?(t=`:`,r=`:`):e===108?t=`:`:e===114&&(r=`:`);let i=n.alignDelimiters===!1?1:Math.max(1,c[d]-t.length-r.length),o=t+`-`.repeat(i)+r;n.alignDelimiters!==!1&&(i=t.length+i+r.length,i>c[d]&&(c[d]=i),p[d]=i),f[d]=o}o.splice(1,0,f),s.splice(1,0,p),u=-1;let m=[];for(;++u<o.length;){let e=o[u],t=s[u];d=-1;let r=[];for(;++d<l;){let i=e[d]||``,o=``,s=``;if(n.alignDelimiters!==!1){let e=c[d]-(t[d]||0),n=a[d];n===114?o=` `.repeat(e):n===99?e%2?(o=` `.repeat(e/2+.5),s=` `.repeat(e/2-.5)):(o=` `.repeat(e/2),s=o):s=` `.repeat(e)}n.delimiterStart!==!1&&!d&&r.push(`|`),n.padding===!1||n.alignDelimiters===!1&&i===``||n.delimiterStart===!1&&!d||r.push(` `),n.alignDelimiters!==!1&&r.push(o),r.push(i),n.alignDelimiters!==!1&&r.push(s),n.padding!==!1&&r.push(` `),(n.delimiterEnd!==!1||d!==l-1)&&r.push(`|`)}m.push(n.delimiterEnd===!1?r.join(``).replace(/ +$/,``):r.join(``))}return m.join(`
2
2
  `)}function serialize(e){return e==null?``:String(e)}function toAlignment(e){let t=typeof e==`string`?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}export{markdownTable as t};
@@ -1 +1 @@
1
- import"../rolldown-runtime.mjs";const convert=(function(e){if(e==null)return ok;if(typeof e==`function`)return castFactory(e);if(typeof e==`object`)return Array.isArray(e)?anyFactory(e):propsFactory(e);if(typeof e==`string`)return typeFactory(e);throw Error(`Expected function, string, or object as test`)});function anyFactory(e){let t=[],n=-1;for(;++n<e.length;)t[n]=convert(e[n]);return castFactory(any);function any(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}function propsFactory(e){let t=e;return castFactory(all);function all(n){let r=n,i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function typeFactory(e){return castFactory(type);function type(t){return t&&t.type===e}}function castFactory(e){return check;function check(t,n,r){return!!(looksLikeANode(t)&&e.call(this,t,typeof n==`number`?n:void 0,r||void 0))}}function ok(){return!0}function looksLikeANode(e){return typeof e==`object`&&!!e&&`type`in e}function color(e){return`\x1B[33m`+e+`\x1B[39m`}const e=[];function visitParents(t,n,r,i){let a;typeof n==`function`&&typeof r!=`function`?(i=r,r=n):a=n;let o=convert(a),s=i?-1:1;factory(t,void 0,[])();function factory(t,a,c){let l=t&&typeof t==`object`?t:{};if(typeof l.type==`string`){let e=typeof l.tagName==`string`?l.tagName:typeof l.name==`string`?l.name:void 0;Object.defineProperty(visit,"name",{value:`node (`+color(t.type+(e?`<`+e+`>`:``))+`)`})}return visit;function visit(){let l=e,u,d,f;if((!n||o(t,a,c[c.length-1]||void 0))&&(l=toResult(r(t,c)),l[0]===!1))return l;if(`children`in t&&t.children){let e=t;if(e.children&&l[0]!==`skip`)for(d=(i?e.children.length:-1)+s,f=c.concat(e);d>-1&&d<e.children.length;){let t=e.children[d];if(u=factory(t,d,f)(),u[0]===!1)return u;d=typeof u[1]==`number`?u[1]:d+s}}return l}}}function toResult(t){return Array.isArray(t)?t:typeof t==`number`?[!0,t]:t==null?e:[t]}function escapeStringRegexp(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}function findAndReplace(e,t,n){let r=convert((n||{}).ignore||[]),i=toPairs(t),a=-1;for(;++a<i.length;)visitParents(e,`text`,visitor);function visitor(e,t){let n=-1,i;for(;++n<t.length;){let e=t[n],a=i?i.children:void 0;if(r(e,a?a.indexOf(e):void 0,i))return;i=e}if(i)return handler(e,t)}function handler(e,t){let n=t[t.length-1],r=i[a][0],o=i[a][1],s=0,c=n.children.indexOf(e),l=!1,u=[];r.lastIndex=0;let d=r.exec(e.value);for(;d;){let n=d.index,i={index:d.index,input:d.input,stack:[...t,e]},a=o(...d,i);if(typeof a==`string`&&(a=a.length>0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s<e.value.length&&u.push({type:`text`,value:e.value.slice(s)}),n.children.splice(c,1,...u)):u=[e],c+u.length}}function toPairs(e){let t=[];if(!Array.isArray(e))throw TypeError(`Expected find and replace tuple or list of tuples`);let n=!e[0]||Array.isArray(e[0])?e:[e],r=-1;for(;++r<n.length;){let e=n[r];t.push([toExpression(e[0]),toFunction(e[1])])}return t}function toExpression(e){return typeof e==`string`?new RegExp(escapeStringRegexp(e),`g`):e}function toFunction(e){return typeof e==`function`?e:function(){return e}}export{visitParents as n,convert as r,findAndReplace as t};
1
+ import"../rolldown-runtime.mjs";function escapeStringRegexp(e){if(typeof e!=`string`)throw TypeError(`Expected a string`);return e.replace(/[|\\{}()[\]^$+*?.]/g,`\\$&`).replace(/-/g,`\\x2d`)}const convert=(function(e){if(e==null)return ok;if(typeof e==`function`)return castFactory(e);if(typeof e==`object`)return Array.isArray(e)?anyFactory(e):propsFactory(e);if(typeof e==`string`)return typeFactory(e);throw Error(`Expected function, string, or object as test`)});function anyFactory(e){let t=[],n=-1;for(;++n<e.length;)t[n]=convert(e[n]);return castFactory(any);function any(...e){let n=-1;for(;++n<t.length;)if(t[n].apply(this,e))return!0;return!1}}function propsFactory(e){let t=e;return castFactory(all);function all(n){let r=n,i;for(i in e)if(r[i]!==t[i])return!1;return!0}}function typeFactory(e){return castFactory(type);function type(t){return t&&t.type===e}}function castFactory(e){return check;function check(t,n,r){return!!(looksLikeANode(t)&&e.call(this,t,typeof n==`number`?n:void 0,r||void 0))}}function ok(){return!0}function looksLikeANode(e){return typeof e==`object`&&!!e&&`type`in e}function color(e){return`\x1B[33m`+e+`\x1B[39m`}const e=[];function visitParents(t,n,r,i){let a;typeof n==`function`&&typeof r!=`function`?(i=r,r=n):a=n;let o=convert(a),s=i?-1:1;factory(t,void 0,[])();function factory(t,a,c){let l=t&&typeof t==`object`?t:{};if(typeof l.type==`string`){let e=typeof l.tagName==`string`?l.tagName:typeof l.name==`string`?l.name:void 0;Object.defineProperty(visit,"name",{value:`node (`+color(t.type+(e?`<`+e+`>`:``))+`)`})}return visit;function visit(){let l=e,u,d,f;if((!n||o(t,a,c[c.length-1]||void 0))&&(l=toResult(r(t,c)),l[0]===!1))return l;if(`children`in t&&t.children){let e=t;if(e.children&&l[0]!==`skip`)for(d=(i?e.children.length:-1)+s,f=c.concat(e);d>-1&&d<e.children.length;){let t=e.children[d];if(u=factory(t,d,f)(),u[0]===!1)return u;d=typeof u[1]==`number`?u[1]:d+s}}return l}}}function toResult(t){return Array.isArray(t)?t:typeof t==`number`?[!0,t]:t==null?e:[t]}function findAndReplace(e,t,n){let r=convert((n||{}).ignore||[]),i=toPairs(t),a=-1;for(;++a<i.length;)visitParents(e,`text`,visitor);function visitor(e,t){let n=-1,i;for(;++n<t.length;){let e=t[n],a=i?i.children:void 0;if(r(e,a?a.indexOf(e):void 0,i))return;i=e}if(i)return handler(e,t)}function handler(e,t){let n=t[t.length-1],r=i[a][0],o=i[a][1],s=0,c=n.children.indexOf(e),l=!1,u=[];r.lastIndex=0;let d=r.exec(e.value);for(;d;){let n=d.index,i={index:d.index,input:d.input,stack:[...t,e]},a=o(...d,i);if(typeof a==`string`&&(a=a.length>0?{type:`text`,value:a}:void 0),a===!1?r.lastIndex=n+1:(s!==n&&u.push({type:`text`,value:e.value.slice(s,n)}),Array.isArray(a)?u.push(...a):a&&u.push(a),s=n+d[0].length,l=!0),!r.global)break;d=r.exec(e.value)}return l?(s<e.value.length&&u.push({type:`text`,value:e.value.slice(s)}),n.children.splice(c,1,...u)):u=[e],c+u.length}}function toPairs(e){let t=[];if(!Array.isArray(e))throw TypeError(`Expected find and replace tuple or list of tuples`);let n=!e[0]||Array.isArray(e[0])?e:[e],r=-1;for(;++r<n.length;){let e=n[r];t.push([toExpression(e[0]),toFunction(e[1])])}return t}function toExpression(e){return typeof e==`string`?new RegExp(escapeStringRegexp(e),`g`):e}function toFunction(e){return typeof e==`function`?e:function(){return e}}export{visitParents as n,convert as r,findAndReplace as t};