@withgraphite/graphite-cli 1.0.9 → 1.0.10
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/.CHANGELOG.md +10 -0
- package/999.js +1 -1
- package/999.js.map +1 -1
- package/build/asset-manifest.json +7 -7
- package/build/index.html +1 -1
- package/build/static/css/{74.67093f40.chunk.css → 521.ea7bdcfc.chunk.css} +1 -1
- package/build/static/css/521.ea7bdcfc.chunk.css.map +1 -0
- package/build/static/css/main.a9f28c16.css +2 -0
- package/build/static/css/main.a9f28c16.css.map +1 -0
- package/build/static/js/521.9e4e25a2.chunk.js +1 -0
- package/build/static/js/521.9e4e25a2.chunk.js.map +1 -0
- package/build/static/js/main.js +1 -1
- package/build/static/js/main.js.map +1 -1
- package/graphite.js +1 -1
- package/package.json +1 -1
- package/build/static/css/74.67093f40.chunk.css.map +0 -1
- package/build/static/css/main.c959f863.css +0 -2
- package/build/static/css/main.c959f863.css.map +0 -1
- package/build/static/js/74.ef2afffb.chunk.js +0 -1
- package/build/static/js/74.ef2afffb.chunk.js.map +0 -1
package/.CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Graphite CLI Changelog
|
|
2
2
|
|
|
3
|
+
# 1.0.10 2023-10-13
|
|
4
|
+
|
|
5
|
+
- Updated the `gt submit --draft` flag to only no longer convert already published PRs back to drafts.
|
|
6
|
+
- Added support for team reviewers. Team reviewers can either be specified using `gt submit --team-reviewers slug` or through `gt submit --reviewers org/slug`.
|
|
7
|
+
|
|
8
|
+
- Added output to `log short` when a branch needs to be fetched from remote (using `gt get`).
|
|
9
|
+
- Added output after `gt checkout` specifying whether a branch needs to be submitted, fetched, or restacked.
|
|
10
|
+
|
|
11
|
+
- Removed a reference to legacy command names.
|
|
12
|
+
|
|
3
13
|
# 1.0.9 2023-10-23
|
|
4
14
|
|
|
5
15
|
- Improved how PR descriptions are persisted across aborted `submit` runs.
|
package/999.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";exports.id=999,exports.ids=[999],exports.modules={33800:(e,t)=>{var n;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"}(n=t.ComparisonType||(t.ComparisonType={})),t.revsetArgsForComparison=function(e){switch(e.type){case n.UncommittedChanges:return["uncommitted"];case n.HeadChanges:return["head"];case n.StackChanges:return["stack"];case n.Committed:return["stack","--ref",e.hash]}},t.labelForComparison=function(e){switch(e.type){case n.UncommittedChanges:return"Uncommitted Changes";case n.HeadChanges:return"Head Changes";case n.StackChanges:return"Stack Changes";case n.Committed:return`In ${e.hash}`}},t.comparisonIsAgainstHead=function(e){switch(e.type){case n.UncommittedChanges:case n.HeadChanges:case n.StackChanges:return!0;case n.Committed:return!1}}},52060:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},2982:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cached=t.LRU=void 0;const r=n(30826);class s{constructor(e,t=3){this.maxItems=e,this.maxHashCollision=t,this.cache=new Map}get(e){let t;const n=o(e),s=this.cache.get(n);if(void 0!==s){const o=s.get(e);if(void 0!==o)t=o;else for(const[n,o]of s)if((0,r.is)(e,n)){t=o;break}this.cache.delete(n),this.cache.set(n,s)}return t}set(e,t){const n=o(e);let r=this.cache.get(n);if(void 0===r||r.size>=this.maxHashCollision?r=new Map([[e,t]]):r.set(e,t),this.cache.delete(n),void 0!==t&&(this.cache.set(n,r),this.cache.size>this.maxItems)){const e=this.cache.keys().next();e.done||this.cache.delete(e.value)}}delete(e){const t=o(e);this.cache.delete(t)}clear(){this.cache.clear()}}function o(e){const t=null==e?void 0:e.hashCode;return void 0!==t?t.apply(e):e}function i(e,t){var n,o;const i=null!==(n=null==t?void 0:t.cache)&&void 0!==n?n:new s(null!==(o=null==t?void 0:t.cacheSize)&&void 0!==o?o:10),a=null==t?void 0:t.getExtraKeys,l=function(...t){var n,s,o;const l=i.stats;if(!t.every(c))return null!=l&&(l.skip=(null!==(n=l.skip)&&void 0!==n?n:0)+1),e.apply(this,t);const u=(0,r.List)(a?[...a.apply(this),...t]:t),d=i.get(u);if(void 0!==d)return null!=l&&(l.hit=(null!==(s=l.hit)&&void 0!==s?s:0)+1),d;null!=l&&(l.miss=(null!==(o=l.miss)&&void 0!==o?o:0)+1);const h=e.apply(this,t);return i.set(u,h),h};return l.cache=i,l}t.LRU=s,t.cached=function(e,t){return"function"==typeof e?i(e,t):function(e){var t;const n=null!==(t=null==e?void 0:e.getExtraKeys)&&void 0!==t?t:function(){return(0,r.isValueObject)(this)?[this]:null!=this&&"object"==typeof this?Object.values(this).filter(c):[]};return function(t,r,s){const o=s.value;s.value=i(o,Object.assign(Object.assign({},e),{getExtraKeys:n}))}}(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,r.isValueObject)(e))}},61110:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5693:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(61110),t),s(n(52568),t),s(n(11268),t),s(n(66877),t)},52568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},11268:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Tracker=void 0;const r=n(48427);class s{constructor(e,t){this.sendData=e,this.context=t}error(e,t,n,r){const s=n instanceof Error?n.message||String(n):n;return this.track(e,Object.assign(Object.assign({},null!=r?r:{}),{errorMessage:s,errorName:t}))}operation(e,t,n,s){var o;const i=Date.now(),a=null!==(o=null==n?void 0:n.id)&&void 0!==o?o:(0,r.randomId)();try{const o=s({parentId:a});if((0,r.isPromise)(o))return o.then((t=>{const r=Date.now()-i;return this.track(e,Object.assign(Object.assign({},null!=n?n:{}),{duration:r,id:a})),t})).catch((r=>{const s=Date.now()-i;return this.error(e,t,r,Object.assign(Object.assign({},null!=n?n:{}),{duration:s,id:a})),Promise.reject(r)}));{const t=Date.now()-i;return this.track(e,Object.assign(Object.assign({},null!=n?n:{}),{duration:t,id:a})),o}}catch(r){const s=Date.now()-i;throw this.error(e,t,r,Object.assign(Object.assign({},null!=n?n:{}),{duration:s,id:a})),r}}trackAsParent(e,t){var n;const o=null!==(n=null==t?void 0:t.id)&&void 0!==n?n:(0,r.randomId)();return this.trackData(Object.assign(Object.assign({},t),{eventName:e,id:o})),new s(((e,t)=>this.trackData(Object.assign(Object.assign({},e),t))),{parentId:o})}track(e,t){return this.trackData(Object.assign(Object.assign({},t),{eventName:e}))}trackData(e){var t,n;const s=null!==(t=null==e?void 0:e.id)&&void 0!==t?t:(0,r.randomId)(),o=null!==(n=null==e?void 0:e.timestamp)&&void 0!==n?n:Date.now(),i=Object.assign({timestamp:o,id:s},null!=e?e:{});this.sendData(i,this.context)}}t.Tracker=s},66877:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},33905:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.newAbortController=void 0;const r=n(53811);t.newAbortController=function(){return"function"==typeof AbortController?new AbortController:new r.AbortController}},66960:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0,t.debounce=function(e,t,n=void 0,r=!1){let s,o=!0;function i(...a){let c;if(r){if(c=function(){o=!0,s=void 0},!o)return clearTimeout(s),void(s=setTimeout(c,t));o=!1,e.apply(n,a)}else i.reset(),c=function(){s=void 0,e.apply(n,a)};s=setTimeout(c,t)}return i.reset=function(){clearTimeout(s),s=void 0,o=!0},i.isPending=function(){return null!=s},i}},90828:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SelfUpdate=void 0;class n{constructor(e){this.inner=e}hashCode(){return this.inner.hashCode()+1}equals(e){if(!(e instanceof n))return!1;if(this===e)return!0;const t=e.inner,r=this.inner.equals(t);return r&&this.inner!==t&&(this.inner=t),r}}t.SelfUpdate=n},98696:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(5693),t),s(n(33800),t),s(n(86099),t),s(n(40256),t),s(n(85249),t),s(n(48427),t),s(n(66224),t),s(n(2982),t),s(n(13035),t),s(n(90828),t),s(n(52060),t),s(n(66960),t),s(n(33905),t),s(n(75905),t)},13035:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.minimalDisambiguousPaths=void 0,t.minimalDisambiguousPaths=function(e,t={}){const n=e.map((e=>{const t=function(e){return e.replace(/[^\\]/g,"").length>e.replace(/[^/]/g,"").length?"\\":"/"}(e),n=/^(\w:).*/.exec(e),r=null!=n?n[1]:"";return{depth:null,parts:e.split(t).reverse().filter((e=>""!==e&&e!==r)),rootPrefix:r,separator:t,hadLeadingSeparator:e.startsWith(t)||r.length>0&&e.startsWith(r)}})),r=null==t.maxDepth?Math.max(...n.map((e=>e.parts.length))):t.maxDepth,s=new Set(n),o=new Map;for(let e=1;e<=r;e++){o.clear();for(const t of s){const n=t.parts.slice(0,e).join(t.separator);o.has(n)||o.set(n,new Set),o.get(n).add(t)}for(const t of o.values())if(1===t.size){const n=Array.from(t)[0];n.depth=e,s.delete(n)}}return n.map((({depth:e,parts:n,rootPrefix:s,separator:o,hadLeadingSeparator:i})=>{var a;let c=n.slice(0,null==e?r:e).reverse();return 0===c.length?`${s}${o}`:((1===c.length&&""===c[0]||c.length>1&&""!==c[0])&&(c=c.length===n.length?i?[s,...c]:c:(null!==(a=t.alwaysShowLeadingSeparator)&&void 0!==a?a:i)?["",...c]:c),c.join(o))}))}},75905:(e,t)=>{var n;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"}(n=t.DiffType||(t.DiffType={}));const r=/^diff --git (.*) (.*)$/,s=/^rename from (.*)$/,o=/^rename to (.*)$/,i=/^copy from (.*)$/,a=/^copy to (.*)$/,c=/^new file mode (\d{6})$/,l=/^deleted file mode (\d{6})$/,u=/^old mode (\d{6})$/,d=/^new mode (\d{6})$/,h=/@@ -(\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)||[],C=[];let y=0;function b(){const e={hunks:[]};for(C.push(e),function(e){for(;y<t.length;){const n=t[y],s=r.exec(n);if(s){e.oldFileName=s[1],e.newFileName=s[2],y++;break}y++}}(e);y<t.length;){const n=t[y];if(/^old mode/.test(n))w(e);else if(/^new mode/.test(n))O(e);else if(/^deleted file mode/.test(n))S(e);else if(/^new file mode/.test(n))E(e);else if(/^copy /.test(n))R(e);else if(/^rename /.test(n))k(e);else{if(/^--- /.test(n)){M(e);break}if(/^diff --git/.test(n))break;y++}}!function(e){for(;y<t.length;){const n=t[y];if(r.test(n))break;/^@@/.test(n)?e.hunks.push(_()):y++}}(e)}function w(e){const r=u.exec(t[y]);f(null!==r,`invalid format '${t[y]}'`),e.oldMode=r[1],e.type=n.Modified,y++}function O(e){const r=d.exec(t[y]);f(null!==r,`invalid format '${t[y]}'`),e.newMode=r[1],e.type=n.Modified,y++}function S(e){const r=l.exec(t[y]);f(null!==r,`invalid format '${t[y]}'`),e.newMode=r[1],e.type=n.Removed,y++}function E(e){const r=c.exec(t[y]);f(null!==r,`invalid format '${t[y]}'`),e.newMode=r[1],e.type=n.Added,y++}function R(e){f(i.test(t[y]),`invalid format '${t[y]}'`),f(a.test(t[y+1]),`invalid format '${t[y+1]}'`),e.type=n.Copied,y+=2}function k(e){f(s.test(t[y]),`invalid format '${t[y]}'`),f(o.test(t[y+1]),`invalid format '${t[y+1]}'`),e.type=n.Renamed,y+=2}function M(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=n.Modified),y+=2}function _(){const e=t[y++].split(h),n={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===n.oldLines&&(n.oldStart+=1),0===n.newLines&&(n.newStart+=1);let r=0,s=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;n.lines.push(t[y]),n.linedelimiters.push(v[y]||"\n"),"+"===e?r++:"-"===e?s++:" "===e&&(r++,s++)}return r||1!==n.newLines||(n.newLines=0),s||1!==n.oldLines||(n.oldLines=0),n}for(;y<t.length;)b();return C}},85249:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deserializeFromString=t.deserialize=t.serializeToString=t.serialize=void 0;const n={__rpcType:"undefined"};function r(e){if(void 0===e)return n;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])=>[r(e),r(t)]))};if(e instanceof Set)return{__rpcType:"Set",data:Array.from(e.values()).map(r)};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=>r(e)));if("object"==typeof e){const t={__rpcType:"object"};for(const[n,s]of Object.entries(e))t[n]=r(s);return t}throw new Error(`cannot serialize argument ${e}`)}function s(e){if("object"!=typeof e||null==e)return e;if(Array.isArray(e))return e.map((e=>s(e)));const t=e;switch(t.__rpcType){case"undefined":return;case"Map":return new Map(t.data.map((([e,t])=>[s(e),s(t)])));case"Set":return new Set(t.data.map(s));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,n={};for(const[e,r]of Object.entries(t))"__rpcType"!==e&&(n[e]=s(r));return n}default:throw new Error(`cannot deserialize unknown type ${t}`)}}t.serialize=r,t.serializeToString=function(e){return JSON.stringify(r(e))},t.deserialize=s,t.deserializeFromString=function(e){return s(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 n;Object.defineProperty(t,"__esModule",{value:!0}),t.SucceedableRevset=t.CommandRunner=void 0,(n=t.CommandRunner||(t.CommandRunner={})).Graphite="gt",n.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,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(50209),t),s(n(85119),t),s(n(45852),t),s(n(74259),t),s(n(1018),t),s(n(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,n)=>{e.resolve=t,e.reject=n})),e},t.basename=function(e,t="/"){const n=e.lastIndexOf(t);return-1===n?e:e.slice(n+1)},t.findParentWithClassName=function(e,t){var n;let r=e;for(;r;){if(null===(n=r.classList)||void 0===n?void 0:n.contains(t))return r;r=r.parentElement}},t.mapObject=function(e,t){return Object.fromEntries(Object.entries(e).map(t))},t.generatorContains=function(e,t){const n="function"==typeof t?t:e=>e===t;for(const t of e)if(n(t))return!0;return!1},t.zip=function*(e,t){const n=e[Symbol.iterator](),r=t[Symbol.iterator]();for(;;){const e=n.next(),t=r.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)}},25999:(e,t,n)=>{n.r(t),n.d(t,{startServer:()=>X});var r=n(98696),s=n(57147),o=n.n(s),i=n(13685),a=n.n(i),c=n(71017),l=n.n(c),u=n(57310),d=n.n(u),h=n(95352),m=n.n(h),p=n(22037),g=n.n(p);function f(){try{return g().userInfo().username}catch(e){try{const{env:e}=process;return(0,r.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 C=e=>{};var y=n(73837),b=n.n(y);const w=console;var O=n(60492),S=n.n(O),E=n(80909),R=n.n(E),k=n(82361);class M extends k.EventEmitter{}class _{codeReviewSystem;runCommand;constructor(e,t){this.codeReviewSystem=e,this.runCommand=t}diffSummaries=new M;onChangeDiffSummaries(e){const t=t=>e({value:t}),n=t=>e({error:t});return this.diffSummaries.on("data",t),this.diffSummaries.on("error",n),{dispose:()=>{this.diffSummaries.off("data",t),this.diffSummaries.off("error",n)}}}async triggerDiffSummariesFetch(e){const t=await this.runCommand(["internal-only","prs"]),n=JSON.parse(t.stdout);this.diffSummaries.emit("data",n)}dispose(){this.diffSummaries.removeAllListeners()}getSummaryName(){return`github:${this.codeReviewSystem.hostname}/${this.codeReviewSystem.owner}/${this.codeReviewSystem.repo}`}runExternalCommand(e,t,n,r){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,n,s){if(null!=this.runningOperation)return this.queuedOperations.push({...e,tracker:n}),void t({id:e.id,kind:"queue",queue:this.queuedOperations.map((e=>e.id))});this.runningOperation=e;const o=(...n)=>{switch(n[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:n[1]});break;case"stderr":t({id:e.id,kind:"stderr",message:n[1]});break;case"exit":t({id:e.id,kind:"exit",exitCode:n[1],timestamp:Date.now()})}};try{const i=(0,r.newAbortController)();if(this.abortController=i,await n.operation(e.trackEventName,"RunOperationError",{extras:{args:e.args,runner:e.runner}},(t=>this.runCallback(e,s,o,i.signal))),this.runningOperation=void 0,this.queuedOperations.length>0){const e=this.queuedOperations.shift();null!=e&&this.runOrQueueOperation(e,t,e.tracker,s)}}catch(n){const r=n.toString();this.logger.log("error running operation: ",e.args[0],r),t({id:e.id,kind:"error",error:r}),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 M;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",(n=>{n===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 j(e){let t,n;const r=()=>{const t=e();return n=t.then((()=>n=void 0),(()=>n=void 0)),t},s=()=>(t=void 0,r());return()=>null==n?r():(()=>{if(null==t){if(null==n)throw new Error("pendingCall must not be null!");t=n.then(s,s)}return t})()}var N=n(51887);const I="0.1.4";class x{info;logger;IGNORE_COMMIT_MESSAGE_LINES_REGEX=/^((?:HG|SL):.*)/gm;mergeConflicts=void 0;uncommittedChanges=null;smartlogCommits=null;mergeConflictsEmitter=new M;uncommittedChangesEmitter=new M;smartlogCommitsChangesEmitter=new M;smartlogCommitsBeginFetchingEmitter=new M;uncommittedChangesBeginFetchingEmitter=new M;disposables=[()=>this.mergeConflictsEmitter.removeAllListeners(),()=>this.uncommittedChangesEmitter.removeAllListeners(),()=>this.smartlogCommitsChangesEmitter.removeAllListeners(),()=>this.smartlogCommitsBeginFetchingEmitter.removeAllListeners(),()=>this.uncommittedChangesBeginFetchingEmitter.removeAllListeners()];onDidDispose(e){this.disposables.push(e)}operationQueue;watchForChangesDisposer;pageFocusTracker=new T;codeReviewProvider;currentVisibleCommitRangeIndex=0;visibleCommitRanges=[r.DEFAULT_DAYS_OF_COMMITS_TO_LOAD,60,void 0];constructor(e,t){this.info=e,this.logger=t;const n=e.codeReviewSystem;"github"===n.type&&(this.codeReviewProvider=new _(n,this.runCommand.bind(this))),this.watchForChangesDisposer=function(e,t,n){if("success"!==e.type)return;const{repoRoot:r,dotdir:s}=e;if(null==r||null==s)return void t.error(`skipping chokidar subscription since ${r} is not a repository`);const o=N.watch(s,{cwd:s});o.on("ready",(()=>{n("everything")})),o.on("all",((e,t)=>{t.startsWith("rebase-merge")&&n("merge conflicts"),(t.startsWith("index")||t.startsWith("HEAD"))&&n("uncommitted changes"),(t.startsWith("refs/heads")||t.startsWith("refs/branch-metadata")||t.startsWith("HEAD"))&&n("branches")}));const i=l().relative(r,s),a=N.watch(r,{cwd:r,ignored:`${i}/**`});return a.on("all",(()=>{n("uncommitted changes")})),()=>{a.close().catch((()=>t.error(`failed to close chokidar worktree watcher for ${r}`))),o.close().catch((()=>t.error(`failed to close chokidar dotdir watcher for ${s}`)))}}(e,t,(e=>{"uncommitted changes"===e?(this.fetchUncommittedChanges(),this.checkForMergeConflicts()):"branches"===e?this.fetchSmartlogCommits():"merge conflicts"===e?this.checkForMergeConflicts():"everything"===e&&(this.fetchUncommittedChanges(),this.fetchSmartlogCommits(),this.checkForMergeConflicts())})),this.operationQueue=new D(this.logger,((e,t,n,s)=>{if(e.runner===r.CommandRunner.Graphite)return this.runOperation(e,n,t,s);if(e.runner===r.CommandRunner.CodeReviewProvider){const r=this.normalizeOperationArgs(t,e.args);return null==this.codeReviewProvider?.runExternalCommand?Promise.reject(Error("CodeReviewProvider does not support running external commands")):this.codeReviewProvider?.runExternalCommand(t,r,n,s)??Promise.resolve()}return Promise.resolve()}));const s=new Set,o=this.subscribeToSmartlogCommitsChanges((e=>{if(e.commits.value){const t=[],n=e.commits.value.filter((e=>e.pr)).map((e=>e.pr?.number));for(const e of n)s.has(e)||(t.push(e),s.add(e));t.length>0&&this.codeReviewProvider?.triggerDiffSummariesFetch(this.getAllDiffIds())}}));this.checkForMergeConflicts(),this.disposables.push((()=>o.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.watchForChangesDisposer?.()}onChangeConflictState(e){return this.mergeConflictsEmitter.on("change",e),this.mergeConflicts&&e(this.mergeConflicts),{dispose:()=>this.mergeConflictsEmitter.off("change",e)}}checkForMergeConflicts=(0,r.debounce)(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"),o().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 n=Date.now();let r;try{const e=await this.runCommand(["internal-only","status"]);r=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)}const s=await o().promises.readFile(l().join(this.info.dotdir,"rebase-merge","head-name")).then((e=>{const t=e.toString();return t.startsWith("refs/heads/")?t.slice(11).trimEnd():void 0}),(()=>{}));if(this.mergeConflicts=function(e,t,n,r){const s=n;if(!s?.conflicts||!t)return;const o=s.files.filter((e=>"UNRESOLVED"===e.status)),i={state:"loaded",branchName:t,files:[],fetchStartTimestamp:r,fetchCompletedTimestamp:Date.now()};if(null!=e?.files&&e.files.length>0){const t=new Set(o.map((e=>e.path)));i.files=e.files.map((e=>t.has(e.path)?{path:e.path,status:"UNRESOLVED"}:{path:e.path,status:"RESOLVED"}))}else i.files=o.map((e=>({path:e.path,status:"UNRESOLVED"})));return i}(this.mergeConflicts,s,r,n),this.logger.info(`repo ${this.mergeConflicts?"IS":"IS NOT"} in merge conflicts`,{mergeConflicts:this.mergeConflicts,files:this.mergeConflicts?.files}),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: ",{branchName:s,remainingConflicts:t})}this.mergeConflictsEmitter.emit("change",this.mergeConflicts)})),100);getMergeConflicts(){return this.mergeConflicts}static async getRepoInfo(e,t,n){const r=await async function(e,t,n){try{return(await F({command:e,args:["--version"],logger:t,cwd:n})).stdout}catch(e){throw t.error(`Failed to find gt version in ${n}`,e),e}}(e,t,n).catch((e=>e));if(r instanceof Error)return{type:"invalidCommand",command:e??"gt"};if("local"!==r&&"dev"!==r&&R().lt(r,I))return{type:"invalidVersion",command:e??"gt",versionFound:r,versionRequired:I};const[s,o,i,a]=await Promise.all([L(e,t,n),A(e,t,n),$(e,t,n,"graphite.branch_edit").then((e=>e??"amend")),$(e,t,n,"graphite.create_prs_as").then((e=>e??"draft"))]);if(null==o)return{type:"cwdNotARepository",cwd:n};let c;if(void 0===o.remote)c={type:"none"};else{const{owner:e,name:t,hostname:n}=o.remote;c={type:"github",owner:e,repo:t,hostname:n}}const l={type:"success",command:e,dotdir:o.dotDir,repoRoot:o.rootDir,codeReviewSystem:c,preferredBranchEdit:i,createPrsAs:a,profile:s,trunkBranch:o.trunkBranch};return t.info("repo info: ",l),l}async runOrQueueOperation(e,t,n,r){await this.operationQueue.runOrQueueOperation(e,t,n,r)}abortRunningOpeation(e){this.operationQueue.abortRunningOperation(e)}normalizeOperationArgs(e,t){const n=(0,r.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(n,t.path)));case"succeedable-revset":return`max(successors(${t.revset}))`}return t}))}async runOperation(e,t,n,r){const s=this.normalizeOperationArgs(n,e.args),{stdin:o}=e,{command:i,args:a,options:c}=U(this.info.command,s,n,o?{input:o}:void 0);this.logger.log("run operation: ",i,s.join(" "));const l=S()(i,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)})),r.addEventListener("abort",(()=>{this.logger.log("kill operation: ",i,s.join(" "))})),function(e,t){t.addEventListener("abort",(()=>{"win32"==g().platform()?e.kill("SIGKILL",{forceKillAfterTimeout:!1}):(e.kill("SIGCONT"),e.kill("SIGTERM",{forceKillAfterTimeout:5e3}))}))}(l,r),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=(0,r.debounce)(j((async()=>{const e=Date.now();try{this.uncommittedChangesBeginFetchingEmitter.emit("start");const t=await this.runCommand(["internal-only","status"]),n=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:n}},this.uncommittedChangesEmitter.emit("change",this.uncommittedChanges)}catch(n){if(this.logger.error("Error fetching files: ",n),null!=(t=n)&&"object"==typeof t&&"stderr"in t&&n.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:n instanceof Error?n:new Error(n)}})}var t})),100);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=(0,r.debounce)(j((async()=>{const e=Date.now();try{this.smartlogCommitsBeginFetchingEmitter.emit("start");const t=await this.runCommand(["internal-only","log"]),n=function(e,t){let n=[];try{n=JSON.parse(t)}catch(t){e.error("failed to parse branch info",t)}return n}(this.logger,t.stdout.trim());if(0===n.length)throw new Error(r.ErrorShortMessages.NoCommitsFetched);this.smartlogCommits={fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),commits:{value:n}},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)}})}})),100);subscribeToHeadCommit(e){let t=this.smartlogCommits?.commits.value?.find((e=>e.isHead));null!=t&&e(t);const n=n=>{const r=n?.commits.value?.find((e=>e.isHead));null!=r&&r.branch!==t?.branch&&(e(r),t=r)};return this.smartlogCommitsChangesEmitter.on("change",n),{dispose:()=>{this.smartlogCommitsChangesEmitter.off("change",n)}}}catLimiter=new P(4,(e=>this.logger.info("[cat]",e)));cat(e,t){const n=l().relative(this.info.repoRoot,e);return this.catLimiter.enqueueRun((async()=>(await this.runCommand(["internal-only","relative-cat",...this.catArgs(t,n)],void 0,{stripFinalNewline:!1})).stdout))}catArgs(e,t){switch(e.type){case r.ComparisonType.UncommittedChanges:return["uncommitted",t];case r.ComparisonType.HeadChanges:return["head",t];case r.ComparisonType.StackChanges:return["stack",t];case r.ComparisonType.Committed:return["stack",t,"--ref",e.hash]}}getAllDiffIds(){return this.getSmartlogCommits()?.commits.value?.map((e=>e.pr?.number)).filter(r.notEmpty)??[]}runCommand(e,t,n){return F({command:this.info.command,args:e,logger:this.logger,cwd:(0,r.unwrap)(t??this.info.repoRoot),options:n})}getConfig(e){return $(this.info.command,this.logger,this.info.repoRoot,e)}setConfig(e,t,n){return async function({command:e,logger:t,cwd:n,level:r,configName:s,configValue:o}){await F({command:e,args:["internal-only","set-config","--level",r,s,o],logger:t,cwd:n})}({command:this.info.command,logger:this.logger,cwd:this.info.repoRoot,level:e,configName:t,configValue:n})}}function F({command:e,args:t,logger:n,cwd:r,options:s}){const{command:o,args:i,options:a}=U(e,t,r,s);return n&&n.log("run command: ",o,...i,a),S()(o,i,a)}async function A(e,t,n){try{return JSON.parse((await F({command:e,args:["internal-only","repo-info"],logger:t,cwd:n})).stdout)}catch(e){return void t.error(`Failed to find repository info in ${n}`,e)}}async function L(e,t,n){try{return JSON.parse((await F({command:e,args:["internal-only","profile"],logger:t,cwd:n})).stdout)}catch(e){return t.error(`Failed to find repository profile in ${n}`,e),{appUrl:"https://app.graphite.dev/"}}}async function $(e,t,n,r){try{return(await F({command:e,args:["internal-only","config",r],logger:t,cwd:n})).stdout.trim()}catch{return}}function U(e,t,n,r){let s=[...t];"win32"!==process.platform&&(s=s.map((e=>e.replace(/\\\\/g,"\\"))));const o={...r,env:{LANG:"en_US.utf-8",EDITOR:void 0,GRAPHITE_INTERACTIVE:"true"},cwd:n};return!e&&process.argv[1].startsWith("/snapshot/")?(e=process.argv[0],s=["/snapshot/monologue/apps/public/cli/dist/graphite.js",...s]):e||(e="gt"),{command:e,args:s,options:o}}var q=n(32081);const H={platformName:"browser",handleMessageFromClient:(e,t)=>{switch(t.type){case"platform/openFile":{const n=l().join((0,r.unwrap)(e?.info.repoRoot),t.path);let s;if(null==s)switch(process.platform){case"darwin":s="/usr/bin/open";break;case"win32":s="notepad.exe";break;case"linux":s="xdg-open"}if(s){e?.logger.log("open file",n);const t=(0,q.spawn)(s,[n],{detached:!0,stdio:"ignore",windowsHide:!1,windowsVerbatimArguments:!0});t.on("error",(t=>{e?.logger.log("failed to open",n,t)})),t.unref()}break}}}};class B{promise;disposeFunc;constructor(e,t){this.promise=e,this.disposeFunc=t}unref(){this.disposed||(this.disposed=!0,this.disposeFunc())}internalReference;disposed=!1}class z{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 W=new class{RepositoryType;constructor(e=x){this.RepositoryType=e}reposByRoot=new Map;activeReposEmitter=new M;lookup(e){for(const n of this.reposByRoot.values())if((e===n.value.info.repoRoot||e.startsWith((t=n.value.info.repoRoot).endsWith(l().sep)?t:t+l().sep))&&!n.isDisposed)return n;var t}getOrCreate(e,t,n){const r=this.lookup(n);if(r)return r.ref(),new B(Promise.resolve(r.value),(()=>r.dispose()));let s;return s=new B((async()=>{const r=await this.RepositoryType.getRepoInfo(e,t,n);if("success"!==r.type)return r;if(s.disposed)return{type:"unknownError",error:new Error("Repository already disposed")};const o=this.lookup(r.repoRoot);if(o)return o.ref(),s.internalReference=o,o.value;const i=new this.RepositoryType(r,t),a=new z(i);return a.ref(),s.internalReference=a,this.reposByRoot.set(r.repoRoot,a),this.activeReposEmitter.emit("change"),i})(),(()=>{s.internalReference&&s.internalReference.dispose(),s.unref()})),s}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 V{platform;connection;tracker;logger;listenersByType=new Map;incomingListener;repoDisposables=[];subscriptions=new Map;activeRepoRef;queuedMessages=[];currentState={type:"loading"};pageId=(0,r.randomId)();constructor(e,t,n,s){this.platform=e,this.connection=t,this.tracker=n,this.logger=s;let o=null;this.incomingListener=this.connection.onDidReceiveMessage(((e,n)=>{if(n)return null==o?void t.logger?.error("Error: got a binary message when not expecting one"):(this.handleIncomingMessageWithPayload(o,e),void(o=null));if(null!=o)return t.logger?.error("Error: didnt get binary payload after a message that requires one"),void(o=null);const s=e.toString("utf-8"),i=(0,r.deserializeFromString)(s);if(function(e){return null!=e&&"object"==typeof e&&!0===e.hasBinaryPayload}(i))o=i;else if("loading"===this.currentState.type)this.queuedMessages.push(i);else try{this.handleIncomingMessage(i)}catch(e){t.logger?.error("error handling incoming message: ",i,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 n=e.getSmartlogCommits(),r=function(e,t){let n;if(null!=e){const r=new Map(e.map((e=>[e.branch,e])));let s=t;for(;null!=s;){if(s.partOfTrunk){n=s;break}if(null==s.parents[0])break;s=r.get(s.parents[0])}}return n}(n?.commits.value,t);this.tracker.track("HeadCommitChanged",{extras:{hash:t.branch,public:r?.branch}})}))),this.processQueuedMessages()}postMessage(e){this.connection.postMessage((0,r.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=W.getOrCreate(t,this.logger,e),this.activeRepoRef.promise.then((t=>{t instanceof x?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:n,filename:s}=e,o=null;if(null==o)return;this.tracker.operation("UploadImage","UploadImageError",{},(()=>o((0,r.unwrap)(this.connection.logger),{filename:s,data:t}))).then((e=>{this.connection.logger?.info("sucessfully uploaded file",s,e),this.postMessage({type:"uploadFileResult",id:n,result:{value:e}})})).catch((e=>{this.connection.logger?.info("error uploading file",s,e),this.postMessage({type:"uploadFileResult",id:n,result:{error:e}})}));break}}}handleIncomingMessage(e){this.handleIncomingGeneralMessage(e);const{currentState:t}=this;switch(t.type){case"repo":{const{repo:n,cwd:r}=t;this.handleIncomingMessageWithRepo(e,n,r);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,n){const{logger:s}=t;switch(e.type){case"subscribe":{const{subscriptionID:n,kind:r}=e;switch(r){case"uncommittedChanges":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"uncommittedChanges",subscriptionID:n,data:e})},r=t.getUncommittedChanges();null!=r&&e(r);const s=[];s.push(t.subscribeToUncommittedChanges(e)),t.fetchUncommittedChanges(),s.push(t.subscribeToUncommittedChangesBeginFetching((()=>this.postMessage({type:"beganFetchingUncommittedChangesEvent"})))),this.subscriptions.set(n,{dispose:()=>{s.forEach((e=>e.dispose()))}});break}case"smartlogCommits":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"smartlogCommits",subscriptionID:n,data:e})},r=t.getSmartlogCommits();null!=r&&e(r);const s=[];s.push(t.subscribeToSmartlogCommitsChanges(e)),t.fetchSmartlogCommits(),s.push(t.subscribeToSmartlogCommitsBeginFetching((()=>this.postMessage({type:"beganFetchingSmartlogCommitsEvent"})))),this.subscriptions.set(n,{dispose:()=>{s.forEach((e=>e.dispose()))}});break}case"mergeConflicts":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"mergeConflicts",subscriptionID:n,data:e})},r=t.getMergeConflicts();null!=r&&e(r),this.subscriptions.set(n,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:r}=e;t.runOrQueueOperation(r,(e=>{this.postMessage({type:"operationProgress",...e}),"queue"===e.kind&&this.tracker.track("QueueOperation",{extras:{operation:r.trackEventName}})}),this.tracker,n);break}case"abortRunningOperation":{const{operationId:n}=e;t.abortRunningOpeation(n);break}case"getConfig":t.getConfig(e.name).catch((()=>{})).then((t=>{s.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=>(s?.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=>(s?.error("error fetching upgrade prompt",e.toString()),{error:e}))).then((e=>this.postMessage({type:"fetchedUpgradePrompt",message:e.value||""})));break;case"setConfig":s.info("set config",e.name,e.value),t.setConfig("user",e.name,e.value).catch((t=>{s.error("error setting config",e.name,e.value,t)}));break;case"deleteFile":{const{filePath:n}=e,r=function(e,t,n=l()){const r=n.resolve(t.info.repoRoot,e);return r.startsWith(t.info.repoRoot+n.sep)?r:null}(n,t);if(null==r)return void s.warn("can't delete file outside of the repo",n);o().promises.rm(r).then((()=>{s.info("deleted file from filesystem",r)})).catch((e=>{s.error("unable to delete file",r,e)}));break}case"requestComparison":{const{comparison:n}=e;t.runCommand(["internal-only","diff",...(0,r.revsetArgsForComparison)(n)]).then((e=>({value:e.stdout}))).catch((e=>(s?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"comparison",comparison:n,data:{diff:e}})));break}case"requestChangedFiles":{const{branch:n}=e;t.runCommand(["internal-only","changed-files",n]).then((e=>JSON.parse(e.stdout))).catch((e=>(s?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"changedFiles",branch:n,data:e})));break}case"requestComparisonContextLines":{const{id:{path:n,comparison:r},start:s,numLines:o}=e;t.cat(n,r).catch((()=>"")).then((e=>this.postMessage({type:"comparisonContextLines",lines:e.split("\n").slice(s-1,s-1+o),path:n})));break}case"refresh":s?.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 n=JSON.parse(e.stdout);this.postMessage({type:"fetchedCommitMessageTemplate",templates:Object.fromEntries(Object.entries(n).map((([e,n])=>[e,n.replace(t.IGNORE_COMMIT_MESSAGE_LINES_REGEX,"")])))})})).catch((e=>{s?.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 G=n(6113);const J="win32"==process.platform?l().join((0,r.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 Q(e,t){const n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&(0,G.timingSafeEqual)(n,r)}function K(e){const t=e.logger??(e.logFileLocation?function(e){const t=(...t)=>{const n=b().format(...t)+"\n";o().promises.appendFile(e,n)};return{info:t,log:t,warn:t,error:t,getLogFileContents:()=>o().promises.readFile(e,"utf-8")}}(e.logFileLocation):w);e.logger=t;const n=e?.platform??H,s=e?.version??"unknown";t.log(`establish client connection for ${e.cwd}`),t.log(`platform '${n.platformName}', version '${s}', command '${e.command}'`);const i=function(e,t,n,s=C){return new r.Tracker(((e,t)=>{const{logger:n}=t;n.log("[track]",e.eventName,e.errorName??"",e.errorMessage??"",null!=e.extras?JSON.stringify(e.extras):"");try{Promise.resolve(s({...e,...t.data})).catch((e=>{}))}catch{}}),new v(e,function(e,t){return{platform:e,version:t,repo:void 0,sessionId:(0,r.randomId)(),unixname:f(),osArch:g().arch(),osType:g().platform(),osRelease:g().release(),hostname:g().hostname()}}(t.platformName,n)))}(t,n,s,(t=>F({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})));i.track("ClientConnection",{extras:{cwd:e.cwd}});let a=new V(n,e,i,t);return a.setActiveRepoForCwd(e.cwd),()=>{a?.dispose(),a=null}}function X({port:e,sensitiveToken:t,challengeToken:n,logFileLocation:s,logInfo:i,command:c,gtVersion:u,foreground:h,frontendDir:p}){return new Promise((g=>{try{const e=JSON.parse(o().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}\``}),ee[t]=t.slice(1)}catch(e){}ee["/favicon.ico"]="favicon.ico";const f=a().createServer((async(e,r)=>{if(e.url){const{pathname:i}=d().parse(e.url);if(null!=i&&ee.hasOwnProperty(i)){const e=ee[i];let t;try{t=await o().promises.readFile(l().join(p,"build",e))}catch(e){return r.writeHead(500,{"Content-Type":"text/plain"}),void r.end((s=e.toString(),s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"")))}const n=e.lastIndexOf("."),a=e.slice(n+1),c=Z[a]??"text/plain";return r.writeHead(200,{"Content-Type":c}),void r.end(t)}if("/challenge_authenticity"===i){const s=Y(e.url).get("token");if(s&&Q(s,t)){r.writeHead(200,{"Content-Type":"text/json"});const e={challengeToken:n,pid:process.pid};r.end(JSON.stringify(e))}else r.writeHead(401,{"Content-Type":"text/json"}),r.end(JSON.stringify({error:"invalid token"}));return}}var s;r.writeHead(404,{"Content-Type":"text/html"}),r.end("<html><body>Not Found!</body></html>")})),v=f.listen(e),C=new(m().Server)({noServer:!0,path:"/ws"});C.on("connection",((e,n)=>{let o,a,l;if(n.url){const e=Y(n.url);o=e.get("token");const t=e.get("cwd");l=e.get("platform"),t&&(a=decodeURIComponent(t))}if(!o){const t="No token provided in websocket request";return i("closing ws:",t),void e.close(r.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE,t)}if(!Q(o,t)){const t="Invalid token";return i("closing ws:",t),void e.close(r.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE,t)}const d=K({postMessage:t=>(e.send(t),Promise.resolve(!0)),onDidReceiveMessage(t){const n=e.on("message",t);return{dispose:()=>n.off("message",t)}},cwd:a??process.cwd(),logFileLocation:"stdout"===s?void 0:s,command:c,version:u,platform:void 0});e.on("close",(()=>{d(),h||setTimeout((()=>{0===W.numberOfActiveServers()&&process.exit(0)}),6e4)}))})),v.on("upgrade",((e,t,n)=>{C.handleUpgrade(e,t,n,(t=>{C.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 Y(e){const t=d().parse(e).search?.replace(/^\?/,"").split("&").map((e=>e.split("=")));return new Map(t)}l().join(J,"graphite-gti");const Z={css:"text/css",html:"text/html",js:"text/javascript",ttf:"font/ttf"},ee={"/":"index.html"}}};
|
|
2
|
+
"use strict";exports.id=999,exports.ids=[999],exports.modules={33800:(e,t)=>{var n;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"}(n=t.ComparisonType||(t.ComparisonType={})),t.revsetArgsForComparison=function(e){switch(e.type){case n.UncommittedChanges:return["uncommitted"];case n.HeadChanges:return["head"];case n.StackChanges:return["stack"];case n.Committed:return["stack","--ref",e.hash]}},t.labelForComparison=function(e){switch(e.type){case n.UncommittedChanges:return"Uncommitted Changes";case n.HeadChanges:return"Head Changes";case n.StackChanges:return"Stack Changes";case n.Committed:return`In ${e.hash}`}},t.comparisonIsAgainstHead=function(e){switch(e.type){case n.UncommittedChanges:case n.HeadChanges:case n.StackChanges:return!0;case n.Committed:return!1}}},52060:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},2982:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cached=t.LRU=void 0;const r=n(30826);class s{constructor(e,t=3){this.maxItems=e,this.maxHashCollision=t,this.cache=new Map}get(e){let t;const n=o(e),s=this.cache.get(n);if(void 0!==s){const o=s.get(e);if(void 0!==o)t=o;else for(const[n,o]of s)if((0,r.is)(e,n)){t=o;break}this.cache.delete(n),this.cache.set(n,s)}return t}set(e,t){const n=o(e);let r=this.cache.get(n);if(void 0===r||r.size>=this.maxHashCollision?r=new Map([[e,t]]):r.set(e,t),this.cache.delete(n),void 0!==t&&(this.cache.set(n,r),this.cache.size>this.maxItems)){const e=this.cache.keys().next();e.done||this.cache.delete(e.value)}}delete(e){const t=o(e);this.cache.delete(t)}clear(){this.cache.clear()}}function o(e){const t=null==e?void 0:e.hashCode;return void 0!==t?t.apply(e):e}function i(e,t){var n,o;const i=null!==(n=null==t?void 0:t.cache)&&void 0!==n?n:new s(null!==(o=null==t?void 0:t.cacheSize)&&void 0!==o?o:10),a=null==t?void 0:t.getExtraKeys,l=function(...t){var n,s,o;const l=i.stats;if(!t.every(c))return null!=l&&(l.skip=(null!==(n=l.skip)&&void 0!==n?n:0)+1),e.apply(this,t);const u=(0,r.List)(a?[...a.apply(this),...t]:t),d=i.get(u);if(void 0!==d)return null!=l&&(l.hit=(null!==(s=l.hit)&&void 0!==s?s:0)+1),d;null!=l&&(l.miss=(null!==(o=l.miss)&&void 0!==o?o:0)+1);const h=e.apply(this,t);return i.set(u,h),h};return l.cache=i,l}t.LRU=s,t.cached=function(e,t){return"function"==typeof e?i(e,t):function(e){var t;const n=null!==(t=null==e?void 0:e.getExtraKeys)&&void 0!==t?t:function(){return(0,r.isValueObject)(this)?[this]:null!=this&&"object"==typeof this?Object.values(this).filter(c):[]};return function(t,r,s){const o=s.value;s.value=i(o,Object.assign(Object.assign({},e),{getExtraKeys:n}))}}(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,r.isValueObject)(e))}},61110:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5693:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(61110),t),s(n(52568),t),s(n(11268),t),s(n(66877),t)},52568:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},11268:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Tracker=void 0;const r=n(48427);class s{constructor(e,t){this.sendData=e,this.context=t}error(e,t,n,r){const s=n instanceof Error?n.message||String(n):n;return this.track(e,Object.assign(Object.assign({},null!=r?r:{}),{errorMessage:s,errorName:t}))}operation(e,t,n,s){var o;const i=Date.now(),a=null!==(o=null==n?void 0:n.id)&&void 0!==o?o:(0,r.randomId)();try{const o=s({parentId:a});if((0,r.isPromise)(o))return o.then((t=>{const r=Date.now()-i;return this.track(e,Object.assign(Object.assign({},null!=n?n:{}),{duration:r,id:a})),t})).catch((r=>{const s=Date.now()-i;return this.error(e,t,r,Object.assign(Object.assign({},null!=n?n:{}),{duration:s,id:a})),Promise.reject(r)}));{const t=Date.now()-i;return this.track(e,Object.assign(Object.assign({},null!=n?n:{}),{duration:t,id:a})),o}}catch(r){const s=Date.now()-i;throw this.error(e,t,r,Object.assign(Object.assign({},null!=n?n:{}),{duration:s,id:a})),r}}trackAsParent(e,t){var n;const o=null!==(n=null==t?void 0:t.id)&&void 0!==n?n:(0,r.randomId)();return this.trackData(Object.assign(Object.assign({},t),{eventName:e,id:o})),new s(((e,t)=>this.trackData(Object.assign(Object.assign({},e),t))),{parentId:o})}track(e,t){return this.trackData(Object.assign(Object.assign({},t),{eventName:e}))}trackData(e){var t,n;const s=null!==(t=null==e?void 0:e.id)&&void 0!==t?t:(0,r.randomId)(),o=null!==(n=null==e?void 0:e.timestamp)&&void 0!==n?n:Date.now(),i=Object.assign({timestamp:o,id:s},null!=e?e:{});this.sendData(i,this.context)}}t.Tracker=s},66877:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},33905:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.newAbortController=void 0;const r=n(53811);t.newAbortController=function(){return"function"==typeof AbortController?new AbortController:new r.AbortController}},66960:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0,t.debounce=function(e,t,n=void 0,r=!1){let s,o=!0;function i(...a){let c;if(r){if(c=function(){o=!0,s=void 0},!o)return clearTimeout(s),void(s=setTimeout(c,t));o=!1,e.apply(n,a)}else i.reset(),c=function(){s=void 0,e.apply(n,a)};s=setTimeout(c,t)}return i.reset=function(){clearTimeout(s),s=void 0,o=!0},i.isPending=function(){return null!=s},i}},90828:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SelfUpdate=void 0;class n{constructor(e){this.inner=e}hashCode(){return this.inner.hashCode()+1}equals(e){if(!(e instanceof n))return!1;if(this===e)return!0;const t=e.inner,r=this.inner.equals(t);return r&&this.inner!==t&&(this.inner=t),r}}t.SelfUpdate=n},98696:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(5693),t),s(n(33800),t),s(n(86099),t),s(n(40256),t),s(n(85249),t),s(n(48427),t),s(n(66224),t),s(n(2982),t),s(n(13035),t),s(n(90828),t),s(n(52060),t),s(n(66960),t),s(n(33905),t),s(n(75905),t)},13035:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.minimalDisambiguousPaths=void 0,t.minimalDisambiguousPaths=function(e,t={}){const n=e.map((e=>{const t=function(e){return e.replace(/[^\\]/g,"").length>e.replace(/[^/]/g,"").length?"\\":"/"}(e),n=/^(\w:).*/.exec(e),r=null!=n?n[1]:"";return{depth:null,parts:e.split(t).reverse().filter((e=>""!==e&&e!==r)),rootPrefix:r,separator:t,hadLeadingSeparator:e.startsWith(t)||r.length>0&&e.startsWith(r)}})),r=null==t.maxDepth?Math.max(...n.map((e=>e.parts.length))):t.maxDepth,s=new Set(n),o=new Map;for(let e=1;e<=r;e++){o.clear();for(const t of s){const n=t.parts.slice(0,e).join(t.separator);o.has(n)||o.set(n,new Set),o.get(n).add(t)}for(const t of o.values())if(1===t.size){const n=Array.from(t)[0];n.depth=e,s.delete(n)}}return n.map((({depth:e,parts:n,rootPrefix:s,separator:o,hadLeadingSeparator:i})=>{var a;let c=n.slice(0,null==e?r:e).reverse();return 0===c.length?`${s}${o}`:((1===c.length&&""===c[0]||c.length>1&&""!==c[0])&&(c=c.length===n.length?i?[s,...c]:c:(null!==(a=t.alwaysShowLeadingSeparator)&&void 0!==a?a:i)?["",...c]:c),c.join(o))}))}},75905:(e,t)=>{var n;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"}(n=t.DiffType||(t.DiffType={}));const r=/^diff --git (.*) (.*)$/,s=/^rename from (.*)$/,o=/^rename to (.*)$/,i=/^copy from (.*)$/,a=/^copy to (.*)$/,c=/^new file mode (\d{6})$/,l=/^deleted file mode (\d{6})$/,u=/^old mode (\d{6})$/,d=/^new mode (\d{6})$/,h=/@@ -(\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)||[],C=[];let y=0;function b(){const e={hunks:[]};for(C.push(e),function(e){for(;y<t.length;){const n=t[y],s=r.exec(n);if(s){e.oldFileName=s[1],e.newFileName=s[2],y++;break}y++}}(e);y<t.length;){const n=t[y];if(/^old mode/.test(n))w(e);else if(/^new mode/.test(n))O(e);else if(/^deleted file mode/.test(n))S(e);else if(/^new file mode/.test(n))E(e);else if(/^copy /.test(n))R(e);else if(/^rename /.test(n))k(e);else{if(/^--- /.test(n)){M(e);break}if(/^diff --git/.test(n))break;y++}}!function(e){for(;y<t.length;){const n=t[y];if(r.test(n))break;/^@@/.test(n)?e.hunks.push(_()):y++}}(e)}function w(e){const r=u.exec(t[y]);f(null!==r,`invalid format '${t[y]}'`),e.oldMode=r[1],e.type=n.Modified,y++}function O(e){const r=d.exec(t[y]);f(null!==r,`invalid format '${t[y]}'`),e.newMode=r[1],e.type=n.Modified,y++}function S(e){const r=l.exec(t[y]);f(null!==r,`invalid format '${t[y]}'`),e.newMode=r[1],e.type=n.Removed,y++}function E(e){const r=c.exec(t[y]);f(null!==r,`invalid format '${t[y]}'`),e.newMode=r[1],e.type=n.Added,y++}function R(e){f(i.test(t[y]),`invalid format '${t[y]}'`),f(a.test(t[y+1]),`invalid format '${t[y+1]}'`),e.type=n.Copied,y+=2}function k(e){f(s.test(t[y]),`invalid format '${t[y]}'`),f(o.test(t[y+1]),`invalid format '${t[y+1]}'`),e.type=n.Renamed,y+=2}function M(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=n.Modified),y+=2}function _(){const e=t[y++].split(h),n={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===n.oldLines&&(n.oldStart+=1),0===n.newLines&&(n.newStart+=1);let r=0,s=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;n.lines.push(t[y]),n.linedelimiters.push(v[y]||"\n"),"+"===e?r++:"-"===e?s++:" "===e&&(r++,s++)}return r||1!==n.newLines||(n.newLines=0),s||1!==n.oldLines||(n.oldLines=0),n}for(;y<t.length;)b();return C}},85249:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deserializeFromString=t.deserialize=t.serializeToString=t.serialize=void 0;const n={__rpcType:"undefined"};function r(e){if(void 0===e)return n;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])=>[r(e),r(t)]))};if(e instanceof Set)return{__rpcType:"Set",data:Array.from(e.values()).map(r)};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=>r(e)));if("object"==typeof e){const t={__rpcType:"object"};for(const[n,s]of Object.entries(e))t[n]=r(s);return t}throw new Error(`cannot serialize argument ${e}`)}function s(e){if("object"!=typeof e||null==e)return e;if(Array.isArray(e))return e.map((e=>s(e)));const t=e;switch(t.__rpcType){case"undefined":return;case"Map":return new Map(t.data.map((([e,t])=>[s(e),s(t)])));case"Set":return new Set(t.data.map(s));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,n={};for(const[e,r]of Object.entries(t))"__rpcType"!==e&&(n[e]=s(r));return n}default:throw new Error(`cannot deserialize unknown type ${t}`)}}t.serialize=r,t.serializeToString=function(e){return JSON.stringify(r(e))},t.deserialize=s,t.deserializeFromString=function(e){return s(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 n;Object.defineProperty(t,"__esModule",{value:!0}),t.SucceedableRevset=t.CommandRunner=void 0,(n=t.CommandRunner||(t.CommandRunner={})).Graphite="gt",n.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,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),s(n(50209),t),s(n(85119),t),s(n(45852),t),s(n(74259),t),s(n(1018),t),s(n(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,n)=>{e.resolve=t,e.reject=n})),e},t.basename=function(e,t="/"){const n=e.lastIndexOf(t);return-1===n?e:e.slice(n+1)},t.findParentWithClassName=function(e,t){var n;let r=e;for(;r;){if(null===(n=r.classList)||void 0===n?void 0:n.contains(t))return r;r=r.parentElement}},t.mapObject=function(e,t){return Object.fromEntries(Object.entries(e).map(t))},t.generatorContains=function(e,t){const n="function"==typeof t?t:e=>e===t;for(const t of e)if(n(t))return!0;return!1},t.zip=function*(e,t){const n=e[Symbol.iterator](),r=t[Symbol.iterator]();for(;;){const e=n.next(),t=r.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)}},25999:(e,t,n)=>{n.r(t),n.d(t,{startServer:()=>X});var r=n(98696),s=n(57147),o=n.n(s),i=n(13685),a=n.n(i),c=n(71017),l=n.n(c),u=n(57310),d=n.n(u),h=n(95352),m=n.n(h),p=n(22037),g=n.n(p);function f(){try{return g().userInfo().username}catch(e){try{const{env:e}=process;return(0,r.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 C=e=>{};var y=n(73837),b=n.n(y);const w=console;var O=n(60492),S=n.n(O),E=n(80909),R=n.n(E),k=n(82361);class M extends k.EventEmitter{}class _{codeReviewSystem;runCommand;constructor(e,t){this.codeReviewSystem=e,this.runCommand=t}diffSummaries=new M;onChangeDiffSummaries(e){const t=t=>e({value:t}),n=t=>e({error:t});return this.diffSummaries.on("data",t),this.diffSummaries.on("error",n),{dispose:()=>{this.diffSummaries.off("data",t),this.diffSummaries.off("error",n)}}}async triggerDiffSummariesFetch(e){const t=await this.runCommand(["internal-only","prs"]),n=JSON.parse(t.stdout);this.diffSummaries.emit("data",n)}dispose(){this.diffSummaries.removeAllListeners()}getSummaryName(){return`github:${this.codeReviewSystem.hostname}/${this.codeReviewSystem.owner}/${this.codeReviewSystem.repo}`}runExternalCommand(e,t,n,r){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,n,s){if(null!=this.runningOperation)return this.queuedOperations.push({...e,tracker:n}),void t({id:e.id,kind:"queue",queue:this.queuedOperations.map((e=>e.id))});this.runningOperation=e;const o=(...n)=>{switch(n[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:n[1]});break;case"stderr":t({id:e.id,kind:"stderr",message:n[1]});break;case"exit":t({id:e.id,kind:"exit",exitCode:n[1],timestamp:Date.now()})}};try{const i=(0,r.newAbortController)();if(this.abortController=i,await n.operation(e.trackEventName,"RunOperationError",{extras:{args:e.args,runner:e.runner}},(t=>this.runCallback(e,s,o,i.signal))),this.runningOperation=void 0,this.queuedOperations.length>0){const e=this.queuedOperations.shift();null!=e&&this.runOrQueueOperation(e,t,e.tracker,s)}}catch(n){const r=n.toString();this.logger.log("error running operation: ",e.args[0],r),t({id:e.id,kind:"error",error:r}),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 M;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",(n=>{n===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 j(e){let t,n;const r=()=>{const t=e();return n=t.then((()=>n=void 0),(()=>n=void 0)),t},s=()=>(t=void 0,r());return()=>null==n?r():(()=>{if(null==t){if(null==n)throw new Error("pendingCall must not be null!");t=n.then(s,s)}return t})()}var I=n(51887);const N="0.1.4";class x{info;logger;IGNORE_COMMIT_MESSAGE_LINES_REGEX=/^((?:HG|SL):.*)/gm;mergeConflicts=void 0;uncommittedChanges=null;smartlogCommits=null;mergeConflictsEmitter=new M;uncommittedChangesEmitter=new M;smartlogCommitsChangesEmitter=new M;smartlogCommitsBeginFetchingEmitter=new M;uncommittedChangesBeginFetchingEmitter=new M;disposables=[()=>this.mergeConflictsEmitter.removeAllListeners(),()=>this.uncommittedChangesEmitter.removeAllListeners(),()=>this.smartlogCommitsChangesEmitter.removeAllListeners(),()=>this.smartlogCommitsBeginFetchingEmitter.removeAllListeners(),()=>this.uncommittedChangesBeginFetchingEmitter.removeAllListeners()];onDidDispose(e){this.disposables.push(e)}operationQueue;watchForChangesDisposer;pageFocusTracker=new T;codeReviewProvider;currentVisibleCommitRangeIndex=0;visibleCommitRanges=[r.DEFAULT_DAYS_OF_COMMITS_TO_LOAD,60,void 0];constructor(e,t){this.info=e,this.logger=t;const n=e.codeReviewSystem;"github"===n.type&&(this.codeReviewProvider=new _(n,this.runCommand.bind(this))),this.watchForChangesDisposer=function(e,t,n){if("success"!==e.type)return;const{repoRoot:r,dotdir:s}=e;if(null==r||null==s)return void t.error(`skipping chokidar subscription since ${r} is not a repository`);const o=I.watch(s,{cwd:s});o.on("ready",(()=>{n("everything")})),o.on("all",((e,t)=>{t.startsWith("rebase-merge")&&n("merge conflicts"),(t.startsWith("index")||t.startsWith("HEAD"))&&n("uncommitted changes"),(t.startsWith("refs/heads")||t.startsWith("refs/branch-metadata")||t.startsWith("HEAD"))&&n("branches")}));const i=l().relative(r,s),a=I.watch(r,{cwd:r,ignored:`${i}/**`});return a.on("all",(()=>{n("uncommitted changes")})),()=>{a.close().catch((()=>t.error(`failed to close chokidar worktree watcher for ${r}`))),o.close().catch((()=>t.error(`failed to close chokidar dotdir watcher for ${s}`)))}}(e,t,(e=>{"uncommitted changes"===e?(this.fetchUncommittedChanges(),this.checkForMergeConflicts()):"branches"===e?this.fetchSmartlogCommits():"merge conflicts"===e?this.checkForMergeConflicts():"everything"===e&&(this.fetchUncommittedChanges(),this.fetchSmartlogCommits(),this.checkForMergeConflicts())})),this.operationQueue=new D(this.logger,((e,t,n,s)=>{if(e.runner===r.CommandRunner.Graphite)return this.runOperation(e,n,t,s);if(e.runner===r.CommandRunner.CodeReviewProvider){const r=this.normalizeOperationArgs(t,e.args);return null==this.codeReviewProvider?.runExternalCommand?Promise.reject(Error("CodeReviewProvider does not support running external commands")):this.codeReviewProvider?.runExternalCommand(t,r,n,s)??Promise.resolve()}return Promise.resolve()}));const s=new Set,o=this.subscribeToSmartlogCommitsChanges((e=>{if(e.commits.value){const t=[],n=e.commits.value.filter((e=>e.pr)).map((e=>e.pr?.number));for(const e of n)s.has(e)||(t.push(e),s.add(e));t.length>0&&this.codeReviewProvider?.triggerDiffSummariesFetch(this.getAllDiffIds())}}));this.checkForMergeConflicts(),this.disposables.push((()=>o.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.watchForChangesDisposer?.()}onChangeConflictState(e){return this.mergeConflictsEmitter.on("change",e),this.mergeConflicts&&e(this.mergeConflicts),{dispose:()=>this.mergeConflictsEmitter.off("change",e)}}checkForMergeConflicts=(0,r.debounce)(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"),o().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 n=Date.now();let r;try{const e=await this.runCommand(["internal-only","status"]);r=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)}const s=await o().promises.readFile(l().join(this.info.dotdir,"rebase-merge","head-name")).then((e=>{const t=e.toString();return t.startsWith("refs/heads/")?t.slice(11).trimEnd():void 0}),(()=>{}));if(this.mergeConflicts=function(e,t,n,r){const s=n;if(!s?.conflicts||!t)return;const o=s.files.filter((e=>"UNRESOLVED"===e.status)),i={state:"loaded",branchName:t,files:[],fetchStartTimestamp:r,fetchCompletedTimestamp:Date.now()};if(null!=e?.files&&e.files.length>0){const t=new Set(o.map((e=>e.path)));i.files=e.files.map((e=>t.has(e.path)?{path:e.path,status:"UNRESOLVED"}:{path:e.path,status:"RESOLVED"}))}else i.files=o.map((e=>({path:e.path,status:"UNRESOLVED"})));return i}(this.mergeConflicts,s,r,n),this.logger.info(`repo ${this.mergeConflicts?"IS":"IS NOT"} in merge conflicts`,{mergeConflicts:this.mergeConflicts,files:this.mergeConflicts?.files}),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: ",{branchName:s,remainingConflicts:t})}this.mergeConflictsEmitter.emit("change",this.mergeConflicts)})),100);getMergeConflicts(){return this.mergeConflicts}static async getRepoInfo(e,t,n){const r=await async function(e,t,n){try{return(await F({command:e,args:["--version"],logger:t,cwd:n})).stdout}catch(e){throw t.error(`Failed to find gt version in ${n}`,e),e}}(e,t,n).catch((e=>e));if(r instanceof Error)return{type:"invalidCommand",command:e??"gt"};if("local"!==r&&"dev"!==r&&R().lt(r,N))return{type:"invalidVersion",command:e??"gt",versionFound:r,versionRequired:N};const[s,o,i,a]=await Promise.all([L(e,t,n),A(e,t,n),$(e,t,n,"graphite.branch_edit").then((e=>e??"amend")),$(e,t,n,"graphite.create_prs_as").then((e=>e??"draft"))]);if(null==o)return{type:"cwdNotARepository",cwd:n};let c;if(void 0===o.remote)c={type:"none"};else{const{owner:e,name:t,hostname:n}=o.remote;c={type:"github",owner:e,repo:t,hostname:n}}const l={type:"success",command:e,dotdir:o.dotDir,repoRoot:o.rootDir,codeReviewSystem:c,preferredBranchEdit:i,createPrsAs:a,profile:s,trunkBranch:o.trunkBranch};return t.info("repo info: ",l),l}async runOrQueueOperation(e,t,n,r){await this.operationQueue.runOrQueueOperation(e,t,n,r)}abortRunningOpeation(e){this.operationQueue.abortRunningOperation(e)}normalizeOperationArgs(e,t){const n=(0,r.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(n,t.path)));case"succeedable-revset":return`max(successors(${t.revset}))`}return t}))}async runOperation(e,t,n,r){const s=this.normalizeOperationArgs(n,e.args),{stdin:o}=e,{command:i,args:a,options:c}=U(this.info.command,s,n,o?{input:o}:void 0);this.logger.log("run operation: ",i,s.join(" "));const l=S()(i,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)})),r.addEventListener("abort",(()=>{this.logger.log("kill operation: ",i,s.join(" "))})),function(e,t){t.addEventListener("abort",(()=>{"win32"==g().platform()?e.kill("SIGKILL",{forceKillAfterTimeout:!1}):(e.kill("SIGCONT"),e.kill("SIGTERM",{forceKillAfterTimeout:5e3}))}))}(l,r),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=(0,r.debounce)(j((async()=>{const e=Date.now();try{this.uncommittedChangesBeginFetchingEmitter.emit("start");const t=await this.runCommand(["internal-only","status"]),n=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:n}},this.uncommittedChangesEmitter.emit("change",this.uncommittedChanges)}catch(n){if(this.logger.error("Error fetching files: ",n),null!=(t=n)&&"object"==typeof t&&"stderr"in t&&n.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:n instanceof Error?n:new Error(n)}})}var t})),100);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=(0,r.debounce)(j((async()=>{const e=Date.now();try{this.smartlogCommitsBeginFetchingEmitter.emit("start");const t=await this.runCommand(["internal-only","log"]),n=function(e,t){let n=[];try{n=JSON.parse(t)}catch(t){e.error("failed to parse branch info",t)}return n}(this.logger,t.stdout.trim());if(0===n.length)throw new Error(r.ErrorShortMessages.NoCommitsFetched);this.smartlogCommits={fetchStartTimestamp:e,fetchCompletedTimestamp:Date.now(),commits:{value:n}},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)}})}})),100);subscribeToHeadCommit(e){let t=this.smartlogCommits?.commits.value?.find((e=>e.isHead));null!=t&&e(t);const n=n=>{const r=n?.commits.value?.find((e=>e.isHead));null!=r&&r.branch!==t?.branch&&(e(r),t=r)};return this.smartlogCommitsChangesEmitter.on("change",n),{dispose:()=>{this.smartlogCommitsChangesEmitter.off("change",n)}}}catLimiter=new P(4,(e=>this.logger.info("[cat]",e)));cat(e,t){const n=l().relative(this.info.repoRoot,e);return this.catLimiter.enqueueRun((async()=>(await this.runCommand(["internal-only","relative-cat",...this.catArgs(t,n)],void 0,{stripFinalNewline:!1})).stdout))}catArgs(e,t){switch(e.type){case r.ComparisonType.UncommittedChanges:return["uncommitted",t];case r.ComparisonType.HeadChanges:return["head",t];case r.ComparisonType.StackChanges:return["stack",t];case r.ComparisonType.Committed:return["stack",t,"--ref",e.hash]}}getAllDiffIds(){return this.getSmartlogCommits()?.commits.value?.map((e=>e.pr?.number)).filter(r.notEmpty)??[]}runCommand(e,t,n){return F({command:this.info.command,args:e,logger:this.logger,cwd:(0,r.unwrap)(t??this.info.repoRoot),options:n})}getConfig(e){return $(this.info.command,this.logger,this.info.repoRoot,e)}setConfig(e,t,n){return async function({command:e,logger:t,cwd:n,level:r,configName:s,configValue:o}){await F({command:e,args:["internal-only","set-config","--level",r,s,o],logger:t,cwd:n})}({command:this.info.command,logger:this.logger,cwd:this.info.repoRoot,level:e,configName:t,configValue:n})}}function F({command:e,args:t,logger:n,cwd:r,options:s}){const{command:o,args:i,options:a}=U(e,t,r,s);return n&&n.log("run command: ",o,...i,a),S()(o,i,a)}async function A(e,t,n){try{return JSON.parse((await F({command:e,args:["internal-only","repo-info"],logger:t,cwd:n})).stdout)}catch(e){return void t.error(`Failed to find repository info in ${n}`,e)}}async function L(e,t,n){try{return JSON.parse((await F({command:e,args:["internal-only","profile"],logger:t,cwd:n})).stdout)}catch(e){return t.error(`Failed to find repository profile in ${n}`,e),{appUrl:"https://app.graphite.dev/"}}}async function $(e,t,n,r){try{return(await F({command:e,args:["internal-only","config",r],logger:t,cwd:n})).stdout.trim()}catch{return}}function U(e,t,n,r){let s=[...t];"win32"!==process.platform&&(s=s.map((e=>e.replace(/\\\\/g,"\\"))));const o={...r,env:{LANG:"en_US.utf-8",EDITOR:void 0,GRAPHITE_INTERACTIVE:"true",GIT_OPTIONAL_LOCKS:"0"},cwd:n};return!e&&process.argv[1].startsWith("/snapshot/")?(e=process.argv[0],s=["/snapshot/monologue/apps/public/cli/dist/graphite.js",...s]):e||(e="gt"),{command:e,args:s,options:o}}var q=n(32081);const H={platformName:"browser",handleMessageFromClient:(e,t)=>{switch(t.type){case"platform/openFile":{const n=l().join((0,r.unwrap)(e?.info.repoRoot),t.path);let s;if(null==s)switch(process.platform){case"darwin":s="/usr/bin/open";break;case"win32":s="notepad.exe";break;case"linux":s="xdg-open"}if(s){e?.logger.log("open file",n);const t=(0,q.spawn)(s,[n],{detached:!0,stdio:"ignore",windowsHide:!1,windowsVerbatimArguments:!0});t.on("error",(t=>{e?.logger.log("failed to open",n,t)})),t.unref()}break}}}};class B{promise;disposeFunc;constructor(e,t){this.promise=e,this.disposeFunc=t}unref(){this.disposed||(this.disposed=!0,this.disposeFunc())}internalReference;disposed=!1}class z{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 W=new class{RepositoryType;constructor(e=x){this.RepositoryType=e}reposByRoot=new Map;activeReposEmitter=new M;lookup(e){for(const n of this.reposByRoot.values())if((e===n.value.info.repoRoot||e.startsWith((t=n.value.info.repoRoot).endsWith(l().sep)?t:t+l().sep))&&!n.isDisposed)return n;var t}getOrCreate(e,t,n){const r=this.lookup(n);if(r)return r.ref(),new B(Promise.resolve(r.value),(()=>r.dispose()));let s;return s=new B((async()=>{const r=await this.RepositoryType.getRepoInfo(e,t,n);if("success"!==r.type)return r;if(s.disposed)return{type:"unknownError",error:new Error("Repository already disposed")};const o=this.lookup(r.repoRoot);if(o)return o.ref(),s.internalReference=o,o.value;const i=new this.RepositoryType(r,t),a=new z(i);return a.ref(),s.internalReference=a,this.reposByRoot.set(r.repoRoot,a),this.activeReposEmitter.emit("change"),i})(),(()=>{s.internalReference&&s.internalReference.dispose(),s.unref()})),s}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 V{platform;connection;tracker;logger;listenersByType=new Map;incomingListener;repoDisposables=[];subscriptions=new Map;activeRepoRef;queuedMessages=[];currentState={type:"loading"};pageId=(0,r.randomId)();constructor(e,t,n,s){this.platform=e,this.connection=t,this.tracker=n,this.logger=s;let o=null;this.incomingListener=this.connection.onDidReceiveMessage(((e,n)=>{if(n)return null==o?void t.logger?.error("Error: got a binary message when not expecting one"):(this.handleIncomingMessageWithPayload(o,e),void(o=null));if(null!=o)return t.logger?.error("Error: didnt get binary payload after a message that requires one"),void(o=null);const s=e.toString("utf-8"),i=(0,r.deserializeFromString)(s);if(function(e){return null!=e&&"object"==typeof e&&!0===e.hasBinaryPayload}(i))o=i;else if("loading"===this.currentState.type)this.queuedMessages.push(i);else try{this.handleIncomingMessage(i)}catch(e){t.logger?.error("error handling incoming message: ",i,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 n=e.getSmartlogCommits(),r=function(e,t){let n;if(null!=e){const r=new Map(e.map((e=>[e.branch,e])));let s=t;for(;null!=s;){if(s.partOfTrunk){n=s;break}if(null==s.parents[0])break;s=r.get(s.parents[0])}}return n}(n?.commits.value,t);this.tracker.track("HeadCommitChanged",{extras:{hash:t.branch,public:r?.branch}})}))),this.processQueuedMessages()}postMessage(e){this.connection.postMessage((0,r.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=W.getOrCreate(t,this.logger,e),this.activeRepoRef.promise.then((t=>{t instanceof x?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:n,filename:s}=e,o=null;if(null==o)return;this.tracker.operation("UploadImage","UploadImageError",{},(()=>o((0,r.unwrap)(this.connection.logger),{filename:s,data:t}))).then((e=>{this.connection.logger?.info("sucessfully uploaded file",s,e),this.postMessage({type:"uploadFileResult",id:n,result:{value:e}})})).catch((e=>{this.connection.logger?.info("error uploading file",s,e),this.postMessage({type:"uploadFileResult",id:n,result:{error:e}})}));break}}}handleIncomingMessage(e){this.handleIncomingGeneralMessage(e);const{currentState:t}=this;switch(t.type){case"repo":{const{repo:n,cwd:r}=t;this.handleIncomingMessageWithRepo(e,n,r);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,n){const{logger:s}=t;switch(e.type){case"subscribe":{const{subscriptionID:n,kind:r}=e;switch(r){case"uncommittedChanges":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"uncommittedChanges",subscriptionID:n,data:e})},r=t.getUncommittedChanges();null!=r&&e(r);const s=[];s.push(t.subscribeToUncommittedChanges(e)),t.fetchUncommittedChanges(),s.push(t.subscribeToUncommittedChangesBeginFetching((()=>this.postMessage({type:"beganFetchingUncommittedChangesEvent"})))),this.subscriptions.set(n,{dispose:()=>{s.forEach((e=>e.dispose()))}});break}case"smartlogCommits":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"smartlogCommits",subscriptionID:n,data:e})},r=t.getSmartlogCommits();null!=r&&e(r);const s=[];s.push(t.subscribeToSmartlogCommitsChanges(e)),t.fetchSmartlogCommits(),s.push(t.subscribeToSmartlogCommitsBeginFetching((()=>this.postMessage({type:"beganFetchingSmartlogCommitsEvent"})))),this.subscriptions.set(n,{dispose:()=>{s.forEach((e=>e.dispose()))}});break}case"mergeConflicts":{const e=e=>{this.postMessage({type:"subscriptionResult",kind:"mergeConflicts",subscriptionID:n,data:e})},r=t.getMergeConflicts();null!=r&&e(r),this.subscriptions.set(n,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:r}=e;t.runOrQueueOperation(r,(e=>{this.postMessage({type:"operationProgress",...e}),"queue"===e.kind&&this.tracker.track("QueueOperation",{extras:{operation:r.trackEventName}})}),this.tracker,n);break}case"abortRunningOperation":{const{operationId:n}=e;t.abortRunningOpeation(n);break}case"getConfig":t.getConfig(e.name).catch((()=>{})).then((t=>{s.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=>(s?.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=>(s?.error("error fetching upgrade prompt",e.toString()),{error:e}))).then((e=>this.postMessage({type:"fetchedUpgradePrompt",message:e.value||""})));break;case"setConfig":s.info("set config",e.name,e.value),t.setConfig("user",e.name,e.value).catch((t=>{s.error("error setting config",e.name,e.value,t)}));break;case"deleteFile":{const{filePath:n}=e,r=function(e,t,n=l()){const r=n.resolve(t.info.repoRoot,e);return r.startsWith(t.info.repoRoot+n.sep)?r:null}(n,t);if(null==r)return void s.warn("can't delete file outside of the repo",n);o().promises.rm(r).then((()=>{s.info("deleted file from filesystem",r)})).catch((e=>{s.error("unable to delete file",r,e)}));break}case"requestComparison":{const{comparison:n}=e;t.runCommand(["internal-only","diff",...(0,r.revsetArgsForComparison)(n)]).then((e=>({value:e.stdout}))).catch((e=>(s?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"comparison",comparison:n,data:{diff:e}})));break}case"requestChangedFiles":{const{branch:n}=e;t.runCommand(["internal-only","changed-files",n]).then((e=>JSON.parse(e.stdout))).catch((e=>(s?.error("error running diff",e.toString()),{error:e}))).then((e=>this.postMessage({type:"changedFiles",branch:n,data:e})));break}case"requestComparisonContextLines":{const{id:{path:n,comparison:r},start:s,numLines:o}=e;t.cat(n,r).catch((()=>"")).then((e=>this.postMessage({type:"comparisonContextLines",lines:e.split("\n").slice(s-1,s-1+o),path:n})));break}case"refresh":s?.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 n=JSON.parse(e.stdout);this.postMessage({type:"fetchedCommitMessageTemplate",templates:Object.fromEntries(Object.entries(n).map((([e,n])=>[e,n.replace(t.IGNORE_COMMIT_MESSAGE_LINES_REGEX,"")])))})})).catch((e=>{s?.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 G=n(6113);const J="win32"==process.platform?l().join((0,r.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 Q(e,t){const n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&(0,G.timingSafeEqual)(n,r)}function K(e){const t=e.logger??(e.logFileLocation?function(e){const t=(...t)=>{const n=b().format(...t)+"\n";o().promises.appendFile(e,n)};return{info:t,log:t,warn:t,error:t,getLogFileContents:()=>o().promises.readFile(e,"utf-8")}}(e.logFileLocation):w);e.logger=t;const n=e?.platform??H,s=e?.version??"unknown";t.log(`establish client connection for ${e.cwd}`),t.log(`platform '${n.platformName}', version '${s}', command '${e.command}'`);const i=function(e,t,n,s=C){return new r.Tracker(((e,t)=>{const{logger:n}=t;n.log("[track]",e.eventName,e.errorName??"",e.errorMessage??"",null!=e.extras?JSON.stringify(e.extras):"");try{Promise.resolve(s({...e,...t.data})).catch((e=>{}))}catch{}}),new v(e,function(e,t){return{platform:e,version:t,repo:void 0,sessionId:(0,r.randomId)(),unixname:f(),osArch:g().arch(),osType:g().platform(),osRelease:g().release(),hostname:g().hostname()}}(t.platformName,n)))}(t,n,s,(t=>F({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})));i.track("ClientConnection",{extras:{cwd:e.cwd}});let a=new V(n,e,i,t);return a.setActiveRepoForCwd(e.cwd),()=>{a?.dispose(),a=null}}function X({port:e,sensitiveToken:t,challengeToken:n,logFileLocation:s,logInfo:i,command:c,gtVersion:u,foreground:h,frontendDir:p}){return new Promise((g=>{try{const e=JSON.parse(o().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}\``}),ee[t]=t.slice(1)}catch(e){}ee["/favicon.ico"]="favicon.ico";const f=a().createServer((async(e,r)=>{if(e.url){const{pathname:i}=d().parse(e.url);if(null!=i&&ee.hasOwnProperty(i)){const e=ee[i];let t;try{t=await o().promises.readFile(l().join(p,"build",e))}catch(e){return r.writeHead(500,{"Content-Type":"text/plain"}),void r.end((s=e.toString(),s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"")))}const n=e.lastIndexOf("."),a=e.slice(n+1),c=Z[a]??"text/plain";return r.writeHead(200,{"Content-Type":c}),void r.end(t)}if("/challenge_authenticity"===i){const s=Y(e.url).get("token");if(s&&Q(s,t)){r.writeHead(200,{"Content-Type":"text/json"});const e={challengeToken:n,pid:process.pid};r.end(JSON.stringify(e))}else r.writeHead(401,{"Content-Type":"text/json"}),r.end(JSON.stringify({error:"invalid token"}));return}}var s;r.writeHead(404,{"Content-Type":"text/html"}),r.end("<html><body>Not Found!</body></html>")})),v=f.listen(e),C=new(m().Server)({noServer:!0,path:"/ws"});C.on("connection",((e,n)=>{let o,a,l;if(n.url){const e=Y(n.url);o=e.get("token");const t=e.get("cwd");l=e.get("platform"),t&&(a=decodeURIComponent(t))}if(!o){const t="No token provided in websocket request";return i("closing ws:",t),void e.close(r.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE,t)}if(!Q(o,t)){const t="Invalid token";return i("closing ws:",t),void e.close(r.CLOSED_AND_SHOULD_NOT_RECONNECT_CODE,t)}const d=K({postMessage:t=>(e.send(t),Promise.resolve(!0)),onDidReceiveMessage(t){const n=e.on("message",t);return{dispose:()=>n.off("message",t)}},cwd:a??process.cwd(),logFileLocation:"stdout"===s?void 0:s,command:c,version:u,platform:void 0});e.on("close",(()=>{d(),h||setTimeout((()=>{0===W.numberOfActiveServers()&&process.exit(0)}),6e4)}))})),v.on("upgrade",((e,t,n)=>{C.handleUpgrade(e,t,n,(t=>{C.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 Y(e){const t=d().parse(e).search?.replace(/^\?/,"").split("&").map((e=>e.split("=")));return new Map(t)}l().join(J,"graphite-gti");const Z={css:"text/css",html:"text/html",js:"text/javascript",ttf:"font/ttf"},ee={"/":"index.html"}}};
|
|
3
3
|
//# sourceMappingURL=999.js.map
|