@withgraphite/graphite-cli 0.22.4 → 0.22.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/325.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- "use strict";exports.id=325,exports.ids=[325],exports.modules={33800:(e,t)=>{var s;Object.defineProperty(t,"__esModule",{value:!0}),t.comparisonIsAgainstHead=t.labelForComparison=t.revsetArgsForComparison=t.ComparisonType=void 0,function(e){e.UncommittedChanges="UNCOMMITTED",e.HeadChanges="HEAD",e.StackChanges="STACK",e.Committed="InCommit"}(s=t.ComparisonType||(t.ComparisonType={})),t.revsetArgsForComparison=function(e){switch(e.type){case s.UncommittedChanges:return["uncommitted"];case s.HeadChanges:return["head"];case s.StackChanges:return["stack"];case s.Committed:return["stack","--ref",e.hash]}},t.labelForComparison=function(e){switch(e.type){case s.UncommittedChanges:return"Uncommitted Changes";case s.HeadChanges:return"Head Changes";case s.StackChanges:return"Stack Changes";case s.Committed:return`In ${e.hash}`}},t.comparisonIsAgainstHead=function(e){switch(e.type){case s.UncommittedChanges:case s.HeadChanges:case s.StackChanges:return!0;case s.Committed:return!1}}},52060:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},2982:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cached=t.LRU=void 0;const n=s(30826);class i{constructor(e,t=3){this.maxItems=e,this.maxHashCollision=t,this.cache=new Map}get(e){let t;const s=r(e),i=this.cache.get(s);if(void 0!==i){const r=i.get(e);if(void 0!==r)t=r;else for(const[s,r]of i)if((0,n.is)(e,s)){t=r;break}this.cache.delete(s),this.cache.set(s,i)}return t}set(e,t){const s=r(e);let n=this.cache.get(s);if(void 0===n||n.size>=this.maxHashCollision?n=new Map([[e,t]]):n.set(e,t),this.cache.delete(s),void 0!==t&&(this.cache.set(s,n),this.cache.size>this.maxItems)){const e=this.cache.keys().next();e.done||this.cache.delete(e.value)}}delete(e){const t=r(e);this.cache.delete(t)}clear(){this.cache.clear()}}function r(e){const t=null==e?void 0:e.hashCode;return void 0!==t?t.apply(e):e}function o(e,t){var s,r;const o=null!==(s=null==t?void 0:t.cache)&&void 0!==s?s:new i(null!==(r=null==t?void 0:t.cacheSize)&&void 0!==r?r:10),a=null==t?void 0:t.getExtraKeys,l=function(...t){var s,i,r;const l=o.stats;if(!t.every(c))return null!=l&&(l.skip=(null!==(s=l.skip)&&void 0!==s?s:0)+1),e.apply(this,t);const h=(0,n.List)(a?[...a.apply(this),...t]:t),u=o.get(h);if(void 0!==u)return null!=l&&(l.hit=(null!==(i=l.hit)&&void 0!==i?i:0)+1),u;null!=l&&(l.miss=(null!==(r=l.miss)&&void 0!==r?r:0)+1);const d=e.apply(this,t);return o.set(h,d),d};return l.cache=o,l}t.LRU=i,t.cached=function(e,t){return"function"==typeof e?o(e,t):function(e){var t;const s=null!==(t=null==e?void 0:e.getExtraKeys)&&void 0!==t?t:function(){return(0,n.isValueObject)(this)?[this]:null!=this&&"object"==typeof this?Object.values(this).filter(c):[]};return function(t,n,i){const r=i.value;i.value=o(r,Object.assign(Object.assign({},e),{getExtraKeys:s}))}}(e)};const a=new Set(["number","string","boolean","symbol","bigint","undefined","null"]);function c(e){if(null==e)return!0;const t=typeof e;return!!a.has(t)||!("object"!==t||!(0,n.isValueObject)(e))}},61110:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5693:function(e,t,s){var n=this&&this.__createBinding||(Object.create?function(e,t,s,n){void 0===n&&(n=s);var i=Object.getOwnPropertyDescriptor(t,s);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,n,i)}:function(e,t,s,n){void 0===n&&(n=s),e[n]=t[s]}),i=this&&this.__exportStar||function(e,t){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(t,s)||n(t,e,s)};Object.defineProperty(t,"__esModule",{value:!0}),i(s(61110),t),i(s(52568),t),i(s(11268),t),i(s(66877),t)},52568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},11268:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Tracker=void 0;const n=s(48427);class i{constructor(e,t){this.sendData=e,this.context=t}error(e,t,s,n){const i=s instanceof Error?s.message||String(s):s;return this.track(e,Object.assign(Object.assign({},null!=n?n:{}),{errorMessage:i,errorName:t}))}operation(e,t,s,i){var r;const o=Date.now(),a=null!==(r=null==s?void 0:s.id)&&void 0!==r?r:(0,n.randomId)();try{const r=i({parentId:a});if((0,n.isPromise)(r))return r.then((t=>{const n=Date.now()-o;return this.track(e,Object.assign(Object.assign({},null!=s?s:{}),{duration:n,id:a})),t})).catch((n=>{const i=Date.now()-o;return this.error(e,t,n,Object.assign(Object.assign({},null!=s?s:{}),{duration:i,id:a})),Promise.reject(n)}));{const t=Date.now()-o;return this.track(e,Object.assign(Object.assign({},null!=s?s:{}),{duration:t,id:a})),r}}catch(n){const i=Date.now()-o;throw this.error(e,t,n,Object.assign(Object.assign({},null!=s?s:{}),{duration:i,id:a})),n}}trackAsParent(e,t){var s;const r=null!==(s=null==t?void 0:t.id)&&void 0!==s?s:(0,n.randomId)();return this.trackData(Object.assign(Object.assign({},t),{eventName:e,id:r})),new i(((e,t)=>this.trackData(Object.assign(Object.assign({},e),t))),{parentId:r})}track(e,t){return this.trackData(Object.assign(Object.assign({},t),{eventName:e}))}trackData(e){var t,s;const i=null!==(t=null==e?void 0:e.id)&&void 0!==t?t:(0,n.randomId)(),r=null!==(s=null==e?void 0:e.timestamp)&&void 0!==s?s:Date.now(),o=Object.assign({timestamp:r,id:i},null!=e?e:{});this.sendData(o,this.context)}}t.Tracker=i},66877:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},33905:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.newAbortController=void 0;const n=s(53811);t.newAbortController=function(){return"function"==typeof AbortController?new AbortController:new n.AbortController}},66960:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0,t.debounce=function(e,t,s=void 0,n=!1){let i,r=!0;function o(...a){let c;if(n){if(c=function(){r=!0,i=void 0},!r)return clearTimeout(i),void(i=setTimeout(c,t));r=!1,e.apply(s,a)}else o.reset(),c=function(){i=void 0,e.apply(s,a)};i=setTimeout(c,t)}return o.reset=function(){clearTimeout(i),i=void 0,r=!0},o.isPending=function(){return null!=i},o}},90828:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SelfUpdate=void 0;class s{constructor(e){this.inner=e}hashCode(){return this.inner.hashCode()+1}equals(e){if(!(e instanceof s))return!1;if(this===e)return!0;const t=e.inner,n=this.inner.equals(t);return n&&this.inner!==t&&(this.inner=t),n}}t.SelfUpdate=s},98696:function(e,t,s){var n=this&&this.__createBinding||(Object.create?function(e,t,s,n){void 0===n&&(n=s);var i=Object.getOwnPropertyDescriptor(t,s);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,n,i)}:function(e,t,s,n){void 0===n&&(n=s),e[n]=t[s]}),i=this&&this.__exportStar||function(e,t){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(t,s)||n(t,e,s)};Object.defineProperty(t,"__esModule",{value:!0}),i(s(5693),t),i(s(33800),t),i(s(86099),t),i(s(40256),t),i(s(85249),t),i(s(48427),t),i(s(66224),t),i(s(2982),t),i(s(13035),t),i(s(90828),t),i(s(52060),t),i(s(66960),t),i(s(33905),t),i(s(75905),t)},13035:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.minimalDisambiguousPaths=void 0,t.minimalDisambiguousPaths=function(e,t={}){const s=e.map((e=>{const t=function(e){return e.replace(/[^\\]/g,"").length>e.replace(/[^/]/g,"").length?"\\":"/"}(e),s=/^(\w:).*/.exec(e),n=null!=s?s[1]:"";return{depth:null,parts:e.split(t).reverse().filter((e=>""!==e&&e!==n)),rootPrefix:n,separator:t,hadLeadingSeparator:e.startsWith(t)||n.length>0&&e.startsWith(n)}})),n=null==t.maxDepth?Math.max(...s.map((e=>e.parts.length))):t.maxDepth,i=new Set(s),r=new Map;for(let e=1;e<=n;e++){r.clear();for(const t of i){const s=t.parts.slice(0,e).join(t.separator);r.has(s)||r.set(s,new Set),r.get(s).add(t)}for(const t of r.values())if(1===t.size){const s=Array.from(t)[0];s.depth=e,i.delete(s)}}return s.map((({depth:e,parts:s,rootPrefix:i,separator:r,hadLeadingSeparator:o})=>{var a;let c=s.slice(0,null==e?n:e).reverse();return 0===c.length?`${i}${r}`:((1===c.length&&""===c[0]||c.length>1&&""!==c[0])&&(c=c.length===s.length?o?[i,...c]:c:(null!==(a=t.alwaysShowLeadingSeparator)&&void 0!==a?a:o)?["",...c]:c),c.join(r))}))}},75905:(e,t)=>{var s;Object.defineProperty(t,"__esModule",{value:!0}),t.parsePatch=t.DiffType=void 0,function(e){e.Modified="Modified",e.Added="Added",e.Removed="Removed",e.Renamed="Renamed",e.Copied="Copied"}(s=t.DiffType||(t.DiffType={}));const n=/^diff --git (.*) (.*)$/,i=/^rename from (.*)$/,r=/^rename to (.*)$/,o=/^copy from (.*)$/,a=/^copy to (.*)$/,c=/^new file mode (\d{6})$/,l=/^deleted file mode (\d{6})$/,h=/^old mode (\d{6})$/,u=/^new mode (\d{6})$/,d=/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/,m=/^--- (.*)$/,p=/^\+\+\+ (.*)$/,g=/\r\n|[\n\v\f\r\x85]/g;function f(e,t){if(!1===e)throw new Error(t)}t.parsePatch=function(e){const t=e.split(g),v=e.match(g)||[],b=[];let y=0;function w(){const e={hunks:[]};for(b.push(e),function(e){for(;y<t.length;){const s=t[y],i=n.exec(s);if(i){e.oldFileName=i[1],e.newFileName=i[2],y++;break}y++}}(e);y<t.length;){const s=t[y];if(/^old mode/.test(s))C(e);else if(/^new mode/.test(s))S(e);else if(/^deleted file mode/.test(s))O(e);else if(/^new file mode/.test(s))E(e);else if(/^copy /.test(s))R(e);else if(/^rename /.test(s))k(e);else{if(/^--- /.test(s)){_(e);break}if(/^diff --git/.test(s))break;y++}}!function(e){for(;y<t.length;){const s=t[y];if(n.test(s))break;/^@@/.test(s)?e.hunks.push(M()):y++}}(e)}function C(e){const n=h.exec(t[y]);f(null!==n,`invalid format '${t[y]}'`),e.oldMode=n[1],e.type=s.Modified,y++}function S(e){const n=u.exec(t[y]);f(null!==n,`invalid format '${t[y]}'`),e.newMode=n[1],e.type=s.Modified,y++}function O(e){const n=l.exec(t[y]);f(null!==n,`invalid format '${t[y]}'`),e.newMode=n[1],e.type=s.Removed,y++}function E(e){const n=c.exec(t[y]);f(null!==n,`invalid format '${t[y]}'`),e.newMode=n[1],e.type=s.Added,y++}function R(e){f(o.test(t[y]),`invalid format '${t[y]}'`),f(a.test(t[y+1]),`invalid format '${t[y+1]}'`),e.type=s.Copied,y+=2}function k(e){f(i.test(t[y]),`invalid format '${t[y]}'`),f(r.test(t[y+1]),`invalid format '${t[y+1]}'`),e.type=s.Renamed,y+=2}function _(e){f(m.test(t[y]),`invalid format '${t[y]}'`),f(p.test(t[y+1]),`invalid format '${t[y+1]}'`),void 0===e.type&&(e.type=s.Modified),y+=2}function M(){const e=t[y++].split(d),s={oldStart:+e[1],oldLines:void 0===e[2]?1:+e[2],newStart:+e[3],newLines:void 0===e[4]?1:+e[4],lines:[],linedelimiters:[]};0===s.oldLines&&(s.oldStart+=1),0===s.newLines&&(s.newStart+=1);let n=0,i=0;for(;y<t.length&&!(0===t[y].indexOf("--- ")&&y+2<t.length&&0===t[y+1].indexOf("+++ ")&&0===t[y+2].indexOf("@@"));y++){const e=0==t[y].length&&y!=t.length-1?" ":t[y][0];if("+"!==e&&"-"!==e&&" "!==e&&"\\"!==e)break;s.lines.push(t[y]),s.linedelimiters.push(v[y]||"\n"),"+"===e?n++:"-"===e?i++:" "===e&&(n++,i++)}return n||1!==s.newLines||(s.newLines=0),i||1!==s.oldLines||(s.oldLines=0),s}for(;y<t.length;)w();return b}},85249:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deserializeFromString=t.deserialize=t.serializeToString=t.serialize=void 0;const s={__rpcType:"undefined"};function n(e){if(void 0===e)return s;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e||null===e)return e;if(e instanceof Map)return{__rpcType:"Map",data:Array.from(e.entries()).map((([e,t])=>[n(e),n(t)]))};if(e instanceof Set)return{__rpcType:"Set",data:Array.from(e.values()).map(n)};if(e instanceof Error)return{__rpcType:"Error",data:{message:e.message,stack:e.stack}};if(e instanceof Date)return{__rpcType:"Date",data:e.valueOf()};if(Array.isArray(e))return e.map((e=>n(e)));if("object"==typeof e){const t={__rpcType:"object"};for(const[s,i]of Object.entries(e))t[s]=n(i);return t}throw new Error(`cannot serialize argument ${e}`)}function i(e){if("object"!=typeof e||null==e)return e;if(Array.isArray(e))return e.map((e=>i(e)));const t=e;switch(t.__rpcType){case"undefined":return;case"Map":return new Map(t.data.map((([e,t])=>[i(e),i(t)])));case"Set":return new Set(t.data.map(i));case"Error":{const e=new Error;return e.stack=t.data.stack,e.message=t.data.message,e}case"Date":return new Date(t.data);case"object":{const t=e,s={};for(const[e,n]of Object.entries(t))"__rpcType"!==e&&(s[e]=i(n));return s}default:throw new Error(`cannot deserialize unknown type ${t}`)}}t.serialize=n,t.serializeToString=function(e){return JSON.stringify(n(e))},t.deserialize=i,t.deserializeFromString=function(e){return i(JSON.parse(e))}},40256:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},66224:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},50209:(e,t)=>{var s;Object.defineProperty(t,"__esModule",{value:!0}),t.SucceedableRevset=t.CommandRunner=void 0,(s=t.CommandRunner||(t.CommandRunner={})).Graphite="gt",s.CodeReviewProvider="codeReviewProvider",t.SucceedableRevset=function(e){return{type:"succeedable-revset",revset:e}}},74259:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},45852:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},1018:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorShortMessages=t.DEFAULT_DAYS_OF_COMMITS_TO_LOAD=t.ONE_MINUTE_MS=t.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE=void 0,t.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE=4100,t.ONE_MINUTE_MS=6e4,t.DEFAULT_DAYS_OF_COMMITS_TO_LOAD=void 0,(t.ErrorShortMessages||(t.ErrorShortMessages={})).NoCommitsFetched="No commits found"},29641:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},86099:function(e,t,s){var n=this&&this.__createBinding||(Object.create?function(e,t,s,n){void 0===n&&(n=s);var i=Object.getOwnPropertyDescriptor(t,s);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,n,i)}:function(e,t,s,n){void 0===n&&(n=s),e[n]=t[s]}),i=this&&this.__exportStar||function(e,t){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(t,s)||n(t,e,s)};Object.defineProperty(t,"__esModule",{value:!0}),i(s(50209),t),i(s(85119),t),i(s(45852),t),i(s(74259),t),i(s(1018),t),i(s(29641),t)},85119:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},48427:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPromise=t.truncate=t.zip=t.generatorContains=t.mapObject=t.findParentWithClassName=t.basename=t.defer=t.randomId=t.unwrap=t.notEmpty=void 0,t.notEmpty=function(e){return null!=e},t.unwrap=function(e){if(null==e)throw new Error(`expected value not to be ${e}`);return e},t.randomId=function(){return Date.now().toString(36)+Math.random().toString(36)},t.defer=function(){const e={promise:void 0,resolve:void 0,reject:void 0};return e.promise=new Promise(((t,s)=>{e.resolve=t,e.reject=s})),e},t.basename=function(e,t="/"){const s=e.lastIndexOf(t);return-1===s?e:e.slice(s+1)},t.findParentWithClassName=function(e,t){var s;let n=e;for(;n;){if(null===(s=n.classList)||void 0===s?void 0:s.contains(t))return n;n=n.parentElement}},t.mapObject=function(e,t){return Object.fromEntries(Object.entries(e).map(t))},t.generatorContains=function(e,t){const s="function"==typeof t?t:e=>e===t;for(const t of e)if(s(t))return!0;return!1},t.zip=function*(e,t){const s=e[Symbol.iterator](),n=t[Symbol.iterator]();for(;;){const e=s.next(),t=n.next();if(e.done||t.done)break;yield[e.value,t.value]}},t.truncate=function(e,t=100){return e.length>t?e.substring(0,Math.max(0,t-1))+"…":e},t.isPromise=function(e){return"function"==typeof(null==e?void 0:e.then)}},20325:(e,t,s)=>{s.r(t),s.d(t,{startServer:()=>ne});var n=s(98696),i=s(57147),r=s.n(i),o=s(13685),a=s.n(o),c=s(71017),l=s.n(c),h=s(57310),u=s.n(h),d=s(95352),m=s.n(d),p=s(22037),g=s.n(p);function f(){try{return g().userInfo().username}catch(e){try{const{env:e}=process;return(0,n.unwrap)(e.LOGNAME||e.USER||e.LNAME||e.USERNAME)}catch(t){throw new Error(String(t)+String(e))}}}class v{logger;data;constructor(e,t){this.logger=e,this.data=t}setRepo(e){this.data.repo=e?.codeReviewProvider?.getSummaryName()}}const b=e=>{};var y=s(73837),w=s.n(y);const C=console;var S=s(60492),O=s.n(S),E=s(80909),R=s.n(E),k=s(82361);class _ extends k.EventEmitter{}class M{codeReviewSystem;runCommand;constructor(e,t){this.codeReviewSystem=e,this.runCommand=t}diffSummaries=new _;onChangeDiffSummaries(e){const t=t=>e({value:t}),s=t=>e({error:t});return this.diffSummaries.on("data",t),this.diffSummaries.on("error",s),{dispose:()=>{this.diffSummaries.off("data",t),this.diffSummaries.off("error",s)}}}async triggerDiffSummariesFetch(e){const t=await this.runCommand(["internal-only","prs"]),s=JSON.parse(t.stdout);this.diffSummaries.emit("data",s)}dispose(){this.diffSummaries.removeAllListeners()}getSummaryName(){return`github:${this.codeReviewSystem.hostname}/${this.codeReviewSystem.owner}/${this.codeReviewSystem.repo}`}runExternalCommand(e,t,s,n){throw new Error("GitHub code review provider does not support running external commands")}async typeahead(e,t){return Promise.resolve([])}}class D{logger;runCallback;constructor(e,t){this.logger=e,this.runCallback=t}queuedOperations=[];runningOperation=void 0;abortController=void 0;async runOrQueueOperation(e,t,s,i){if(null!=this.runningOperation)return this.queuedOperations.push({...e,tracker:s}),void t({id:e.id,kind:"queue",queue:this.queuedOperations.map((e=>e.id))});this.runningOperation=e;const r=(...s)=>{switch(s[0]){case"spawn":t({id:e.id,kind:"spawn",queue:this.queuedOperations.map((e=>e.id))});break;case"stdout":t({id:e.id,kind:"stdout",message:s[1]});break;case"stderr":t({id:e.id,kind:"stderr",message:s[1]});break;case"exit":t({id:e.id,kind:"exit",exitCode:s[1],timestamp:Date.now()})}};try{const o=(0,n.newAbortController)();if(this.abortController=o,await s.operation(e.trackEventName,"RunOperationError",{extras:{args:e.args,runner:e.runner}},(t=>this.runCallback(e,i,r,o.signal))),this.runningOperation=void 0,this.queuedOperations.length>0){const e=this.queuedOperations.shift();null!=e&&this.runOrQueueOperation(e,t,e.tracker,i)}}catch(s){const n=s.toString();this.logger.log("error running operation: ",e.args[0],n),t({id:e.id,kind:"error",error:n}),this.queuedOperations=[],this.runningOperation=void 0}}abortRunningOperation(e){this.runningOperation?.id==e&&this.abortController?.abort()}}class T{focusedPages=new Set;visiblePages=new Set;onChangeHandlers=new Set;setState(e,t){switch(t){case"focused":this.focusedPages.add(e),this.visiblePages.add(e);break;case"visible":this.focusedPages.delete(e),this.visiblePages.add(e);break;case"hidden":this.focusedPages.delete(e),this.visiblePages.delete(e)}for(const e of this.onChangeHandlers)e(t)}disposePage(e){this.focusedPages.delete(e),this.visiblePages.delete(e)}hasPageWithFocus(){return this.focusedPages.size>0}hasVisiblePage(){return this.visiblePages.size>0}onChange(e){return this.onChangeHandlers.add(e),()=>this.onChangeHandlers.delete(e)}}class P{maxSimultaneousRunning;log;queued=[];running=[];runs=new _;constructor(e,t){this.maxSimultaneousRunning=e,this.log=t}nextId=1;generateId(){return this.nextId++}async enqueueRun(e){const t=this.generateId();this.queued.push(t),this.tryDequeueNext(),this.running.includes(t)||(this.log?.(`${this.running.length} tasks are already running, enqueuing ID:${t}`),await new Promise((e=>{this.runs.on("run",(s=>{s===t&&(this.log?.(`now allowing ID:${t} to run`),e(void 0))}))})));try{return await e()}finally{this.notifyFinished(t)}}notifyFinished(e){this.running=this.running.filter((t=>t!==e)),this.tryDequeueNext()}tryDequeueNext(){if(this.running.length<this.maxSimultaneousRunning){const e=this.queued.shift();null!=e&&this.run(e)}}run(e){this.running.push(e),this.runs.emit("run",e)}}function N(e){return new Promise((t=>setTimeout(t,e)))}function j(e){let t,s;const n=()=>{const t=e();return s=t.then((()=>s=void 0),(()=>s=void 0)),t},i=()=>(t=void 0,n());return()=>null==s?n():(()=>{if(null==t){if(null==s)throw new Error("pendingCall must not be null!");t=s.then(i,i)}return t})()}var F=s(24678);class I{logger;client;serializedReconnect;reconnectDelayMs=100;subscriptions=new Map;lastKnownClockTimes=new Map;status="initializing";constructor(e){this.logger=e,this.client=new F.Client({watchmanBinaryPath:void 0}),this.initWatchmanClient(),this.serializedReconnect=j((async()=>{let e=0;for(;;)try{return void await this.reconnectClient()}catch(t){this.logger.warn(`reconnectClient failed (try #${e}):`,t instanceof Error?t.message:t),e++,this.reconnectDelayMs*=2,this.reconnectDelayMs>6e4&&(this.reconnectDelayMs=6e4),this.logger.info("Calling reconnectClient from _serializedReconnect in %dms",this.reconnectDelayMs),await N(this.reconnectDelayMs)}}))}setStatus(e){this.logger.log("Watchman status: ",e),this.status=e}async watchDirectoryRecursive(e,t,s){const n=this.fixupName(e,t),i=this.getSubscription(n);if(i)return i.subscriptionCount++,i;{const{watch:t,relative_path:i}=await this.watchProject(e),r=await this.clock(t),o={...s,fields:null!=s&&null!=s.fields?s.fields:["name","new","exists"],since:r};i&&(o.relative_root=i),o.empty_on_fresh_instance=!0;const a={root:t,pathFromSubscriptionRootToSubscriptionPath:i,path:e,name:n,subscriptionCount:1,options:o,emitter:new k.EventEmitter};return this.setSubscription(n,a),await this.subscribe(t,n,o),this.logger.log("watchman subscription %s established",n),this.setStatus("healthy"),a}}async unwatch(e,t){const s=this.fixupName(e,t),n=this.getSubscription(s);null!=n?0==--n.subscriptionCount&&(await this.unsubscribe(n.path,n.name),this.deleteSubscription(s),this.logger.log("watchman subscription %s destroyed",s)):this.logger.error(`No watcher entity found with path [${e}] name [${t}]`)}initWatchmanClient(){this.client.on("end",(()=>{this.setStatus("ended"),this.logger.info("Watchman client ended"),this.client.removeAllListeners(),this.serializedReconnect()})),this.client.on("error",(e=>{const t=this.status;this.logger.error("Error while talking to watchman: ",e),this.setStatus("errored"),this.client.removeAllListeners(),this.client.end(),"initializing"!==t&&this.serializedReconnect()})),this.client.on("subscription",this.onSubscriptionResult.bind(this))}async reconnectClient(){this.logger.info("Ending existing watchman client to reconnect a new one"),this.setStatus("reconnecting"),this.client.removeAllListeners(),this.client.end(),this.client=new F.Client({watchmanBinaryPath:void 0}),this.logger.error("Watchman client disconnected, reconnecting a new client!"),this.initWatchmanClient(),this.logger.info("Watchman client re-initialized, restoring subscriptions"),await this.restoreSubscriptions()}async restoreSubscriptions(){const e=Array.from(this.subscriptions.values()),t=e.length;this.logger.info(`Attempting to restore ${t} Watchman subscriptions.`);let s=0;await Promise.all(e.map((async(e,n)=>{await this.watchProject(e.path),await N(2500);const{name:i,options:r,root:o}=e;e.options.since=this.lastKnownClockTimes.get(o)||await this.clock(o),this.logger.info(`Subscribing to ${i}: (${n+1}/${t})`),await this.subscribe(o,i,r),++s,this.logger.info(`Subscribed to ${i}: (${s}/${t}) complete.`)}))),s>0&&s===t&&(this.logger.info("Successfully reconnected all %d subscriptions.",s),this.reconnectDelayMs=100,this.setStatus("healthy"))}getSubscription(e){return this.subscriptions.get(l().normalize(e))}setSubscription(e,t){const s=l().normalize(e);this.subscriptions.set(s,t)}deleteSubscription(e){const t=l().normalize(e);this.subscriptions.delete(t)}onSubscriptionResult(e){const t=this.getSubscription(e.subscription);if(null!=t){if(null!=e&&null!=e.root&&null!=e.clock&&this.lastKnownClockTimes.set(e.root,e.clock),!0===e.is_fresh_instance)this.logger.warn(`Watch for ${e.root} (${e.subscription}) returned an empty fresh instance.`),t.emitter.emit("fresh-instance");else if(Array.isArray(e.files))t.emitter.emit("change",e.files);else if(!0===e.canceled)this.logger.info(`Watch for ${e.root} was deleted: triggering a reconnect.`),this.client.end();else if(this.subscriptions.values().next().value===t){const t=e["state-enter"],s=e["state-leave"],n=null!=t?`Entering ${t}`:`Leaving ${s}`,i=this.subscriptions.size;this.logger.info(`Subscription state: ${n} (${i})`)}}else this.logger.error("Subscription not found for response:!",e)}fixupName(e,t){return`${e.replace(/\\/g,"-").replace(/\//g,"-")}-${t}`}unsubscribe(e,t){return this.command("unsubscribe",e,t)}async watchProject(e){const t=await this.command("watch-project",e);return t.warning&&this.logger.error("watchman warning: ",t.warning),t}async clock(e){const{clock:t}=await this.command("clock",e);return t}subscribe(e,t,s){return this.logger.info(`Creating Watchman subscription ${String(t)} under ${e}`,JSON.stringify(s)),this.command("subscribe",e,t,s)}async command(...e){try{return await new Promise(((t,s)=>{this.client.command(e,((e,n)=>e?s(e):t(n)))}))}catch(t){throw this.logger.error("Watchman command error: ",e,t),t}}}const x=5*n.ONE_MINUTE_MS,A=1*n.ONE_MINUTE_MS,L=.25*n.ONE_MINUTE_MS;class ${repoInfo;logger;pageFocusTracker;changeCallback;static WATCHMAN_DEFER="hg.update";watchman;disposables=[];constructor(e,t,s,n,i){this.repoInfo=e,this.logger=t,this.pageFocusTracker=s,this.changeCallback=n,this.watchman=i??new I(t),this.setupWatchmanSubscriptions(),this.setupPolling(),this.pageFocusTracker.onChange(this.poll.bind(this))}timeout;lastFetch=(new Date).valueOf();setupPolling(){this.timeout=setTimeout(this.poll,x)}poll=e=>{let t=x;"healthy"!==this.watchman.status&&(this.pageFocusTracker.hasPageWithFocus()?t=L:this.pageFocusTracker.hasVisiblePage()&&(t=A));const s=Date.now()-this.lastFetch;"force"===e||s>=t||"focused"===e&&s>=1e4||"visible"===e&&s>=2e4?(this.changeCallback("everything"),this.lastFetch=Date.now(),clearTimeout(this.timeout),this.timeout=setTimeout(this.poll,t)):(clearTimeout(this.timeout),this.timeout=setTimeout(this.poll,t-s))};async setupWatchmanSubscriptions(){if("success"!==this.repoInfo.type)return;const{repoRoot:e,dotdir:t}=this.repoInfo;if(null==e||null==t)return void this.logger.error(`skipping watchman subscription since ${e} is not a repository`);const s=l().relative(e,t),i="graphite-smartlog-file-change",r="graphite-smartlog-dirstate-change";try{const t=(0,n.debounce)((()=>{this.changeCallback("everything"),this.lastFetch=(new Date).valueOf()}),100),o=await this.watchman.watchDirectoryRecursive(e,r,{fields:["name"],expression:["name",[`${s}/bookmarks.current`,`${s}/bookmarks`,`${s}/dirstate`,`${s}/merge`],"wholename"],defer:[$.WATCHMAN_DEFER],empty_on_fresh_instance:!0});o.emitter.on("change",(e=>{e.includes(`${s}/merge`)&&this.changeCallback("merge conflicts"),e.includes(`${s}/dirstate`)&&t()})),o.emitter.on("fresh-instance",t);const a=()=>{this.changeCallback("uncommitted changes"),this.lastFetch=(new Date).valueOf()},c=await this.watchman.watchDirectoryRecursive(e,i,{fields:["name"],expression:["allof",["type","f"],["not",["dirname",s]],["not",["match",s,"basename"]]],defer:[$.WATCHMAN_DEFER],empty_on_fresh_instance:!0});c.emitter.on("change",a),c.emitter.on("fresh-instance",a),this.disposables.push((()=>{this.logger.log("unsubscribe watchman"),this.watchman.unwatch(e,r),this.watchman.unwatch(e,i)}))}catch(e){this.logger.error("failed to setup watchman subscriptions",e)}}dispose(){this.disposables.forEach((e=>e())),this.timeout&&(clearTimeout(this.timeout),this.timeout=void 0)}}const U="0.22.3";class q{info;logger;IGNORE_COMMIT_MESSAGE_LINES_REGEX=/^((?:HG|SL):.*)/gm;mergeConflicts=void 0;uncommittedChanges=null;smartlogCommits=null;mergeConflictsEmitter=new _;uncommittedChangesEmitter=new _;smartlogCommitsChangesEmitter=new _;smartlogCommitsBeginFetchingEmitter=new _;uncommittedChangesBeginFetchingEmitter=new _;disposables=[()=>this.mergeConflictsEmitter.removeAllListeners(),()=>this.uncommittedChangesEmitter.removeAllListeners(),()=>this.smartlogCommitsChangesEmitter.removeAllListeners(),()=>this.smartlogCommitsBeginFetchingEmitter.removeAllListeners(),()=>this.uncommittedChangesBeginFetchingEmitter.removeAllListeners()];onDidDispose(e){this.disposables.push(e)}operationQueue;watchForChanges;pageFocusTracker=new T;codeReviewProvider;currentVisibleCommitRangeIndex=0;visibleCommitRanges=[n.DEFAULT_DAYS_OF_COMMITS_TO_LOAD,60,void 0];constructor(e,t){this.info=e,this.logger=t;const s=e.codeReviewSystem;"github"===s.type&&(this.codeReviewProvider=new M(s,this.runCommand.bind(this))),this.watchForChanges=new $(e,t,this.pageFocusTracker,(e=>{"uncommitted changes"===e?this.fetchUncommittedChanges():"commits"===e?this.fetchSmartlogCommits():"merge conflicts"===e?this.checkForMergeConflicts():"everything"===e&&(this.fetchUncommittedChanges(),this.fetchSmartlogCommits(),this.checkForMergeConflicts(),this.codeReviewProvider?.triggerDiffSummariesFetch(this.getAllDiffIds()))})),this.operationQueue=new D(this.logger,((e,t,s,i)=>{if(e.runner===n.CommandRunner.Graphite)return this.runOperation(e,s,t,i);if(e.runner===n.CommandRunner.CodeReviewProvider){const n=this.normalizeOperationArgs(t,e.args);return null==this.codeReviewProvider?.runExternalCommand?Promise.reject(Error("CodeReviewProvider does not support running external commands")):this.codeReviewProvider?.runExternalCommand(t,n,s,i)??Promise.resolve()}return Promise.resolve()}));const i=new Set,r=this.subscribeToSmartlogCommitsChanges((e=>{if(e.commits.value){const t=[],s=e.commits.value.filter((e=>e.pr)).map((e=>e.pr?.number));for(const e of s)i.has(e)||(t.push(e),i.add(e));t.length>0&&this.codeReviewProvider?.triggerDiffSummariesFetch(this.getAllDiffIds())}}));this.checkForMergeConflicts(),this.disposables.push((()=>r.dispose()))}nextVisibleCommitRangeInDays(){return this.currentVisibleCommitRangeIndex+1<this.visibleCommitRanges.length&&this.currentVisibleCommitRangeIndex++,this.visibleCommitRanges[this.currentVisibleCommitRangeIndex]}dispose(){this.disposables.forEach((e=>e())),this.codeReviewProvider?.dispose(),this.watchForChanges.dispose()}onChangeConflictState(e){return this.mergeConflictsEmitter.on("change",e),this.mergeConflicts&&e(this.mergeConflicts),{dispose:()=>this.mergeConflictsEmitter.off("change",e)}}checkForMergeConflicts=j((async()=>{this.logger.info("checking for merge conflicts");const e=null!=this.mergeConflicts;if(!e&&!await(t=l().join(this.info.dotdir,"rebase-merge"),r().promises.stat(t).then((()=>!0)).catch((e=>{if("ENOENT"===e.code)return!1;throw e}))))return void this.logger.info(`conflict state still the same (${e?"IN merge conflict":"NOT in conflict"})`);var t;null==this.mergeConflicts&&(this.mergeConflicts={state:"loading"},this.mergeConflictsEmitter.emit("change",this.mergeConflicts));const s=Date.now();let n;try{const e=await this.runCommand(["internal-only","status"]);n=JSON.parse(e.stdout)}catch(e){return this.logger.error(`failed to check for merge conflicts: ${e}`),this.mergeConflicts=void 0,void this.mergeConflictsEmitter.emit("change",this.mergeConflicts)}if(this.mergeConflicts=function(e,t,s){const n=t;if(!n?.conflicts)return;const i=n.files.filter((e=>"UNRESOLVED"===e.status)),r={state:"loaded",files:[],fetchStartTimestamp:s,fetchCompletedTimestamp:Date.now()};if(null!=e?.files&&e.files.length>0){const t=new Set(i.map((e=>e.path)));r.files=e.files.map((e=>t.has(e.path)?{path:e.path,status:"UNRESOLVED"}:{path:e.path,status:"RESOLVED"}))}else r.files=i.map((e=>({path:e.path,status:"UNRESOLVED"})));return r}(this.mergeConflicts,n,s),this.logger.info(`repo ${this.mergeConflicts?"IS":"IS NOT"} in merge conflicts`),this.mergeConflicts){const e=20,t=(this.mergeConflicts.files??[]).filter((e=>"UNRESOLVED"===e.status)).map((e=>e.path)).slice(0,e);this.logger.info("remaining files with conflicts: ",t)}this.mergeConflictsEmitter.emit("change",this.mergeConflicts)}));getMergeConflicts(){return this.mergeConflicts}static async getRepoInfo(e,t,s){const n=await async function(e,t,s){try{return(await H({command:e,args:["--version"],logger:t,cwd:s})).stdout}catch(e){throw t.error(`Failed to find gt version in ${s}`,e),e}}(e,t,s).catch((e=>e));if(n instanceof Error)return{type:"invalidCommand",command:e??"gt"};if("local"!==n&&R().lt(n,U))return{type:"invalidVersion",command:e??"gt",versionFound:n,versionRequired:U};const[i,r,o]=await Promise.all([W(e,t,s),z(e,t,s),B(e,t,s,"graphite.branch_edit").then((e=>e??"amend"))]);if(null==r)return{type:"cwdNotARepository",cwd:s};let a;if(void 0===r.remote)a={type:"none"};else{const{owner:e,name:t,hostname:s}=r.remote;a={type:"github",owner:e,repo:t,hostname:s}}const c={type:"success",command:e,dotdir:r.dotDir,repoRoot:r.rootDir,codeReviewSystem:a,preferredBranchEdit:o,profile:i,trunkBranch:r.trunkBranch};return t.info("repo info: ",c),c}async runOrQueueOperation(e,t,s,n){await this.operationQueue.runOrQueueOperation(e,t,s,n),this.watchForChanges.poll("force")}abortRunningOpeation(e){this.operationQueue.abortRunningOperation(e)}normalizeOperationArgs(e,t){const s=(0,n.unwrap)(this.info.repoRoot);return t.map((t=>{if("object"==typeof t)switch(t.type){case"repo-relative-file":return l().normalize(l().relative(e,l().join(s,t.path)));case"succeedable-revset":return`max(successors(${t.revset}))`}return t}))}async runOperation(e,t,s,n){const i=this.normalizeOperationArgs(s,e.args),{stdin:r}=e,{command:o,args:a,options:c}=V(this.info.command,i,s,r?{input:r}:void 0);this.logger.log("run operation: ",o,i.join(" "));const l=O()(o,a,{...c,stdout:"pipe",stderr:"pipe"});t("spawn"),l.stdout?.on("data",(e=>{t("stdout",e.toString())})),l.stderr?.on("data",(e=>{t("stderr",e.toString())})),l.on("exit",(e=>{t("exit",e||0)})),n.addEventListener("abort",(()=>{this.logger.log("kill operation: ",o,i.join(" "))})),function(e,t){t.addEventListener("abort",(()=>{"win32"==g().platform()?e.kill("SIGKILL",{forceKillAfterTimeout:!1}):(e.kill("SIGCONT"),e.kill("SIGTERM",{forceKillAfterTimeout:5e3}))}))}(l,n),await l}setPageFocus(e,t){this.pageFocusTracker.setState(e,t)}getUncommittedChanges(){return this.uncommittedChanges}subscribeToUncommittedChanges(e){return this.uncommittedChangesEmitter.on("change",e),{dispose:()=>{this.uncommittedChangesEmitter.off("change",e)}}}fetchUncommittedChanges=j((async()=>{const e=Date.now();try{this.uncommittedChangesBeginFetchingEmitter.emit("start");const t=await this.runCommand(["internal-only","status"]),s=JSON.parse(t.stdout).files.map((e=>{return{...e,path:(t=e.path,t.startsWith(l().sep)?t.slice(1):t)};var t}));this.uncommittedChanges={fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),files:{value:s}},this.uncommittedChangesEmitter.emit("change",this.uncommittedChanges)}catch(s){if(this.logger.error("Error fetching files: ",s),null!=(t=s)&&"object"==typeof t&&"stderr"in t&&s.stderr.includes("checkout is currently in progress"))return void this.logger.info("Ignoring `hg status` error caused by in-progress checkout");this.uncommittedChangesEmitter.emit("change",{fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),files:{error:s instanceof Error?s:new Error(s)}})}var t}));getSmartlogCommits(){return this.smartlogCommits}subscribeToSmartlogCommitsChanges(e){return this.smartlogCommitsChangesEmitter.on("change",e),{dispose:()=>{this.smartlogCommitsChangesEmitter.off("change",e)}}}subscribeToSmartlogCommitsBeginFetching(e){const t=()=>e(!0);return this.smartlogCommitsBeginFetchingEmitter.on("start",t),{dispose:()=>{this.smartlogCommitsBeginFetchingEmitter.off("start",t)}}}subscribeToUncommittedChangesBeginFetching(e){const t=()=>e(!0);return this.uncommittedChangesBeginFetchingEmitter.on("start",t),{dispose:()=>{this.uncommittedChangesBeginFetchingEmitter.off("start",t)}}}fetchSmartlogCommits=j((async()=>{const e=Date.now();try{this.smartlogCommitsBeginFetchingEmitter.emit("start");const t=await this.runCommand(["internal-only","log"]),s=function(e,t){let s=[];try{s=JSON.parse(t)}catch(t){e.error("failed to parse branch info",t)}return s}(this.logger,t.stdout.trim());if(0===s.length)throw new Error(n.ErrorShortMessages.NoCommitsFetched);this.smartlogCommits={fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),commits:{value:s}},this.smartlogCommitsChangesEmitter.emit("change",this.smartlogCommits)}catch(t){this.logger.error("Error fetching commits: ",t),this.smartlogCommitsChangesEmitter.emit("change",{fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),commits:{error:t instanceof Error?t:new Error(t)}})}}));subscribeToHeadCommit(e){let t=this.smartlogCommits?.commits.value?.find((e=>e.isHead));null!=t&&e(t);const s=s=>{const n=s?.commits.value?.find((e=>e.isHead));null!=n&&n.branch!==t?.branch&&(e(n),t=n)};return this.smartlogCommitsChangesEmitter.on("change",s),{dispose:()=>{this.smartlogCommitsChangesEmitter.off("change",s)}}}catLimiter=new P(4,(e=>this.logger.info("[cat]",e)));cat(e,t){const s=l().relative(this.info.repoRoot,e);return this.catLimiter.enqueueRun((async()=>(await this.runCommand(["internal-only","relative-cat",...this.catArgs(t,s)],void 0,{stripFinalNewline:!1})).stdout))}catArgs(e,t){switch(e.type){case n.ComparisonType.UncommittedChanges:return["uncommitted",t];case n.ComparisonType.HeadChanges:return["head",t];case n.ComparisonType.StackChanges:return["stack",t];case n.ComparisonType.Committed:return["stack",t,"--ref",e.hash]}}getAllDiffIds(){return this.getSmartlogCommits()?.commits.value?.map((e=>e.pr?.number)).filter(n.notEmpty)??[]}runCommand(e,t,s){return H({command:this.info.command,args:e,logger:this.logger,cwd:(0,n.unwrap)(t??this.info.repoRoot),options:s})}getConfig(e){return B(this.info.command,this.logger,this.info.repoRoot,e)}setConfig(e,t,s){return async function({command:e,logger:t,cwd:s,level:n,configName:i,configValue:r}){await H({command:e,args:["internal-only","set-config","--level",n,i,r],logger:t,cwd:s})}({command:this.info.command,logger:this.logger,cwd:this.info.repoRoot,level:e,configName:t,configValue:s})}}function H({command:e,args:t,logger:s,cwd:n,options:i}){const{command:r,args:o,options:a}=V(e,t,n,i);return s&&s.log("run command: ",r,...o),O()(r,o,a)}async function z(e,t,s){try{return JSON.parse((await H({command:e,args:["internal-only","repo-info"],logger:t,cwd:s})).stdout)}catch(e){return void t.error(`Failed to find repository info in ${s}`,e)}}async function W(e,t,s){try{return JSON.parse((await H({command:e,args:["internal-only","profile"],logger:t,cwd:s})).stdout)}catch(e){return t.error(`Failed to find repository profile in ${s}`,e),{appUrl:"https://app.graphite.dev/"}}}async function B(e,t,s,n){try{return(await H({command:e,args:["internal-only","config",n],logger:t,cwd:s})).stdout.trim()}catch{return}}function V(e,t,s,n){let i=[...t];"win32"!==process.platform&&(i=i.map((e=>e.replace(/\\\\/g,"\\"))));const r={...n,env:{LANG:"en_US.utf-8",EDITOR:void 0,GRAPHITE_INTERACTIVE:"true"},cwd:s};return!e&&process.argv[1].startsWith("/snapshot/")?(e=process.argv[0],i=["/snapshot/monologue/apps/public/cli/dist/graphite.js",...i]):e||(e="gt"),{command:e,args:i,options:r}}var G=s(32081);const J={platformName:"browser",handleMessageFromClient:(e,t)=>{switch(t.type){case"platform/openFile":{const s=l().join((0,n.unwrap)(e?.info.repoRoot),t.path);let i;if(null==i)switch(process.platform){case"darwin":i="/usr/bin/open";break;case"win32":i="notepad.exe";break;case"linux":i="xdg-open"}if(i){e?.logger.log("open file",s);const t=(0,G.spawn)(i,[s],{detached:!0,stdio:"ignore",windowsHide:!1,windowsVerbatimArguments:!0});t.on("error",(t=>{e?.logger.log("failed to open",s,t)})),t.unref()}break}}}};class Q{promise;disposeFunc;constructor(e,t){this.promise=e,this.disposeFunc=t}unref(){this.disposed||(this.disposed=!0,this.disposeFunc())}internalReference;disposed=!1}class K{value;constructor(e){this.value=e}references=0;isDisposed=!1;ref(){this.references++}getNumberOfReferences(){return this.references}dispose(){this.references--,this.isDisposed||0!==this.references||(this.isDisposed=!0,this.value.dispose())}}const X=new class{RepositoryType;constructor(e=q){this.RepositoryType=e}reposByRoot=new Map;activeReposEmitter=new _;lookup(e){for(const s of this.reposByRoot.values())if((e===s.value.info.repoRoot||e.startsWith((t=s.value.info.repoRoot).endsWith(l().sep)?t:t+l().sep))&&!s.isDisposed)return s;var t}getOrCreate(e,t,s){const n=this.lookup(s);if(n)return n.ref(),new Q(Promise.resolve(n.value),(()=>n.dispose()));let i;return i=new Q((async()=>{const n=await this.RepositoryType.getRepoInfo(e,t,s);if("success"!==n.type)return n;if(i.disposed)return{type:"unknownError",error:new Error("Repository already disposed")};const r=this.lookup(n.repoRoot);if(r)return r.ref(),i.internalReference=r,r.value;const o=new this.RepositoryType(n,t),a=new K(o);return a.ref(),i.internalReference=a,this.reposByRoot.set(n.repoRoot,a),this.activeReposEmitter.emit("change"),o})(),(()=>{i.internalReference&&i.internalReference.dispose(),i.unref()})),i}cachedRepositoryForPath(e){const t=this.lookup(e);return t?.value}onChangeActiveRepos(e){const t=()=>{e([...this.reposByRoot.values()].map((e=>e.value)))};return this.activeReposEmitter.on("change",t),t(),()=>this.activeReposEmitter.off("change",t)}clearCache(){this.reposByRoot.forEach((e=>e.dispose())),this.reposByRoot=new Map,this.activeReposEmitter.removeAllListeners()}numberOfActiveServers(){let e=0;for(const t of this.reposByRoot.values())e+=t.getNumberOfReferences();return e}};class Y{platform;connection;tracker;logger;listenersByType=new Map;incomingListener;repoDisposables=[];subscriptions=new Map;activeRepoRef;queuedMessages=[];currentState={type:"loading"};pageId=(0,n.randomId)();constructor(e,t,s,i){this.platform=e,this.connection=t,this.tracker=s,this.logger=i;let r=null;this.incomingListener=this.connection.onDidReceiveMessage(((e,s)=>{if(s)return null==r?void t.logger?.error("Error: got a binary message when not expecting one"):(this.handleIncomingMessageWithPayload(r,e),void(r=null));if(null!=r)return t.logger?.error("Error: didnt get binary payload after a message that requires one"),void(r=null);const i=e.toString("utf-8"),o=(0,n.deserializeFromString)(i);if(function(e){return null!=e&&"object"==typeof e&&!0===e.hasBinaryPayload}(o))r=o;else if("loading"===this.currentState.type)this.queuedMessages.push(o);else try{this.handleIncomingMessage(o)}catch(e){t.logger?.error("error handling incoming message: ",o,e)}}))}setRepoError(e){this.disposeRepoDisposables(),this.currentState={type:"error",error:e},this.tracker.context.setRepo(void 0),this.processQueuedMessages()}setCurrentRepo(e,t){this.disposeRepoDisposables(),this.currentState={type:"repo",repo:e,cwd:t},this.tracker.context.setRepo(e),null!=e.codeReviewProvider&&this.repoDisposables.push(e.codeReviewProvider.onChangeDiffSummaries((e=>{this.postMessage({type:"fetchedDiffSummaries",summaries:e})}))),this.repoDisposables.push(e.subscribeToHeadCommit((t=>{const s=e.getSmartlogCommits(),n=function(e,t){let s;if(null!=e){const n=new Map(e.map((e=>[e.branch,e])));let i=t;for(;null!=i;){if(i.partOfTrunk){s=i;break}if(null==i.parents[0])break;i=n.get(i.parents[0])}}return s}(s?.commits.value,t);this.tracker.track("HeadCommitChanged",{extras:{hash:t.branch,public:n?.branch}})}))),this.processQueuedMessages()}postMessage(e){this.connection.postMessage((0,n.serializeToString)(e)).catch((()=>{console.warn("Failed to post message to client")}))}setActiveRepoForCwd(e){void 0!==this.activeRepoRef&&this.activeRepoRef.unref(),this.logger.info(`Setting active repo cwd to ${e}`),this.currentState={type:"loading"};const t=this.connection.command;this.activeRepoRef=X.getOrCreate(t,this.logger,e),this.activeRepoRef.promise.then((t=>{t instanceof q?this.setCurrentRepo(t,e):this.setRepoError(t)}))}dispose(){this.incomingListener.dispose(),this.disposeRepoDisposables(),void 0!==this.activeRepoRef&&this.activeRepoRef.unref()}disposeRepoDisposables(){this.repoDisposables.forEach((e=>e.dispose())),this.repoDisposables=[],this.subscriptions.forEach((e=>e.dispose())),this.subscriptions.clear()}processQueuedMessages(){for(const e of this.queuedMessages)try{this.handleIncomingMessage(e)}catch(t){this.connection.logger?.error("error handling queued message: ",e,t)}this.queuedMessages=[]}handleIncomingMessageWithPayload(e,t){switch(e.type){case"uploadFile":{const{id:s,filename:i}=e,r=null;if(null==r)return;this.tracker.operation("UploadImage","UploadImageError",{},(()=>r((0,n.unwrap)(this.connection.logger),{filename:i,data:t}))).then((e=>{this.connection.logger?.info("sucessfully uploaded file",i,e),this.postMessage({type:"uploadFileResult",id:s,result:{value:e}})})).catch((e=>{this.connection.logger?.info("error uploading file",i,e),this.postMessage({type:"uploadFileResult",id:s,result:{error:e}})}));break}}}handleIncomingMessage(e){this.handleIncomingGeneralMessage(e);const{currentState:t}=this;switch(t.type){case"repo":{const{repo:s,cwd:n}=t;this.handleIncomingMessageWithRepo(e,s,n);break}case"loading":case"error":e.type.startsWith("platform/")&&(this.platform.handleMessageFromClient(void 0,e,(e=>this.postMessage(e)),(e=>{this.repoDisposables.push({dispose:e})})),this.notifyListeners(e))}}handleIncomingGeneralMessage(e){switch(e.type){case"track":this.tracker.trackData(e.data);break;case"changeCwd":this.setActiveRepoForCwd(e.cwd);break;case"requestRepoInfo":switch(this.currentState.type){case"repo":this.postMessage({type:"repoInfo",info:this.currentState.repo.info,cwd:this.currentState.cwd});break;case"error":this.postMessage({type:"repoInfo",info:this.currentState.error})}break;case"requestApplicationInfo":this.postMessage({type:"applicationInfo",platformName:this.platform.platformName,version:this.connection.version})}}handleIncomingMessageWithRepo(e,t,s){const{logger:i}=t;switch(e.type){case"subscribe":{const{subscriptionID:s,kind:n}=e;switch(n){case"uncommittedChanges":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"uncommittedChanges",subscriptionID:s,data:e})},n=t.getUncommittedChanges();null!=n&&e(n);const i=[];i.push(t.subscribeToUncommittedChanges(e)),t.fetchUncommittedChanges(),i.push(t.subscribeToUncommittedChangesBeginFetching((()=>this.postMessage({type:"beganFetchingUncommittedChangesEvent"})))),this.subscriptions.set(s,{dispose:()=>{i.forEach((e=>e.dispose()))}});break}case"smartlogCommits":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"smartlogCommits",subscriptionID:s,data:e})},n=t.getSmartlogCommits();null!=n&&e(n);const i=[];i.push(t.subscribeToSmartlogCommitsChanges(e)),t.fetchSmartlogCommits(),i.push(t.subscribeToSmartlogCommitsBeginFetching((()=>this.postMessage({type:"beganFetchingSmartlogCommitsEvent"})))),this.subscriptions.set(s,{dispose:()=>{i.forEach((e=>e.dispose()))}});break}case"mergeConflicts":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"mergeConflicts",subscriptionID:s,data:e})},n=t.getMergeConflicts();null!=n&&e(n),this.subscriptions.set(s,t.onChangeConflictState(e));break}}break}case"unsubscribe":{const t=this.subscriptions.get(e.subscriptionID);t?.dispose(),this.subscriptions.delete(e.subscriptionID);break}case"runOperation":{const{operation:n}=e;t.runOrQueueOperation(n,(e=>{this.postMessage({type:"operationProgress",...e}),"queue"===e.kind&&this.tracker.track("QueueOperation",{extras:{operation:n.trackEventName}})}),this.tracker,s);break}case"abortRunningOperation":{const{operationId:s}=e;t.abortRunningOpeation(s);break}case"getConfig":t.getConfig(e.name).catch((()=>{})).then((t=>{i.info("got config",e.name,t),this.postMessage({type:"gotConfig",name:e.name,value:t})}));break;case"fetchRepoMessage":t.runCommand(["internal-only","repo-message"]).then((e=>({value:e.stdout}))).catch((e=>(i?.error("error fetching repo message",e.toString()),{error:e}))).then((e=>this.postMessage({type:"fetchedRepoMessage",message:e.value||""})));break;case"fetchUpgradePrompt":t.runCommand(["internal-only","upgrade-prompt"]).then((e=>({value:e.stdout}))).catch((e=>(i?.error("error fetching upgrade prompt",e.toString()),{error:e}))).then((e=>this.postMessage({type:"fetchedUpgradePrompt",message:e.value||""})));break;case"setConfig":i.info("set config",e.name,e.value),t.setConfig("user",e.name,e.value).catch((t=>{i.error("error setting config",e.name,e.value,t)}));break;case"deleteFile":{const{filePath:s}=e,n=function(e,t,s=l()){const n=s.resolve(t.info.repoRoot,e);return n.startsWith(t.info.repoRoot+s.sep)?n:null}(s,t);if(null==n)return void i.warn("can't delete file outside of the repo",s);r().promises.rm(n).then((()=>{i.info("deleted file from filesystem",n)})).catch((e=>{i.error("unable to delete file",n,e)}));break}case"requestComparison":{const{comparison:s}=e;t.runCommand(["internal-only","diff",...(0,n.revsetArgsForComparison)(s)]).then((e=>({value:e.stdout}))).catch((e=>(i?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"comparison",comparison:s,data:{diff:e}})));break}case"requestChangedFiles":{const{branch:s}=e;t.runCommand(["internal-only","changed-files",s]).then((e=>JSON.parse(e.stdout))).catch((e=>(i?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"changedFiles",branch:s,data:e})));break}case"requestComparisonContextLines":{const{id:{path:s,comparison:n},start:i,numLines:r}=e;t.cat(s,n).catch((()=>"")).then((e=>this.postMessage({type:"comparisonContextLines",lines:e.split("\n").slice(i-1,i-1+r),path:s})));break}case"refresh":i?.log("refresh requested"),t.fetchSmartlogCommits(),t.fetchUncommittedChanges(),t.codeReviewProvider?.triggerDiffSummariesFetch(t.getAllDiffIds());break;case"pageVisibility":t.setPageFocus(this.pageId,e.state);break;case"fetchCommitMessageTemplate":t.runCommand(["internal-only","templates"]).then((e=>{const s=JSON.parse(e.stdout);this.postMessage({type:"fetchedCommitMessageTemplate",templates:Object.fromEntries(Object.entries(s).map((([e,s])=>[e,s.replace(t.IGNORE_COMMIT_MESSAGE_LINES_REGEX,"")])))})})).catch((e=>{i?.error("Could not fetch commit message template",e)}));break;case"typeahead":t.codeReviewProvider?.typeahead?.(e.kind,e.query)?.then((t=>this.postMessage({type:"typeaheadResult",id:e.id,result:t})));break;case"fetchDiffSummaries":t.codeReviewProvider?.triggerDiffSummariesFetch(t.getAllDiffIds());break;case"loadMoreCommits":{const e=t.nextVisibleCommitRangeInDays();return this.postMessage({type:"commitsShownRange",rangeInDays:e}),this.postMessage({type:"beganLoadingMoreCommits"}),t.fetchSmartlogCommits(),void this.tracker.track("LoadMoreCommits",{extras:{daysToFetch:e??"Infinity"}})}default:this.platform.handleMessageFromClient(t,e,(e=>this.postMessage(e)),(e=>{this.repoDisposables.push({dispose:e})}))}this.notifyListeners(e)}notifyListeners(e){const t=this.listenersByType.get(e.type);t&&t.forEach((t=>t(e)))}}var Z=s(6113);const ee="win32"==process.platform?l().join((0,n.unwrap)(process.env.LOCALAPPDATA),"cache"):"darwin"==process.platform?l().join(g().homedir(),"Library/Caches"):process.env.XDG_CACHE_HOME||l().join(g().homedir(),".cache");function te(e,t){const s=Buffer.from(e),n=Buffer.from(t);return s.length===n.length&&(0,Z.timingSafeEqual)(s,n)}function se(e){const t=e.logger??(e.logFileLocation?function(e){const t=(...t)=>{const s=w().format(...t)+"\n";r().promises.appendFile(e,s)};return{info:t,log:t,warn:t,error:t,getLogFileContents:()=>r().promises.readFile(e,"utf-8")}}(e.logFileLocation):C);e.logger=t;const s=e?.platform??J,i=e?.version??"unknown";t.log(`establish client connection for ${e.cwd}`),t.log(`platform '${s.platformName}', version '${i}'`);const o=function(e,t,s,i=b){return new n.Tracker(((e,t)=>{const{logger:s}=t;s.log("[track]",e.eventName,e.errorName??"",null!=e.extras?JSON.stringify(e.extras):"");try{Promise.resolve(i({...e,...t.data})).catch((e=>{}))}catch{}}),new v(e,function(e,t){return{platform:e,version:t,repo:void 0,sessionId:(0,n.randomId)(),unixname:f(),osArch:g().arch(),osType:g().platform(),osRelease:g().release(),hostname:g().hostname()}}(t.platformName,s)))}(t,s,i,(t=>H({command:e.command||"gt",args:["internal-only","log-action",t.eventName||t.errorName||"UNKNOWN_CLI_EVENT",(t.timestamp?new Date(t.timestamp):new Date).toISOString(),JSON.stringify(t)],cwd:e.cwd})));o.track("ClientConnection",{extras:{cwd:e.cwd}});let a=new Y(s,e,o,t);return a.setActiveRepoForCwd(e.cwd),()=>{a?.dispose(),a=null}}function ne({port:e,sensitiveToken:t,challengeToken:s,logFileLocation:i,logInfo:o,command:c,gtVersion:h,foreground:d,frontendDir:p}){return new Promise((g=>{try{const e=JSON.parse(r().readFileSync(l().join(p,"build/asset-manifest.json"),"utf-8"));for(const t of Object.values(e.files))t.startsWith("/")||g({type:"error",error:`expected entry to start with / but was: \`${t}\``}),oe[t]=t.slice(1)}catch(e){}oe["/favicon.ico"]="favicon.ico";const f=a().createServer((async(e,n)=>{if(e.url){const{pathname:o}=u().parse(e.url);if(null!=o&&oe.hasOwnProperty(o)){const e=oe[o];let t;try{t=await r().promises.readFile(l().join(p,"build",e))}catch(e){return n.writeHead(500,{"Content-Type":"text/plain"}),void n.end((i=e.toString(),i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#27;")))}const s=e.lastIndexOf("."),a=e.slice(s+1),c=re[a]??"text/plain";return n.writeHead(200,{"Content-Type":c}),void n.end(t)}if("/challenge_authenticity"===o){const i=ie(e.url).get("token");if(i&&te(i,t)){n.writeHead(200,{"Content-Type":"text/json"});const e={challengeToken:s,pid:process.pid};n.end(JSON.stringify(e))}else n.writeHead(401,{"Content-Type":"text/json"}),n.end(JSON.stringify({error:"invalid token"}));return}}var i;n.writeHead(404,{"Content-Type":"text/html"}),n.end("<html><body>Not Found!</body></html>")})),v=f.listen(e),b=new(m().Server)({noServer:!0,path:"/ws"});b.on("connection",((e,s)=>{let r,a,l;if(s.url){const e=ie(s.url);r=e.get("token");const t=e.get("cwd");l=e.get("platform"),t&&(a=decodeURIComponent(t))}if(!r){const t="No token provided in websocket request";return o("closing ws:",t),void e.close(n.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE,t)}if(!te(r,t)){const t="Invalid token";return o("closing ws:",t),void e.close(n.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE,t)}const u=se({postMessage:t=>(e.send(t),Promise.resolve(!0)),onDidReceiveMessage(t){const s=e.on("message",t);return{dispose:()=>s.off("message",t)}},cwd:a??process.cwd(),logFileLocation:"stdout"===i?void 0:i,command:c,version:h,platform:void 0});e.on("close",(()=>{u(),d||setTimeout((()=>{0===X.numberOfActiveServers()&&process.exit(0)}),6e4)}))})),v.on("upgrade",((e,t,s)=>{b.handleUpgrade(e,t,s,(t=>{b.emit("connection",t,e)}))})),f.on("error",(function(t){if("listen"!==t.syscall)throw g({type:"error",error:t.toString()}),t;switch(t.code){case"EACCES":throw g({type:"error",error:`Port ${e} requires elevated privileges`}),t;case"EADDRINUSE":return void g({type:"addressInUse"});default:throw g({type:"error",error:t.toString()}),t}})),f.on("listening",(()=>g({type:"success",port:f.address().port,pid:process.pid})))}))}function ie(e){const t=u().parse(e).search?.replace(/^\?/,"").split("&").map((e=>e.split("=")));return new Map(t)}l().join(ee,"graphite-gti");const re={css:"text/css",html:"text/html",js:"text/javascript",ttf:"font/ttf"},oe={"/":"index.html"}}};
2
+ "use strict";exports.id=325,exports.ids=[325],exports.modules={33800:(e,t)=>{var s;Object.defineProperty(t,"__esModule",{value:!0}),t.comparisonIsAgainstHead=t.labelForComparison=t.revsetArgsForComparison=t.ComparisonType=void 0,function(e){e.UncommittedChanges="UNCOMMITTED",e.HeadChanges="HEAD",e.StackChanges="STACK",e.Committed="InCommit"}(s=t.ComparisonType||(t.ComparisonType={})),t.revsetArgsForComparison=function(e){switch(e.type){case s.UncommittedChanges:return["uncommitted"];case s.HeadChanges:return["head"];case s.StackChanges:return["stack"];case s.Committed:return["stack","--ref",e.hash]}},t.labelForComparison=function(e){switch(e.type){case s.UncommittedChanges:return"Uncommitted Changes";case s.HeadChanges:return"Head Changes";case s.StackChanges:return"Stack Changes";case s.Committed:return`In ${e.hash}`}},t.comparisonIsAgainstHead=function(e){switch(e.type){case s.UncommittedChanges:case s.HeadChanges:case s.StackChanges:return!0;case s.Committed:return!1}}},52060:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},2982:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cached=t.LRU=void 0;const n=s(30826);class i{constructor(e,t=3){this.maxItems=e,this.maxHashCollision=t,this.cache=new Map}get(e){let t;const s=r(e),i=this.cache.get(s);if(void 0!==i){const r=i.get(e);if(void 0!==r)t=r;else for(const[s,r]of i)if((0,n.is)(e,s)){t=r;break}this.cache.delete(s),this.cache.set(s,i)}return t}set(e,t){const s=r(e);let n=this.cache.get(s);if(void 0===n||n.size>=this.maxHashCollision?n=new Map([[e,t]]):n.set(e,t),this.cache.delete(s),void 0!==t&&(this.cache.set(s,n),this.cache.size>this.maxItems)){const e=this.cache.keys().next();e.done||this.cache.delete(e.value)}}delete(e){const t=r(e);this.cache.delete(t)}clear(){this.cache.clear()}}function r(e){const t=null==e?void 0:e.hashCode;return void 0!==t?t.apply(e):e}function o(e,t){var s,r;const o=null!==(s=null==t?void 0:t.cache)&&void 0!==s?s:new i(null!==(r=null==t?void 0:t.cacheSize)&&void 0!==r?r:10),a=null==t?void 0:t.getExtraKeys,l=function(...t){var s,i,r;const l=o.stats;if(!t.every(c))return null!=l&&(l.skip=(null!==(s=l.skip)&&void 0!==s?s:0)+1),e.apply(this,t);const h=(0,n.List)(a?[...a.apply(this),...t]:t),u=o.get(h);if(void 0!==u)return null!=l&&(l.hit=(null!==(i=l.hit)&&void 0!==i?i:0)+1),u;null!=l&&(l.miss=(null!==(r=l.miss)&&void 0!==r?r:0)+1);const d=e.apply(this,t);return o.set(h,d),d};return l.cache=o,l}t.LRU=i,t.cached=function(e,t){return"function"==typeof e?o(e,t):function(e){var t;const s=null!==(t=null==e?void 0:e.getExtraKeys)&&void 0!==t?t:function(){return(0,n.isValueObject)(this)?[this]:null!=this&&"object"==typeof this?Object.values(this).filter(c):[]};return function(t,n,i){const r=i.value;i.value=o(r,Object.assign(Object.assign({},e),{getExtraKeys:s}))}}(e)};const a=new Set(["number","string","boolean","symbol","bigint","undefined","null"]);function c(e){if(null==e)return!0;const t=typeof e;return!!a.has(t)||!("object"!==t||!(0,n.isValueObject)(e))}},61110:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5693:function(e,t,s){var n=this&&this.__createBinding||(Object.create?function(e,t,s,n){void 0===n&&(n=s);var i=Object.getOwnPropertyDescriptor(t,s);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,n,i)}:function(e,t,s,n){void 0===n&&(n=s),e[n]=t[s]}),i=this&&this.__exportStar||function(e,t){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(t,s)||n(t,e,s)};Object.defineProperty(t,"__esModule",{value:!0}),i(s(61110),t),i(s(52568),t),i(s(11268),t),i(s(66877),t)},52568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},11268:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Tracker=void 0;const n=s(48427);class i{constructor(e,t){this.sendData=e,this.context=t}error(e,t,s,n){const i=s instanceof Error?s.message||String(s):s;return this.track(e,Object.assign(Object.assign({},null!=n?n:{}),{errorMessage:i,errorName:t}))}operation(e,t,s,i){var r;const o=Date.now(),a=null!==(r=null==s?void 0:s.id)&&void 0!==r?r:(0,n.randomId)();try{const r=i({parentId:a});if((0,n.isPromise)(r))return r.then((t=>{const n=Date.now()-o;return this.track(e,Object.assign(Object.assign({},null!=s?s:{}),{duration:n,id:a})),t})).catch((n=>{const i=Date.now()-o;return this.error(e,t,n,Object.assign(Object.assign({},null!=s?s:{}),{duration:i,id:a})),Promise.reject(n)}));{const t=Date.now()-o;return this.track(e,Object.assign(Object.assign({},null!=s?s:{}),{duration:t,id:a})),r}}catch(n){const i=Date.now()-o;throw this.error(e,t,n,Object.assign(Object.assign({},null!=s?s:{}),{duration:i,id:a})),n}}trackAsParent(e,t){var s;const r=null!==(s=null==t?void 0:t.id)&&void 0!==s?s:(0,n.randomId)();return this.trackData(Object.assign(Object.assign({},t),{eventName:e,id:r})),new i(((e,t)=>this.trackData(Object.assign(Object.assign({},e),t))),{parentId:r})}track(e,t){return this.trackData(Object.assign(Object.assign({},t),{eventName:e}))}trackData(e){var t,s;const i=null!==(t=null==e?void 0:e.id)&&void 0!==t?t:(0,n.randomId)(),r=null!==(s=null==e?void 0:e.timestamp)&&void 0!==s?s:Date.now(),o=Object.assign({timestamp:r,id:i},null!=e?e:{});this.sendData(o,this.context)}}t.Tracker=i},66877:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},33905:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.newAbortController=void 0;const n=s(53811);t.newAbortController=function(){return"function"==typeof AbortController?new AbortController:new n.AbortController}},66960:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0,t.debounce=function(e,t,s=void 0,n=!1){let i,r=!0;function o(...a){let c;if(n){if(c=function(){r=!0,i=void 0},!r)return clearTimeout(i),void(i=setTimeout(c,t));r=!1,e.apply(s,a)}else o.reset(),c=function(){i=void 0,e.apply(s,a)};i=setTimeout(c,t)}return o.reset=function(){clearTimeout(i),i=void 0,r=!0},o.isPending=function(){return null!=i},o}},90828:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SelfUpdate=void 0;class s{constructor(e){this.inner=e}hashCode(){return this.inner.hashCode()+1}equals(e){if(!(e instanceof s))return!1;if(this===e)return!0;const t=e.inner,n=this.inner.equals(t);return n&&this.inner!==t&&(this.inner=t),n}}t.SelfUpdate=s},98696:function(e,t,s){var n=this&&this.__createBinding||(Object.create?function(e,t,s,n){void 0===n&&(n=s);var i=Object.getOwnPropertyDescriptor(t,s);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,n,i)}:function(e,t,s,n){void 0===n&&(n=s),e[n]=t[s]}),i=this&&this.__exportStar||function(e,t){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(t,s)||n(t,e,s)};Object.defineProperty(t,"__esModule",{value:!0}),i(s(5693),t),i(s(33800),t),i(s(86099),t),i(s(40256),t),i(s(85249),t),i(s(48427),t),i(s(66224),t),i(s(2982),t),i(s(13035),t),i(s(90828),t),i(s(52060),t),i(s(66960),t),i(s(33905),t),i(s(75905),t)},13035:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.minimalDisambiguousPaths=void 0,t.minimalDisambiguousPaths=function(e,t={}){const s=e.map((e=>{const t=function(e){return e.replace(/[^\\]/g,"").length>e.replace(/[^/]/g,"").length?"\\":"/"}(e),s=/^(\w:).*/.exec(e),n=null!=s?s[1]:"";return{depth:null,parts:e.split(t).reverse().filter((e=>""!==e&&e!==n)),rootPrefix:n,separator:t,hadLeadingSeparator:e.startsWith(t)||n.length>0&&e.startsWith(n)}})),n=null==t.maxDepth?Math.max(...s.map((e=>e.parts.length))):t.maxDepth,i=new Set(s),r=new Map;for(let e=1;e<=n;e++){r.clear();for(const t of i){const s=t.parts.slice(0,e).join(t.separator);r.has(s)||r.set(s,new Set),r.get(s).add(t)}for(const t of r.values())if(1===t.size){const s=Array.from(t)[0];s.depth=e,i.delete(s)}}return s.map((({depth:e,parts:s,rootPrefix:i,separator:r,hadLeadingSeparator:o})=>{var a;let c=s.slice(0,null==e?n:e).reverse();return 0===c.length?`${i}${r}`:((1===c.length&&""===c[0]||c.length>1&&""!==c[0])&&(c=c.length===s.length?o?[i,...c]:c:(null!==(a=t.alwaysShowLeadingSeparator)&&void 0!==a?a:o)?["",...c]:c),c.join(r))}))}},75905:(e,t)=>{var s;Object.defineProperty(t,"__esModule",{value:!0}),t.parsePatch=t.DiffType=void 0,function(e){e.Modified="Modified",e.Added="Added",e.Removed="Removed",e.Renamed="Renamed",e.Copied="Copied"}(s=t.DiffType||(t.DiffType={}));const n=/^diff --git (.*) (.*)$/,i=/^rename from (.*)$/,r=/^rename to (.*)$/,o=/^copy from (.*)$/,a=/^copy to (.*)$/,c=/^new file mode (\d{6})$/,l=/^deleted file mode (\d{6})$/,h=/^old mode (\d{6})$/,u=/^new mode (\d{6})$/,d=/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/,m=/^--- (.*)$/,p=/^\+\+\+ (.*)$/,g=/\r\n|[\n\v\f\r\x85]/g;function f(e,t){if(!1===e)throw new Error(t)}t.parsePatch=function(e){const t=e.split(g),v=e.match(g)||[],b=[];let y=0;function w(){const e={hunks:[]};for(b.push(e),function(e){for(;y<t.length;){const s=t[y],i=n.exec(s);if(i){e.oldFileName=i[1],e.newFileName=i[2],y++;break}y++}}(e);y<t.length;){const s=t[y];if(/^old mode/.test(s))C(e);else if(/^new mode/.test(s))S(e);else if(/^deleted file mode/.test(s))O(e);else if(/^new file mode/.test(s))E(e);else if(/^copy /.test(s))R(e);else if(/^rename /.test(s))k(e);else{if(/^--- /.test(s)){_(e);break}if(/^diff --git/.test(s))break;y++}}!function(e){for(;y<t.length;){const s=t[y];if(n.test(s))break;/^@@/.test(s)?e.hunks.push(M()):y++}}(e)}function C(e){const n=h.exec(t[y]);f(null!==n,`invalid format '${t[y]}'`),e.oldMode=n[1],e.type=s.Modified,y++}function S(e){const n=u.exec(t[y]);f(null!==n,`invalid format '${t[y]}'`),e.newMode=n[1],e.type=s.Modified,y++}function O(e){const n=l.exec(t[y]);f(null!==n,`invalid format '${t[y]}'`),e.newMode=n[1],e.type=s.Removed,y++}function E(e){const n=c.exec(t[y]);f(null!==n,`invalid format '${t[y]}'`),e.newMode=n[1],e.type=s.Added,y++}function R(e){f(o.test(t[y]),`invalid format '${t[y]}'`),f(a.test(t[y+1]),`invalid format '${t[y+1]}'`),e.type=s.Copied,y+=2}function k(e){f(i.test(t[y]),`invalid format '${t[y]}'`),f(r.test(t[y+1]),`invalid format '${t[y+1]}'`),e.type=s.Renamed,y+=2}function _(e){f(m.test(t[y]),`invalid format '${t[y]}'`),f(p.test(t[y+1]),`invalid format '${t[y+1]}'`),void 0===e.type&&(e.type=s.Modified),y+=2}function M(){const e=t[y++].split(d),s={oldStart:+e[1],oldLines:void 0===e[2]?1:+e[2],newStart:+e[3],newLines:void 0===e[4]?1:+e[4],lines:[],linedelimiters:[]};0===s.oldLines&&(s.oldStart+=1),0===s.newLines&&(s.newStart+=1);let n=0,i=0;for(;y<t.length&&!(0===t[y].indexOf("--- ")&&y+2<t.length&&0===t[y+1].indexOf("+++ ")&&0===t[y+2].indexOf("@@"));y++){const e=0==t[y].length&&y!=t.length-1?" ":t[y][0];if("+"!==e&&"-"!==e&&" "!==e&&"\\"!==e)break;s.lines.push(t[y]),s.linedelimiters.push(v[y]||"\n"),"+"===e?n++:"-"===e?i++:" "===e&&(n++,i++)}return n||1!==s.newLines||(s.newLines=0),i||1!==s.oldLines||(s.oldLines=0),s}for(;y<t.length;)w();return b}},85249:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deserializeFromString=t.deserialize=t.serializeToString=t.serialize=void 0;const s={__rpcType:"undefined"};function n(e){if(void 0===e)return s;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e||null===e)return e;if(e instanceof Map)return{__rpcType:"Map",data:Array.from(e.entries()).map((([e,t])=>[n(e),n(t)]))};if(e instanceof Set)return{__rpcType:"Set",data:Array.from(e.values()).map(n)};if(e instanceof Error)return{__rpcType:"Error",data:{message:e.message,stack:e.stack}};if(e instanceof Date)return{__rpcType:"Date",data:e.valueOf()};if(Array.isArray(e))return e.map((e=>n(e)));if("object"==typeof e){const t={__rpcType:"object"};for(const[s,i]of Object.entries(e))t[s]=n(i);return t}throw new Error(`cannot serialize argument ${e}`)}function i(e){if("object"!=typeof e||null==e)return e;if(Array.isArray(e))return e.map((e=>i(e)));const t=e;switch(t.__rpcType){case"undefined":return;case"Map":return new Map(t.data.map((([e,t])=>[i(e),i(t)])));case"Set":return new Set(t.data.map(i));case"Error":{const e=new Error;return e.stack=t.data.stack,e.message=t.data.message,e}case"Date":return new Date(t.data);case"object":{const t=e,s={};for(const[e,n]of Object.entries(t))"__rpcType"!==e&&(s[e]=i(n));return s}default:throw new Error(`cannot deserialize unknown type ${t}`)}}t.serialize=n,t.serializeToString=function(e){return JSON.stringify(n(e))},t.deserialize=i,t.deserializeFromString=function(e){return i(JSON.parse(e))}},40256:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},66224:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},50209:(e,t)=>{var s;Object.defineProperty(t,"__esModule",{value:!0}),t.SucceedableRevset=t.CommandRunner=void 0,(s=t.CommandRunner||(t.CommandRunner={})).Graphite="gt",s.CodeReviewProvider="codeReviewProvider",t.SucceedableRevset=function(e){return{type:"succeedable-revset",revset:e}}},74259:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},45852:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},1018:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorShortMessages=t.DEFAULT_DAYS_OF_COMMITS_TO_LOAD=t.ONE_MINUTE_MS=t.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE=void 0,t.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE=4100,t.ONE_MINUTE_MS=6e4,t.DEFAULT_DAYS_OF_COMMITS_TO_LOAD=void 0,(t.ErrorShortMessages||(t.ErrorShortMessages={})).NoCommitsFetched="No commits found"},29641:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},86099:function(e,t,s){var n=this&&this.__createBinding||(Object.create?function(e,t,s,n){void 0===n&&(n=s);var i=Object.getOwnPropertyDescriptor(t,s);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,n,i)}:function(e,t,s,n){void 0===n&&(n=s),e[n]=t[s]}),i=this&&this.__exportStar||function(e,t){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(t,s)||n(t,e,s)};Object.defineProperty(t,"__esModule",{value:!0}),i(s(50209),t),i(s(85119),t),i(s(45852),t),i(s(74259),t),i(s(1018),t),i(s(29641),t)},85119:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},48427:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPromise=t.truncate=t.zip=t.generatorContains=t.mapObject=t.findParentWithClassName=t.basename=t.defer=t.randomId=t.unwrap=t.notEmpty=void 0,t.notEmpty=function(e){return null!=e},t.unwrap=function(e){if(null==e)throw new Error(`expected value not to be ${e}`);return e},t.randomId=function(){return Date.now().toString(36)+Math.random().toString(36)},t.defer=function(){const e={promise:void 0,resolve:void 0,reject:void 0};return e.promise=new Promise(((t,s)=>{e.resolve=t,e.reject=s})),e},t.basename=function(e,t="/"){const s=e.lastIndexOf(t);return-1===s?e:e.slice(s+1)},t.findParentWithClassName=function(e,t){var s;let n=e;for(;n;){if(null===(s=n.classList)||void 0===s?void 0:s.contains(t))return n;n=n.parentElement}},t.mapObject=function(e,t){return Object.fromEntries(Object.entries(e).map(t))},t.generatorContains=function(e,t){const s="function"==typeof t?t:e=>e===t;for(const t of e)if(s(t))return!0;return!1},t.zip=function*(e,t){const s=e[Symbol.iterator](),n=t[Symbol.iterator]();for(;;){const e=s.next(),t=n.next();if(e.done||t.done)break;yield[e.value,t.value]}},t.truncate=function(e,t=100){return e.length>t?e.substring(0,Math.max(0,t-1))+"…":e},t.isPromise=function(e){return"function"==typeof(null==e?void 0:e.then)}},20325:(e,t,s)=>{s.r(t),s.d(t,{startServer:()=>ne});var n=s(98696),i=s(57147),r=s.n(i),o=s(13685),a=s.n(o),c=s(71017),l=s.n(c),h=s(57310),u=s.n(h),d=s(95352),m=s.n(d),p=s(22037),g=s.n(p);function f(){try{return g().userInfo().username}catch(e){try{const{env:e}=process;return(0,n.unwrap)(e.LOGNAME||e.USER||e.LNAME||e.USERNAME)}catch(t){throw new Error(String(t)+String(e))}}}class v{logger;data;constructor(e,t){this.logger=e,this.data=t}setRepo(e){this.data.repo=e?.codeReviewProvider?.getSummaryName()}}const b=e=>{};var y=s(73837),w=s.n(y);const C=console;var S=s(60492),O=s.n(S),E=s(80909),R=s.n(E),k=s(82361);class _ extends k.EventEmitter{}class M{codeReviewSystem;runCommand;constructor(e,t){this.codeReviewSystem=e,this.runCommand=t}diffSummaries=new _;onChangeDiffSummaries(e){const t=t=>e({value:t}),s=t=>e({error:t});return this.diffSummaries.on("data",t),this.diffSummaries.on("error",s),{dispose:()=>{this.diffSummaries.off("data",t),this.diffSummaries.off("error",s)}}}async triggerDiffSummariesFetch(e){const t=await this.runCommand(["internal-only","prs"]),s=JSON.parse(t.stdout);this.diffSummaries.emit("data",s)}dispose(){this.diffSummaries.removeAllListeners()}getSummaryName(){return`github:${this.codeReviewSystem.hostname}/${this.codeReviewSystem.owner}/${this.codeReviewSystem.repo}`}runExternalCommand(e,t,s,n){throw new Error("GitHub code review provider does not support running external commands")}async typeahead(e,t){return Promise.resolve([])}}class D{logger;runCallback;constructor(e,t){this.logger=e,this.runCallback=t}queuedOperations=[];runningOperation=void 0;abortController=void 0;async runOrQueueOperation(e,t,s,i){if(null!=this.runningOperation)return this.queuedOperations.push({...e,tracker:s}),void t({id:e.id,kind:"queue",queue:this.queuedOperations.map((e=>e.id))});this.runningOperation=e;const r=(...s)=>{switch(s[0]){case"spawn":t({id:e.id,kind:"spawn",queue:this.queuedOperations.map((e=>e.id))});break;case"stdout":t({id:e.id,kind:"stdout",message:s[1]});break;case"stderr":t({id:e.id,kind:"stderr",message:s[1]});break;case"exit":t({id:e.id,kind:"exit",exitCode:s[1],timestamp:Date.now()})}};try{const o=(0,n.newAbortController)();if(this.abortController=o,await s.operation(e.trackEventName,"RunOperationError",{extras:{args:e.args,runner:e.runner}},(t=>this.runCallback(e,i,r,o.signal))),this.runningOperation=void 0,this.queuedOperations.length>0){const e=this.queuedOperations.shift();null!=e&&this.runOrQueueOperation(e,t,e.tracker,i)}}catch(s){const n=s.toString();this.logger.log("error running operation: ",e.args[0],n),t({id:e.id,kind:"error",error:n}),this.queuedOperations=[],this.runningOperation=void 0}}abortRunningOperation(e){this.runningOperation?.id==e&&this.abortController?.abort()}}class T{focusedPages=new Set;visiblePages=new Set;onChangeHandlers=new Set;setState(e,t){switch(t){case"focused":this.focusedPages.add(e),this.visiblePages.add(e);break;case"visible":this.focusedPages.delete(e),this.visiblePages.add(e);break;case"hidden":this.focusedPages.delete(e),this.visiblePages.delete(e)}for(const e of this.onChangeHandlers)e(t)}disposePage(e){this.focusedPages.delete(e),this.visiblePages.delete(e)}hasPageWithFocus(){return this.focusedPages.size>0}hasVisiblePage(){return this.visiblePages.size>0}onChange(e){return this.onChangeHandlers.add(e),()=>this.onChangeHandlers.delete(e)}}class P{maxSimultaneousRunning;log;queued=[];running=[];runs=new _;constructor(e,t){this.maxSimultaneousRunning=e,this.log=t}nextId=1;generateId(){return this.nextId++}async enqueueRun(e){const t=this.generateId();this.queued.push(t),this.tryDequeueNext(),this.running.includes(t)||(this.log?.(`${this.running.length} tasks are already running, enqueuing ID:${t}`),await new Promise((e=>{this.runs.on("run",(s=>{s===t&&(this.log?.(`now allowing ID:${t} to run`),e(void 0))}))})));try{return await e()}finally{this.notifyFinished(t)}}notifyFinished(e){this.running=this.running.filter((t=>t!==e)),this.tryDequeueNext()}tryDequeueNext(){if(this.running.length<this.maxSimultaneousRunning){const e=this.queued.shift();null!=e&&this.run(e)}}run(e){this.running.push(e),this.runs.emit("run",e)}}function N(e){return new Promise((t=>setTimeout(t,e)))}function j(e){let t,s;const n=()=>{const t=e();return s=t.then((()=>s=void 0),(()=>s=void 0)),t},i=()=>(t=void 0,n());return()=>null==s?n():(()=>{if(null==t){if(null==s)throw new Error("pendingCall must not be null!");t=s.then(i,i)}return t})()}var F=s(24678);class I{logger;client;serializedReconnect;reconnectDelayMs=100;subscriptions=new Map;lastKnownClockTimes=new Map;status="initializing";constructor(e){this.logger=e,this.client=new F.Client({watchmanBinaryPath:void 0}),this.initWatchmanClient(),this.serializedReconnect=j((async()=>{let e=0;for(;;)try{return void await this.reconnectClient()}catch(t){this.logger.warn(`reconnectClient failed (try #${e}):`,t instanceof Error?t.message:t),e++,this.reconnectDelayMs*=2,this.reconnectDelayMs>6e4&&(this.reconnectDelayMs=6e4),this.logger.info("Calling reconnectClient from _serializedReconnect in %dms",this.reconnectDelayMs),await N(this.reconnectDelayMs)}}))}setStatus(e){this.logger.log("Watchman status: ",e),this.status=e}async watchDirectoryRecursive(e,t,s){const n=this.fixupName(e,t),i=this.getSubscription(n);if(i)return i.subscriptionCount++,i;{const{watch:t,relative_path:i}=await this.watchProject(e),r=await this.clock(t),o={...s,fields:null!=s&&null!=s.fields?s.fields:["name","new","exists"],since:r};i&&(o.relative_root=i),o.empty_on_fresh_instance=!0;const a={root:t,pathFromSubscriptionRootToSubscriptionPath:i,path:e,name:n,subscriptionCount:1,options:o,emitter:new k.EventEmitter};return this.setSubscription(n,a),await this.subscribe(t,n,o),this.logger.log("watchman subscription %s established",n),this.setStatus("healthy"),a}}async unwatch(e,t){const s=this.fixupName(e,t),n=this.getSubscription(s);null!=n?0==--n.subscriptionCount&&(await this.unsubscribe(n.path,n.name),this.deleteSubscription(s),this.logger.log("watchman subscription %s destroyed",s)):this.logger.error(`No watcher entity found with path [${e}] name [${t}]`)}initWatchmanClient(){this.client.on("end",(()=>{this.setStatus("ended"),this.logger.info("Watchman client ended"),this.client.removeAllListeners(),this.serializedReconnect()})),this.client.on("error",(e=>{const t=this.status;this.logger.error("Error while talking to watchman: ",e),this.setStatus("errored"),this.client.removeAllListeners(),this.client.end(),"initializing"!==t&&this.serializedReconnect()})),this.client.on("subscription",this.onSubscriptionResult.bind(this))}async reconnectClient(){this.logger.info("Ending existing watchman client to reconnect a new one"),this.setStatus("reconnecting"),this.client.removeAllListeners(),this.client.end(),this.client=new F.Client({watchmanBinaryPath:void 0}),this.logger.error("Watchman client disconnected, reconnecting a new client!"),this.initWatchmanClient(),this.logger.info("Watchman client re-initialized, restoring subscriptions"),await this.restoreSubscriptions()}async restoreSubscriptions(){const e=Array.from(this.subscriptions.values()),t=e.length;this.logger.info(`Attempting to restore ${t} Watchman subscriptions.`);let s=0;await Promise.all(e.map((async(e,n)=>{await this.watchProject(e.path),await N(2500);const{name:i,options:r,root:o}=e;e.options.since=this.lastKnownClockTimes.get(o)||await this.clock(o),this.logger.info(`Subscribing to ${i}: (${n+1}/${t})`),await this.subscribe(o,i,r),++s,this.logger.info(`Subscribed to ${i}: (${s}/${t}) complete.`)}))),s>0&&s===t&&(this.logger.info("Successfully reconnected all %d subscriptions.",s),this.reconnectDelayMs=100,this.setStatus("healthy"))}getSubscription(e){return this.subscriptions.get(l().normalize(e))}setSubscription(e,t){const s=l().normalize(e);this.subscriptions.set(s,t)}deleteSubscription(e){const t=l().normalize(e);this.subscriptions.delete(t)}onSubscriptionResult(e){const t=this.getSubscription(e.subscription);if(null!=t){if(null!=e&&null!=e.root&&null!=e.clock&&this.lastKnownClockTimes.set(e.root,e.clock),!0===e.is_fresh_instance)this.logger.warn(`Watch for ${e.root} (${e.subscription}) returned an empty fresh instance.`),t.emitter.emit("fresh-instance");else if(Array.isArray(e.files))t.emitter.emit("change",e.files);else if(!0===e.canceled)this.logger.info(`Watch for ${e.root} was deleted: triggering a reconnect.`),this.client.end();else if(this.subscriptions.values().next().value===t){const t=e["state-enter"],s=e["state-leave"],n=null!=t?`Entering ${t}`:`Leaving ${s}`,i=this.subscriptions.size;this.logger.info(`Subscription state: ${n} (${i})`)}}else this.logger.error("Subscription not found for response:!",e)}fixupName(e,t){return`${e.replace(/\\/g,"-").replace(/\//g,"-")}-${t}`}unsubscribe(e,t){return this.command("unsubscribe",e,t)}async watchProject(e){const t=await this.command("watch-project",e);return t.warning&&this.logger.error("watchman warning: ",t.warning),t}async clock(e){const{clock:t}=await this.command("clock",e);return t}subscribe(e,t,s){return this.logger.info(`Creating Watchman subscription ${String(t)} under ${e}`,JSON.stringify(s)),this.command("subscribe",e,t,s)}async command(...e){try{return await new Promise(((t,s)=>{this.client.command(e,((e,n)=>e?s(e):t(n)))}))}catch(t){throw this.logger.error("Watchman command error: ",e,t),t}}}const x=5*n.ONE_MINUTE_MS,A=1*n.ONE_MINUTE_MS,L=.25*n.ONE_MINUTE_MS;class ${repoInfo;logger;pageFocusTracker;changeCallback;static WATCHMAN_DEFER="hg.update";watchman;disposables=[];constructor(e,t,s,n,i){this.repoInfo=e,this.logger=t,this.pageFocusTracker=s,this.changeCallback=n,this.watchman=i??new I(t),this.setupWatchmanSubscriptions(),this.setupPolling(),this.pageFocusTracker.onChange(this.poll.bind(this))}timeout;lastFetch=(new Date).valueOf();setupPolling(){this.timeout=setTimeout(this.poll,x)}poll=e=>{let t=x;"healthy"!==this.watchman.status&&(this.pageFocusTracker.hasPageWithFocus()?t=L:this.pageFocusTracker.hasVisiblePage()&&(t=A));const s=Date.now()-this.lastFetch;"force"===e||s>=t||"focused"===e&&s>=1e4||"visible"===e&&s>=2e4?(this.changeCallback("everything"),this.lastFetch=Date.now(),clearTimeout(this.timeout),this.timeout=setTimeout(this.poll,t)):(clearTimeout(this.timeout),this.timeout=setTimeout(this.poll,t-s))};async setupWatchmanSubscriptions(){if("success"!==this.repoInfo.type)return;const{repoRoot:e,dotdir:t}=this.repoInfo;if(null==e||null==t)return void this.logger.error(`skipping watchman subscription since ${e} is not a repository`);const s=l().relative(e,t),i="graphite-smartlog-file-change",r="graphite-smartlog-dirstate-change";try{const t=(0,n.debounce)((()=>{this.changeCallback("everything"),this.lastFetch=(new Date).valueOf()}),100),o=await this.watchman.watchDirectoryRecursive(e,r,{fields:["name"],expression:["name",[`${s}/bookmarks.current`,`${s}/bookmarks`,`${s}/dirstate`,`${s}/merge`],"wholename"],defer:[$.WATCHMAN_DEFER],empty_on_fresh_instance:!0});o.emitter.on("change",(e=>{e.includes(`${s}/merge`)&&this.changeCallback("merge conflicts"),e.includes(`${s}/dirstate`)&&t()})),o.emitter.on("fresh-instance",t);const a=()=>{this.changeCallback("uncommitted changes"),this.lastFetch=(new Date).valueOf()},c=await this.watchman.watchDirectoryRecursive(e,i,{fields:["name"],expression:["allof",["type","f"],["not",["dirname",s]],["not",["match",s,"basename"]]],defer:[$.WATCHMAN_DEFER],empty_on_fresh_instance:!0});c.emitter.on("change",a),c.emitter.on("fresh-instance",a),this.disposables.push((()=>{this.logger.log("unsubscribe watchman"),this.watchman.unwatch(e,r),this.watchman.unwatch(e,i)}))}catch(e){this.logger.error("failed to setup watchman subscriptions",e)}}dispose(){this.disposables.forEach((e=>e())),this.timeout&&(clearTimeout(this.timeout),this.timeout=void 0)}}const U="0.22.5";class q{info;logger;IGNORE_COMMIT_MESSAGE_LINES_REGEX=/^((?:HG|SL):.*)/gm;mergeConflicts=void 0;uncommittedChanges=null;smartlogCommits=null;mergeConflictsEmitter=new _;uncommittedChangesEmitter=new _;smartlogCommitsChangesEmitter=new _;smartlogCommitsBeginFetchingEmitter=new _;uncommittedChangesBeginFetchingEmitter=new _;disposables=[()=>this.mergeConflictsEmitter.removeAllListeners(),()=>this.uncommittedChangesEmitter.removeAllListeners(),()=>this.smartlogCommitsChangesEmitter.removeAllListeners(),()=>this.smartlogCommitsBeginFetchingEmitter.removeAllListeners(),()=>this.uncommittedChangesBeginFetchingEmitter.removeAllListeners()];onDidDispose(e){this.disposables.push(e)}operationQueue;watchForChanges;pageFocusTracker=new T;codeReviewProvider;currentVisibleCommitRangeIndex=0;visibleCommitRanges=[n.DEFAULT_DAYS_OF_COMMITS_TO_LOAD,60,void 0];constructor(e,t){this.info=e,this.logger=t;const s=e.codeReviewSystem;"github"===s.type&&(this.codeReviewProvider=new M(s,this.runCommand.bind(this))),this.watchForChanges=new $(e,t,this.pageFocusTracker,(e=>{"uncommitted changes"===e?this.fetchUncommittedChanges():"commits"===e?this.fetchSmartlogCommits():"merge conflicts"===e?this.checkForMergeConflicts():"everything"===e&&(this.fetchUncommittedChanges(),this.fetchSmartlogCommits(),this.checkForMergeConflicts(),this.codeReviewProvider?.triggerDiffSummariesFetch(this.getAllDiffIds()))})),this.operationQueue=new D(this.logger,((e,t,s,i)=>{if(e.runner===n.CommandRunner.Graphite)return this.runOperation(e,s,t,i);if(e.runner===n.CommandRunner.CodeReviewProvider){const n=this.normalizeOperationArgs(t,e.args);return null==this.codeReviewProvider?.runExternalCommand?Promise.reject(Error("CodeReviewProvider does not support running external commands")):this.codeReviewProvider?.runExternalCommand(t,n,s,i)??Promise.resolve()}return Promise.resolve()}));const i=new Set,r=this.subscribeToSmartlogCommitsChanges((e=>{if(e.commits.value){const t=[],s=e.commits.value.filter((e=>e.pr)).map((e=>e.pr?.number));for(const e of s)i.has(e)||(t.push(e),i.add(e));t.length>0&&this.codeReviewProvider?.triggerDiffSummariesFetch(this.getAllDiffIds())}}));this.checkForMergeConflicts(),this.disposables.push((()=>r.dispose()))}nextVisibleCommitRangeInDays(){return this.currentVisibleCommitRangeIndex+1<this.visibleCommitRanges.length&&this.currentVisibleCommitRangeIndex++,this.visibleCommitRanges[this.currentVisibleCommitRangeIndex]}dispose(){this.disposables.forEach((e=>e())),this.codeReviewProvider?.dispose(),this.watchForChanges.dispose()}onChangeConflictState(e){return this.mergeConflictsEmitter.on("change",e),this.mergeConflicts&&e(this.mergeConflicts),{dispose:()=>this.mergeConflictsEmitter.off("change",e)}}checkForMergeConflicts=j((async()=>{this.logger.info("checking for merge conflicts");const e=null!=this.mergeConflicts;if(!e&&!await(t=l().join(this.info.dotdir,"rebase-merge"),r().promises.stat(t).then((()=>!0)).catch((e=>{if("ENOENT"===e.code)return!1;throw e}))))return void this.logger.info(`conflict state still the same (${e?"IN merge conflict":"NOT in conflict"})`);var t;null==this.mergeConflicts&&(this.mergeConflicts={state:"loading"},this.mergeConflictsEmitter.emit("change",this.mergeConflicts));const s=Date.now();let n;try{const e=await this.runCommand(["internal-only","status"]);n=JSON.parse(e.stdout)}catch(e){return this.logger.error(`failed to check for merge conflicts: ${e}`),this.mergeConflicts=void 0,void this.mergeConflictsEmitter.emit("change",this.mergeConflicts)}if(this.mergeConflicts=function(e,t,s){const n=t;if(!n?.conflicts)return;const i=n.files.filter((e=>"UNRESOLVED"===e.status)),r={state:"loaded",files:[],fetchStartTimestamp:s,fetchCompletedTimestamp:Date.now()};if(null!=e?.files&&e.files.length>0){const t=new Set(i.map((e=>e.path)));r.files=e.files.map((e=>t.has(e.path)?{path:e.path,status:"UNRESOLVED"}:{path:e.path,status:"RESOLVED"}))}else r.files=i.map((e=>({path:e.path,status:"UNRESOLVED"})));return r}(this.mergeConflicts,n,s),this.logger.info(`repo ${this.mergeConflicts?"IS":"IS NOT"} in merge conflicts`),this.mergeConflicts){const e=20,t=(this.mergeConflicts.files??[]).filter((e=>"UNRESOLVED"===e.status)).map((e=>e.path)).slice(0,e);this.logger.info("remaining files with conflicts: ",t)}this.mergeConflictsEmitter.emit("change",this.mergeConflicts)}));getMergeConflicts(){return this.mergeConflicts}static async getRepoInfo(e,t,s){const n=await async function(e,t,s){try{return(await H({command:e,args:["--version"],logger:t,cwd:s})).stdout}catch(e){throw t.error(`Failed to find gt version in ${s}`,e),e}}(e,t,s).catch((e=>e));if(n instanceof Error)return{type:"invalidCommand",command:e??"gt"};if("local"!==n&&R().lt(n,U))return{type:"invalidVersion",command:e??"gt",versionFound:n,versionRequired:U};const[i,r,o]=await Promise.all([W(e,t,s),z(e,t,s),B(e,t,s,"graphite.branch_edit").then((e=>e??"amend"))]);if(null==r)return{type:"cwdNotARepository",cwd:s};let a;if(void 0===r.remote)a={type:"none"};else{const{owner:e,name:t,hostname:s}=r.remote;a={type:"github",owner:e,repo:t,hostname:s}}const c={type:"success",command:e,dotdir:r.dotDir,repoRoot:r.rootDir,codeReviewSystem:a,preferredBranchEdit:o,profile:i,trunkBranch:r.trunkBranch};return t.info("repo info: ",c),c}async runOrQueueOperation(e,t,s,n){await this.operationQueue.runOrQueueOperation(e,t,s,n),this.watchForChanges.poll("force")}abortRunningOpeation(e){this.operationQueue.abortRunningOperation(e)}normalizeOperationArgs(e,t){const s=(0,n.unwrap)(this.info.repoRoot);return t.map((t=>{if("object"==typeof t)switch(t.type){case"repo-relative-file":return l().normalize(l().relative(e,l().join(s,t.path)));case"succeedable-revset":return`max(successors(${t.revset}))`}return t}))}async runOperation(e,t,s,n){const i=this.normalizeOperationArgs(s,e.args),{stdin:r}=e,{command:o,args:a,options:c}=V(this.info.command,i,s,r?{input:r}:void 0);this.logger.log("run operation: ",o,i.join(" "));const l=O()(o,a,{...c,stdout:"pipe",stderr:"pipe"});t("spawn"),l.stdout?.on("data",(e=>{t("stdout",e.toString())})),l.stderr?.on("data",(e=>{t("stderr",e.toString())})),l.on("exit",(e=>{t("exit",e||0)})),n.addEventListener("abort",(()=>{this.logger.log("kill operation: ",o,i.join(" "))})),function(e,t){t.addEventListener("abort",(()=>{"win32"==g().platform()?e.kill("SIGKILL",{forceKillAfterTimeout:!1}):(e.kill("SIGCONT"),e.kill("SIGTERM",{forceKillAfterTimeout:5e3}))}))}(l,n),await l}setPageFocus(e,t){this.pageFocusTracker.setState(e,t)}getUncommittedChanges(){return this.uncommittedChanges}subscribeToUncommittedChanges(e){return this.uncommittedChangesEmitter.on("change",e),{dispose:()=>{this.uncommittedChangesEmitter.off("change",e)}}}fetchUncommittedChanges=j((async()=>{const e=Date.now();try{this.uncommittedChangesBeginFetchingEmitter.emit("start");const t=await this.runCommand(["internal-only","status"]),s=JSON.parse(t.stdout).files.map((e=>{return{...e,path:(t=e.path,t.startsWith(l().sep)?t.slice(1):t)};var t}));this.uncommittedChanges={fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),files:{value:s}},this.uncommittedChangesEmitter.emit("change",this.uncommittedChanges)}catch(s){if(this.logger.error("Error fetching files: ",s),null!=(t=s)&&"object"==typeof t&&"stderr"in t&&s.stderr.includes("checkout is currently in progress"))return void this.logger.info("Ignoring `hg status` error caused by in-progress checkout");this.uncommittedChangesEmitter.emit("change",{fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),files:{error:s instanceof Error?s:new Error(s)}})}var t}));getSmartlogCommits(){return this.smartlogCommits}subscribeToSmartlogCommitsChanges(e){return this.smartlogCommitsChangesEmitter.on("change",e),{dispose:()=>{this.smartlogCommitsChangesEmitter.off("change",e)}}}subscribeToSmartlogCommitsBeginFetching(e){const t=()=>e(!0);return this.smartlogCommitsBeginFetchingEmitter.on("start",t),{dispose:()=>{this.smartlogCommitsBeginFetchingEmitter.off("start",t)}}}subscribeToUncommittedChangesBeginFetching(e){const t=()=>e(!0);return this.uncommittedChangesBeginFetchingEmitter.on("start",t),{dispose:()=>{this.uncommittedChangesBeginFetchingEmitter.off("start",t)}}}fetchSmartlogCommits=j((async()=>{const e=Date.now();try{this.smartlogCommitsBeginFetchingEmitter.emit("start");const t=await this.runCommand(["internal-only","log"]),s=function(e,t){let s=[];try{s=JSON.parse(t)}catch(t){e.error("failed to parse branch info",t)}return s}(this.logger,t.stdout.trim());if(0===s.length)throw new Error(n.ErrorShortMessages.NoCommitsFetched);this.smartlogCommits={fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),commits:{value:s}},this.smartlogCommitsChangesEmitter.emit("change",this.smartlogCommits)}catch(t){this.logger.error("Error fetching commits: ",t),this.smartlogCommitsChangesEmitter.emit("change",{fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),commits:{error:t instanceof Error?t:new Error(t)}})}}));subscribeToHeadCommit(e){let t=this.smartlogCommits?.commits.value?.find((e=>e.isHead));null!=t&&e(t);const s=s=>{const n=s?.commits.value?.find((e=>e.isHead));null!=n&&n.branch!==t?.branch&&(e(n),t=n)};return this.smartlogCommitsChangesEmitter.on("change",s),{dispose:()=>{this.smartlogCommitsChangesEmitter.off("change",s)}}}catLimiter=new P(4,(e=>this.logger.info("[cat]",e)));cat(e,t){const s=l().relative(this.info.repoRoot,e);return this.catLimiter.enqueueRun((async()=>(await this.runCommand(["internal-only","relative-cat",...this.catArgs(t,s)],void 0,{stripFinalNewline:!1})).stdout))}catArgs(e,t){switch(e.type){case n.ComparisonType.UncommittedChanges:return["uncommitted",t];case n.ComparisonType.HeadChanges:return["head",t];case n.ComparisonType.StackChanges:return["stack",t];case n.ComparisonType.Committed:return["stack",t,"--ref",e.hash]}}getAllDiffIds(){return this.getSmartlogCommits()?.commits.value?.map((e=>e.pr?.number)).filter(n.notEmpty)??[]}runCommand(e,t,s){return H({command:this.info.command,args:e,logger:this.logger,cwd:(0,n.unwrap)(t??this.info.repoRoot),options:s})}getConfig(e){return B(this.info.command,this.logger,this.info.repoRoot,e)}setConfig(e,t,s){return async function({command:e,logger:t,cwd:s,level:n,configName:i,configValue:r}){await H({command:e,args:["internal-only","set-config","--level",n,i,r],logger:t,cwd:s})}({command:this.info.command,logger:this.logger,cwd:this.info.repoRoot,level:e,configName:t,configValue:s})}}function H({command:e,args:t,logger:s,cwd:n,options:i}){const{command:r,args:o,options:a}=V(e,t,n,i);return s&&s.log("run command: ",r,...o,a),O()(r,o,a)}async function z(e,t,s){try{return JSON.parse((await H({command:e,args:["internal-only","repo-info"],logger:t,cwd:s})).stdout)}catch(e){return void t.error(`Failed to find repository info in ${s}`,e)}}async function W(e,t,s){try{return JSON.parse((await H({command:e,args:["internal-only","profile"],logger:t,cwd:s})).stdout)}catch(e){return t.error(`Failed to find repository profile in ${s}`,e),{appUrl:"https://app.graphite.dev/"}}}async function B(e,t,s,n){try{return(await H({command:e,args:["internal-only","config",n],logger:t,cwd:s})).stdout.trim()}catch{return}}function V(e,t,s,n){let i=[...t];"win32"!==process.platform&&(i=i.map((e=>e.replace(/\\\\/g,"\\"))));const r={...n,env:{LANG:"en_US.utf-8",EDITOR:void 0,GRAPHITE_INTERACTIVE:"true"},cwd:s};return!e&&process.argv[1].startsWith("/snapshot/")?(e=process.argv[0],i=["/snapshot/monologue/apps/public/cli/dist/graphite.js",...i]):e||(e="gt"),{command:e,args:i,options:r}}var G=s(32081);const J={platformName:"browser",handleMessageFromClient:(e,t)=>{switch(t.type){case"platform/openFile":{const s=l().join((0,n.unwrap)(e?.info.repoRoot),t.path);let i;if(null==i)switch(process.platform){case"darwin":i="/usr/bin/open";break;case"win32":i="notepad.exe";break;case"linux":i="xdg-open"}if(i){e?.logger.log("open file",s);const t=(0,G.spawn)(i,[s],{detached:!0,stdio:"ignore",windowsHide:!1,windowsVerbatimArguments:!0});t.on("error",(t=>{e?.logger.log("failed to open",s,t)})),t.unref()}break}}}};class Q{promise;disposeFunc;constructor(e,t){this.promise=e,this.disposeFunc=t}unref(){this.disposed||(this.disposed=!0,this.disposeFunc())}internalReference;disposed=!1}class K{value;constructor(e){this.value=e}references=0;isDisposed=!1;ref(){this.references++}getNumberOfReferences(){return this.references}dispose(){this.references--,this.isDisposed||0!==this.references||(this.isDisposed=!0,this.value.dispose())}}const X=new class{RepositoryType;constructor(e=q){this.RepositoryType=e}reposByRoot=new Map;activeReposEmitter=new _;lookup(e){for(const s of this.reposByRoot.values())if((e===s.value.info.repoRoot||e.startsWith((t=s.value.info.repoRoot).endsWith(l().sep)?t:t+l().sep))&&!s.isDisposed)return s;var t}getOrCreate(e,t,s){const n=this.lookup(s);if(n)return n.ref(),new Q(Promise.resolve(n.value),(()=>n.dispose()));let i;return i=new Q((async()=>{const n=await this.RepositoryType.getRepoInfo(e,t,s);if("success"!==n.type)return n;if(i.disposed)return{type:"unknownError",error:new Error("Repository already disposed")};const r=this.lookup(n.repoRoot);if(r)return r.ref(),i.internalReference=r,r.value;const o=new this.RepositoryType(n,t),a=new K(o);return a.ref(),i.internalReference=a,this.reposByRoot.set(n.repoRoot,a),this.activeReposEmitter.emit("change"),o})(),(()=>{i.internalReference&&i.internalReference.dispose(),i.unref()})),i}cachedRepositoryForPath(e){const t=this.lookup(e);return t?.value}onChangeActiveRepos(e){const t=()=>{e([...this.reposByRoot.values()].map((e=>e.value)))};return this.activeReposEmitter.on("change",t),t(),()=>this.activeReposEmitter.off("change",t)}clearCache(){this.reposByRoot.forEach((e=>e.dispose())),this.reposByRoot=new Map,this.activeReposEmitter.removeAllListeners()}numberOfActiveServers(){let e=0;for(const t of this.reposByRoot.values())e+=t.getNumberOfReferences();return e}};class Y{platform;connection;tracker;logger;listenersByType=new Map;incomingListener;repoDisposables=[];subscriptions=new Map;activeRepoRef;queuedMessages=[];currentState={type:"loading"};pageId=(0,n.randomId)();constructor(e,t,s,i){this.platform=e,this.connection=t,this.tracker=s,this.logger=i;let r=null;this.incomingListener=this.connection.onDidReceiveMessage(((e,s)=>{if(s)return null==r?void t.logger?.error("Error: got a binary message when not expecting one"):(this.handleIncomingMessageWithPayload(r,e),void(r=null));if(null!=r)return t.logger?.error("Error: didnt get binary payload after a message that requires one"),void(r=null);const i=e.toString("utf-8"),o=(0,n.deserializeFromString)(i);if(function(e){return null!=e&&"object"==typeof e&&!0===e.hasBinaryPayload}(o))r=o;else if("loading"===this.currentState.type)this.queuedMessages.push(o);else try{this.handleIncomingMessage(o)}catch(e){t.logger?.error("error handling incoming message: ",o,e)}}))}setRepoError(e){this.disposeRepoDisposables(),this.currentState={type:"error",error:e},this.tracker.context.setRepo(void 0),this.processQueuedMessages()}setCurrentRepo(e,t){this.disposeRepoDisposables(),this.currentState={type:"repo",repo:e,cwd:t},this.tracker.context.setRepo(e),null!=e.codeReviewProvider&&this.repoDisposables.push(e.codeReviewProvider.onChangeDiffSummaries((e=>{this.postMessage({type:"fetchedDiffSummaries",summaries:e})}))),this.repoDisposables.push(e.subscribeToHeadCommit((t=>{const s=e.getSmartlogCommits(),n=function(e,t){let s;if(null!=e){const n=new Map(e.map((e=>[e.branch,e])));let i=t;for(;null!=i;){if(i.partOfTrunk){s=i;break}if(null==i.parents[0])break;i=n.get(i.parents[0])}}return s}(s?.commits.value,t);this.tracker.track("HeadCommitChanged",{extras:{hash:t.branch,public:n?.branch}})}))),this.processQueuedMessages()}postMessage(e){this.connection.postMessage((0,n.serializeToString)(e)).catch((()=>{console.warn("Failed to post message to client")}))}setActiveRepoForCwd(e){void 0!==this.activeRepoRef&&this.activeRepoRef.unref(),this.logger.info(`Setting active repo cwd to ${e}`),this.currentState={type:"loading"};const t=this.connection.command;this.activeRepoRef=X.getOrCreate(t,this.logger,e),this.activeRepoRef.promise.then((t=>{t instanceof q?this.setCurrentRepo(t,e):this.setRepoError(t)}))}dispose(){this.incomingListener.dispose(),this.disposeRepoDisposables(),void 0!==this.activeRepoRef&&this.activeRepoRef.unref()}disposeRepoDisposables(){this.repoDisposables.forEach((e=>e.dispose())),this.repoDisposables=[],this.subscriptions.forEach((e=>e.dispose())),this.subscriptions.clear()}processQueuedMessages(){for(const e of this.queuedMessages)try{this.handleIncomingMessage(e)}catch(t){this.connection.logger?.error("error handling queued message: ",e,t)}this.queuedMessages=[]}handleIncomingMessageWithPayload(e,t){switch(e.type){case"uploadFile":{const{id:s,filename:i}=e,r=null;if(null==r)return;this.tracker.operation("UploadImage","UploadImageError",{},(()=>r((0,n.unwrap)(this.connection.logger),{filename:i,data:t}))).then((e=>{this.connection.logger?.info("sucessfully uploaded file",i,e),this.postMessage({type:"uploadFileResult",id:s,result:{value:e}})})).catch((e=>{this.connection.logger?.info("error uploading file",i,e),this.postMessage({type:"uploadFileResult",id:s,result:{error:e}})}));break}}}handleIncomingMessage(e){this.handleIncomingGeneralMessage(e);const{currentState:t}=this;switch(t.type){case"repo":{const{repo:s,cwd:n}=t;this.handleIncomingMessageWithRepo(e,s,n);break}case"loading":case"error":e.type.startsWith("platform/")&&(this.platform.handleMessageFromClient(void 0,e,(e=>this.postMessage(e)),(e=>{this.repoDisposables.push({dispose:e})})),this.notifyListeners(e))}}handleIncomingGeneralMessage(e){switch(e.type){case"track":this.tracker.trackData(e.data);break;case"changeCwd":this.setActiveRepoForCwd(e.cwd);break;case"requestRepoInfo":switch(this.currentState.type){case"repo":this.postMessage({type:"repoInfo",info:this.currentState.repo.info,cwd:this.currentState.cwd});break;case"error":this.postMessage({type:"repoInfo",info:this.currentState.error})}break;case"requestApplicationInfo":this.postMessage({type:"applicationInfo",platformName:this.platform.platformName,version:this.connection.version})}}handleIncomingMessageWithRepo(e,t,s){const{logger:i}=t;switch(e.type){case"subscribe":{const{subscriptionID:s,kind:n}=e;switch(n){case"uncommittedChanges":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"uncommittedChanges",subscriptionID:s,data:e})},n=t.getUncommittedChanges();null!=n&&e(n);const i=[];i.push(t.subscribeToUncommittedChanges(e)),t.fetchUncommittedChanges(),i.push(t.subscribeToUncommittedChangesBeginFetching((()=>this.postMessage({type:"beganFetchingUncommittedChangesEvent"})))),this.subscriptions.set(s,{dispose:()=>{i.forEach((e=>e.dispose()))}});break}case"smartlogCommits":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"smartlogCommits",subscriptionID:s,data:e})},n=t.getSmartlogCommits();null!=n&&e(n);const i=[];i.push(t.subscribeToSmartlogCommitsChanges(e)),t.fetchSmartlogCommits(),i.push(t.subscribeToSmartlogCommitsBeginFetching((()=>this.postMessage({type:"beganFetchingSmartlogCommitsEvent"})))),this.subscriptions.set(s,{dispose:()=>{i.forEach((e=>e.dispose()))}});break}case"mergeConflicts":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"mergeConflicts",subscriptionID:s,data:e})},n=t.getMergeConflicts();null!=n&&e(n),this.subscriptions.set(s,t.onChangeConflictState(e));break}}break}case"unsubscribe":{const t=this.subscriptions.get(e.subscriptionID);t?.dispose(),this.subscriptions.delete(e.subscriptionID);break}case"runOperation":{const{operation:n}=e;t.runOrQueueOperation(n,(e=>{this.postMessage({type:"operationProgress",...e}),"queue"===e.kind&&this.tracker.track("QueueOperation",{extras:{operation:n.trackEventName}})}),this.tracker,s);break}case"abortRunningOperation":{const{operationId:s}=e;t.abortRunningOpeation(s);break}case"getConfig":t.getConfig(e.name).catch((()=>{})).then((t=>{i.info("got config",e.name,t),this.postMessage({type:"gotConfig",name:e.name,value:t})}));break;case"fetchRepoMessage":t.runCommand(["internal-only","repo-message"]).then((e=>({value:e.stdout}))).catch((e=>(i?.error("error fetching repo message",e.toString()),{error:e}))).then((e=>this.postMessage({type:"fetchedRepoMessage",message:e.value||""})));break;case"fetchUpgradePrompt":t.runCommand(["internal-only","upgrade-prompt"]).then((e=>({value:e.stdout}))).catch((e=>(i?.error("error fetching upgrade prompt",e.toString()),{error:e}))).then((e=>this.postMessage({type:"fetchedUpgradePrompt",message:e.value||""})));break;case"setConfig":i.info("set config",e.name,e.value),t.setConfig("user",e.name,e.value).catch((t=>{i.error("error setting config",e.name,e.value,t)}));break;case"deleteFile":{const{filePath:s}=e,n=function(e,t,s=l()){const n=s.resolve(t.info.repoRoot,e);return n.startsWith(t.info.repoRoot+s.sep)?n:null}(s,t);if(null==n)return void i.warn("can't delete file outside of the repo",s);r().promises.rm(n).then((()=>{i.info("deleted file from filesystem",n)})).catch((e=>{i.error("unable to delete file",n,e)}));break}case"requestComparison":{const{comparison:s}=e;t.runCommand(["internal-only","diff",...(0,n.revsetArgsForComparison)(s)]).then((e=>({value:e.stdout}))).catch((e=>(i?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"comparison",comparison:s,data:{diff:e}})));break}case"requestChangedFiles":{const{branch:s}=e;t.runCommand(["internal-only","changed-files",s]).then((e=>JSON.parse(e.stdout))).catch((e=>(i?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"changedFiles",branch:s,data:e})));break}case"requestComparisonContextLines":{const{id:{path:s,comparison:n},start:i,numLines:r}=e;t.cat(s,n).catch((()=>"")).then((e=>this.postMessage({type:"comparisonContextLines",lines:e.split("\n").slice(i-1,i-1+r),path:s})));break}case"refresh":i?.log("refresh requested"),t.fetchSmartlogCommits(),t.fetchUncommittedChanges(),t.codeReviewProvider?.triggerDiffSummariesFetch(t.getAllDiffIds());break;case"pageVisibility":t.setPageFocus(this.pageId,e.state);break;case"fetchCommitMessageTemplate":t.runCommand(["internal-only","templates"]).then((e=>{const s=JSON.parse(e.stdout);this.postMessage({type:"fetchedCommitMessageTemplate",templates:Object.fromEntries(Object.entries(s).map((([e,s])=>[e,s.replace(t.IGNORE_COMMIT_MESSAGE_LINES_REGEX,"")])))})})).catch((e=>{i?.error("Could not fetch commit message template",e)}));break;case"typeahead":t.codeReviewProvider?.typeahead?.(e.kind,e.query)?.then((t=>this.postMessage({type:"typeaheadResult",id:e.id,result:t})));break;case"fetchDiffSummaries":t.codeReviewProvider?.triggerDiffSummariesFetch(t.getAllDiffIds());break;case"loadMoreCommits":{const e=t.nextVisibleCommitRangeInDays();return this.postMessage({type:"commitsShownRange",rangeInDays:e}),this.postMessage({type:"beganLoadingMoreCommits"}),t.fetchSmartlogCommits(),void this.tracker.track("LoadMoreCommits",{extras:{daysToFetch:e??"Infinity"}})}default:this.platform.handleMessageFromClient(t,e,(e=>this.postMessage(e)),(e=>{this.repoDisposables.push({dispose:e})}))}this.notifyListeners(e)}notifyListeners(e){const t=this.listenersByType.get(e.type);t&&t.forEach((t=>t(e)))}}var Z=s(6113);const ee="win32"==process.platform?l().join((0,n.unwrap)(process.env.LOCALAPPDATA),"cache"):"darwin"==process.platform?l().join(g().homedir(),"Library/Caches"):process.env.XDG_CACHE_HOME||l().join(g().homedir(),".cache");function te(e,t){const s=Buffer.from(e),n=Buffer.from(t);return s.length===n.length&&(0,Z.timingSafeEqual)(s,n)}function se(e){const t=e.logger??(e.logFileLocation?function(e){const t=(...t)=>{const s=w().format(...t)+"\n";r().promises.appendFile(e,s)};return{info:t,log:t,warn:t,error:t,getLogFileContents:()=>r().promises.readFile(e,"utf-8")}}(e.logFileLocation):C);e.logger=t;const s=e?.platform??J,i=e?.version??"unknown";t.log(`establish client connection for ${e.cwd}`),t.log(`platform '${s.platformName}', version '${i}'`);const o=function(e,t,s,i=b){return new n.Tracker(((e,t)=>{const{logger:s}=t;s.log("[track]",e.eventName,e.errorName??"",null!=e.extras?JSON.stringify(e.extras):"");try{Promise.resolve(i({...e,...t.data})).catch((e=>{}))}catch{}}),new v(e,function(e,t){return{platform:e,version:t,repo:void 0,sessionId:(0,n.randomId)(),unixname:f(),osArch:g().arch(),osType:g().platform(),osRelease:g().release(),hostname:g().hostname()}}(t.platformName,s)))}(t,s,i,(t=>H({command:e.command||"gt",args:["internal-only","log-action",t.eventName||t.errorName||"UNKNOWN_CLI_EVENT",(t.timestamp?new Date(t.timestamp):new Date).toISOString(),JSON.stringify(t)],cwd:e.cwd})));o.track("ClientConnection",{extras:{cwd:e.cwd}});let a=new Y(s,e,o,t);return a.setActiveRepoForCwd(e.cwd),()=>{a?.dispose(),a=null}}function ne({port:e,sensitiveToken:t,challengeToken:s,logFileLocation:i,logInfo:o,command:c,gtVersion:h,foreground:d,frontendDir:p}){return new Promise((g=>{try{const e=JSON.parse(r().readFileSync(l().join(p,"build/asset-manifest.json"),"utf-8"));for(const t of Object.values(e.files))t.startsWith("/")||g({type:"error",error:`expected entry to start with / but was: \`${t}\``}),oe[t]=t.slice(1)}catch(e){}oe["/favicon.ico"]="favicon.ico";const f=a().createServer((async(e,n)=>{if(e.url){const{pathname:o}=u().parse(e.url);if(null!=o&&oe.hasOwnProperty(o)){const e=oe[o];let t;try{t=await r().promises.readFile(l().join(p,"build",e))}catch(e){return n.writeHead(500,{"Content-Type":"text/plain"}),void n.end((i=e.toString(),i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#27;")))}const s=e.lastIndexOf("."),a=e.slice(s+1),c=re[a]??"text/plain";return n.writeHead(200,{"Content-Type":c}),void n.end(t)}if("/challenge_authenticity"===o){const i=ie(e.url).get("token");if(i&&te(i,t)){n.writeHead(200,{"Content-Type":"text/json"});const e={challengeToken:s,pid:process.pid};n.end(JSON.stringify(e))}else n.writeHead(401,{"Content-Type":"text/json"}),n.end(JSON.stringify({error:"invalid token"}));return}}var i;n.writeHead(404,{"Content-Type":"text/html"}),n.end("<html><body>Not Found!</body></html>")})),v=f.listen(e),b=new(m().Server)({noServer:!0,path:"/ws"});b.on("connection",((e,s)=>{let r,a,l;if(s.url){const e=ie(s.url);r=e.get("token");const t=e.get("cwd");l=e.get("platform"),t&&(a=decodeURIComponent(t))}if(!r){const t="No token provided in websocket request";return o("closing ws:",t),void e.close(n.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE,t)}if(!te(r,t)){const t="Invalid token";return o("closing ws:",t),void e.close(n.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE,t)}const u=se({postMessage:t=>(e.send(t),Promise.resolve(!0)),onDidReceiveMessage(t){const s=e.on("message",t);return{dispose:()=>s.off("message",t)}},cwd:a??process.cwd(),logFileLocation:"stdout"===i?void 0:i,command:c,version:h,platform:void 0});e.on("close",(()=>{u(),d||setTimeout((()=>{0===X.numberOfActiveServers()&&process.exit(0)}),6e4)}))})),v.on("upgrade",((e,t,s)=>{b.handleUpgrade(e,t,s,(t=>{b.emit("connection",t,e)}))})),f.on("error",(function(t){if("listen"!==t.syscall)throw g({type:"error",error:t.toString()}),t;switch(t.code){case"EACCES":throw g({type:"error",error:`Port ${e} requires elevated privileges`}),t;case"EADDRINUSE":return void g({type:"addressInUse"});default:throw g({type:"error",error:t.toString()}),t}})),f.on("listening",(()=>g({type:"success",port:f.address().port,pid:process.pid})))}))}function ie(e){const t=u().parse(e).search?.replace(/^\?/,"").split("&").map((e=>e.split("=")));return new Map(t)}l().join(ee,"graphite-gti");const re={css:"text/css",html:"text/html",js:"text/javascript",ttf:"font/ttf"},oe={"/":"index.html"}}};
3
3
  //# sourceMappingURL=325.js.map