monacopilot 0.9.0 → 0.9.1

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/build/index.d.mts CHANGED
@@ -63,8 +63,8 @@ interface CompletionMetadata {
63
63
  filename: Filename | undefined;
64
64
  technologies: Technologies | undefined;
65
65
  externalContext: ExternalContext | undefined;
66
- codeAfterCursor: string;
67
- codeBeforeCursor: string;
66
+ textAfterCursor: string;
67
+ textBeforeCursor: string;
68
68
  editorState: {
69
69
  completionMode: CompletionMode;
70
70
  };
@@ -75,7 +75,7 @@ interface CopilotOptions {
75
75
  }
76
76
 
77
77
  /**
78
- * Copilot class for handling code completions using the Groq API.
78
+ * Copilot class for handling completions using the Groq API.
79
79
  */
80
80
  declare class Copilot {
81
81
  private readonly apiKey;
@@ -89,7 +89,7 @@ declare class Copilot {
89
89
  /**
90
90
  * Sends a completion request to Groq API and returns the completion.
91
91
  * @param {CompletionRequest} params - The metadata required to generate the completion.
92
- * @returns {Promise<CompletionResponse>} The completed code snippet or an error.
92
+ * @returns {Promise<CompletionResponse>} The completed text snippet or an error.
93
93
  */
94
94
  complete({ completionMetadata, }: CompletionRequest): Promise<CompletionResponse>;
95
95
  private createRequestBody;
package/build/index.d.ts CHANGED
@@ -63,8 +63,8 @@ interface CompletionMetadata {
63
63
  filename: Filename | undefined;
64
64
  technologies: Technologies | undefined;
65
65
  externalContext: ExternalContext | undefined;
66
- codeAfterCursor: string;
67
- codeBeforeCursor: string;
66
+ textAfterCursor: string;
67
+ textBeforeCursor: string;
68
68
  editorState: {
69
69
  completionMode: CompletionMode;
70
70
  };
@@ -75,7 +75,7 @@ interface CopilotOptions {
75
75
  }
76
76
 
77
77
  /**
78
- * Copilot class for handling code completions using the Groq API.
78
+ * Copilot class for handling completions using the Groq API.
79
79
  */
80
80
  declare class Copilot {
81
81
  private readonly apiKey;
@@ -89,7 +89,7 @@ declare class Copilot {
89
89
  /**
90
90
  * Sends a completion request to Groq API and returns the completion.
91
91
  * @param {CompletionRequest} params - The metadata required to generate the completion.
92
- * @returns {Promise<CompletionResponse>} The completed code snippet or an error.
92
+ * @returns {Promise<CompletionResponse>} The completed text snippet or an error.
93
93
  */
94
94
  complete({ completionMetadata, }: CompletionRequest): Promise<CompletionResponse>;
95
95
  private createRequestBody;
package/build/index.js CHANGED
@@ -1,16 +1,15 @@
1
- "use strict";var Pe=Object.create;var M=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var Le=Object.getPrototypeOf,be=Object.prototype.hasOwnProperty;var Oe=(e,t)=>{for(var o in t)M(e,o,{get:t[o],enumerable:!0})},j=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Me(t))!be.call(e,n)&&n!==o&&M(e,n,{get:()=>t[n],enumerable:!(r=Re(t,n))||r.enumerable});return e};var xe=(e,t,o)=>(o=e!=null?Pe(Le(e)):{},j(t||!e||!e.__esModule?M(o,"default",{value:e,enumerable:!0}):o,e)),Ie=e=>j(M({},"__esModule",{value:!0}),e);var ke={};Oe(ke,{Copilot:()=>I,DiffEditor:()=>f.DiffEditor,default:()=>Te,loader:()=>f.loader,useMonaco:()=>f.useMonaco});module.exports=Ie(ke);var G={scrollBeyondLastColumn:0,codeLens:!1,minimap:{enabled:!1},quickSuggestions:!1,folding:!1,foldingHighlight:!1,foldingImportsByDefault:!1,links:!1,fontSize:14,wordWrap:"on",automaticLayout:!0};var H={llama:"llama3-70b-8192"},L="llama",U="https://api.groq.com/openai/v1/chat/completions";var W={javascript:1,typescript:2,typescriptreact:3,python:4,vue:5,php:6,dart:7,javascriptreact:8,go:9,css:10,cpp:11,html:12,scss:13,markdown:14,csharp:15,java:16,json:17,rust:18,ruby:19,c:20},v={" ":1,"!":2,'"':3,"#":4,$:5,"%":6,"&":7,"'":8,"(":9,")":10,"*":11,"+":12,",":13,"-":14,".":15,"/":16,0:17,1:18,2:19,3:20,4:21,5:22,6:23,7:24,8:25,9:26,":":27,";":28,"<":29,"=":30,">":31,"?":32,"@":33,A:34,B:35,C:36,D:37,E:38,F:39,G:40,H:41,I:42,J:43,K:44,L:45,M:46,N:47,O:48,P:49,Q:50,R:51,S:52,T:53,U:54,V:55,W:56,X:57,Y:58,Z:59,"[":60,"\\":61,"]":62,"^":63,_:64,"`":65,a:66,b:67,c:68,d:69,e:70,f:71,g:72,h:73,i:74,j:75,k:76,l:77,m:78,n:79,o:80,p:81,q:82,r:83,s:84,t:85,u:86,v:87,w:88,x:89,y:90,z:91,"{":92,"|":93,"}":94,"~":95},d=[.9978708359643611,.7001905605239328,-.1736749244124868,-.22994157947320112,.13406692641682572,-.007751370662011853,.0057783222035240715,.41910878254476003,-.1621657125711092,.13770814958908187,-.06036011308184006,-.07351180985800129,0,-.05584878151248109,.30618794079412015,-.1282197982598485,.10951859303997555,.1700461782788777,-.3346057842644757,.22497985923128136,0,-.44038101825774356,-.6540115939236782,.16595600081341702,.20733910722385135,-.1337033766105696,-.06923072125290894,-.05806684191976292,.3583334671633344,-.47357732824944315,.17810871365594377,.42268219963946685,0,0,-.16379620467004602,-.43893868831061167,0,.11570094006709251,.9326431262654882,-.9990110509203912,-.44125275652726503,-.15840786997162004,-.4600396256644451,-.018814811994044403,.09230944537175266,.025814790934742798,-1.0940162204190154,-.9407503631235489,-.9854303778694269,-1.1045822488262245,-1.1417299456573262,-1.5623704405345513,-.4157473855795939,-1.0244257735561713,-.7477401944601753,-1.1275109699068402,-.0714715633552533,-1.1408628006786907,-1.0409898655074672,-.2288889836518878,-.5469549893760344,-.181946611106845,.1264329316374918,0,0,.312206968554707,-.3656436392517924,.23655650686038968,.1014912419901576,0,.06287549221765308,0,0,.19027065218932154,-.8519502045974378,0,.23753599905971923,.2488809322489166,.019969251907983224,0,.06916505526229488,.29053356359188204,-.14484456555431657,.014768129429370188,-.15051464926341374,.07614835502776021,-.3317489901313935,0,0,.04921938684669103,-.28248576768353445,-.9708816204525345,-1.3560464522265527,.014165375212383239,-.23924166472544983,.10006595730248855,.09867233147279562,.32330430333220644,-.058625706114180595,.17149853105783947,.4436484054395367,.047189049576707255,.16832520944790552,.1117259900942179,-.35469010329927253,0,-.1528189124465582,-.3804848349564939,.07278077320753953,.13263786480064088,.22920682659292527,1.1512955314336537,0,.016939862282340023,.4242994650403408,.12759835577444986,-.5577261135825583,-.19764560943067672,-.4042102444736004,.12063461617733708,-.2933966817484834,.2715683893968593,0,-.7138548251238751,0,-.023066228703035277,0,-.06383043976746139,.09683723720709651,-.7337151424080791,0,-.27191370124625525,.2819781269656171,-.08711496549050252,.11048604909969338,-.0934849550450534,.0721001250772912,.2589126797890794,.6729582659532254,-.21921032738244908,-.21535277468651456,-.45474006124091354,-.05861820126419139,-.007875306207720204,-.056661261678809284,.17727881404222662,.23603713348534658,.17485861412377932,-.5737483768696752,-.38220029570342745,-.5202722985519168,-.37187947527657256,.47155277792990113,-.12077912346691123,.47825628981545326,.4736704404000214,-.1615218651546898,.18362447973513005,0,0,-.18183417425866824,0,0,-.2538532305733833,-.1303692690676528,-.4073577969188216,.04172985870928789,-.1704527388573901,0,0,.7536858953385828,-.44703159588787644,0,-.7246484085580873,-.21378128540782063,0,.037461090552656146,-.16205852364367032,-.10973952064404884,.017468043407647377,-.1288980387397392,0,0,0,-1.218692715379445,.05536949662193305,-.3763799844799116,-.1845001725624579,-.1615576298149558,0,-.15373262203249874,-.04603412604270418,0,-.3068149681460828,.09412352468269412,0,.09116543650609721,.06065865264082559,.05688267379386188,-.05873945477722306,0,.14532465133322153,.1870857769705463,.36304258043185555,.1411392422180405,.0630388629716367,0,-1.1170522012450395,.16133697772771127,.15908534390781448,-.23485453704002232,-.1419980841417892,.21909510179526218,.39948420260153766,.40802294284289187,.15403767653746853,0,.19764784115096676,.584914157527457,0,-.4573883817015294],V=-.3043572714994554,K=.15;var Y=(e,t=1e3)=>{let o=null;return(...n)=>(o&&clearTimeout(o),new Promise((i,s)=>{o=setTimeout(()=>{e(...n).then(i).catch(s)},t)}))},S=(e,t)=>{let o={...t};for(let r in e)typeof e[r]=="object"&&!Array.isArray(e[r])?t[r]&&typeof t[r]=="object"&&!Array.isArray(t[r])?o[r]=S(e[r],t[r]):o[r]={...e[r]}:o[r]=e[r];return o},z=e=>!e||e.length===0?"":e.length===1?e[0]:`${e.slice(0,-1).join(", ")} and ${e.slice(-1)}`,N=e=>e.split("").reverse().join("");var J=(e,t)=>e[t]||"",$=e=>e.split(`
2
- `)[e.split(`
3
- `).length-1].length;var X=(e,t)=>e.split(`
4
- `)[t-1];var Q=async(e,t,o={})=>{let r={"Content-Type":"application/json",...o.headers},n=t==="POST"&&o.body?JSON.stringify(o.body):void 0,i=await fetch(e,{method:t,headers:r,body:n,signal:o.signal});if(!i.ok)throw new Error(`${o.error||"Network error"}: ${i.statusText}`);return i.json()},Ae=(e,t)=>Q(e,"GET",t),we=(e,t,o)=>Q(e,"POST",{...o,body:t}),b={GET:Ae,POST:we};var E="<<CURSOR>>",Z=e=>e==="javascript"?"latest JavaScript":e,ee=e=>{switch(e){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code";default:return"completing the code"}},te=e=>{let t=Z(e.language),o=ee(e.editorState.completionMode);return`You are an expert ${t||""} code completion assistant known for exceptional skill in ${o}.`},_e=(e,t)=>{if(!e?.length&&!t)return"";let o=z(e),r=Z(t);return`The code is written${r?` in ${r}`:""}${o?` using ${o}`:""}.`},oe=e=>{let{filename:t,language:o,technologies:r,editorState:n,codeBeforeCursor:i,codeAfterCursor:s,externalContext:c}=e,l=ee(n.completionMode),p=t?`the file named ${t}`:"a larger project",a=`You will be presented with a code snippet in '<code>' tag where the cursor location is marked with '${E}'. Your task is to assist with ${l}. This code is part of ${p}. Please `;switch(n.completionMode){case"fill-in-the-middle":a+=`generate a completion to fill the middle of the code around '${E}'. Ensure the completion replaces '${E}' precisely, maintaining consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break;case"completion":a+=`provide the necessary completion for '${E}' while ensuring consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break}a+=` Output only the necessary completion code, without additional explanations or content.${_e(r,o)}`;let h=`${i}${E}${s}
1
+ "use strict";var ue=Object.create;var x=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var ge=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var Ee=(t,e)=>{for(var o in e)x(t,o,{get:e[o],enumerable:!0})},q=(t,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ge(e))!he.call(t,n)&&n!==o&&x(t,n,{get:()=>e[n],enumerable:!(r=fe(e,n))||r.enumerable});return t};var Te=(t,e,o)=>(o=t!=null?ue(Ce(t)):{},q(e||!t||!t.__esModule?x(o,"default",{value:t,enumerable:!0}):o,t)),Pe=t=>q(x({},"__esModule",{value:!0}),t);var Se={};Ee(Se,{Copilot:()=>b,DiffEditor:()=>g.DiffEditor,default:()=>de,loader:()=>g.loader,useMonaco:()=>g.useMonaco});module.exports=Pe(Se);var F=(t,e=1e3)=>{let o=null;return(...n)=>(o&&clearTimeout(o),new Promise((i,s)=>{o=setTimeout(()=>{t(...n).then(i).catch(s)},e)}))},w=(t,e)=>{let o={...e};for(let r in t)typeof t[r]=="object"&&!Array.isArray(t[r])?e[r]&&typeof e[r]=="object"&&!Array.isArray(e[r])?o[r]=w(t[r],e[r]):o[r]={...t[r]}:o[r]=t[r];return o},U=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`,A=t=>t.split("").reverse().join("");var y=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],j=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),f=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),G=t=>{let e=t.split(`
2
+ `);return e[e.length-1].length};var h=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),S=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var W=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},n=e==="POST"&&o.body?JSON.stringify(o.body):void 0,i=await fetch(t,{method:e,headers:r,body:n,signal:o.signal});if(!i.ok)throw new Error(`${o.error||"Network error"}: ${i.statusText}`);return i.json()},xe=(t,e)=>W(t,"GET",e),ye=(t,e,o)=>W(t,"POST",{...o,body:e}),M={GET:xe,POST:ye};var R=class{constructor(e,o){this.formattedCompletion="";this.originalCompletion="";this.model=e,this.cursorPosition=o,this.lineCount=e.getLineCount()}ignoreBlankLines(){return this.formattedCompletion.trimStart()===""&&this.originalCompletion!==`
3
+ `&&(this.formattedCompletion=this.formattedCompletion.trim()),this}normalise(e){return e?.trim()??""}removeDuplicatesFromStartOfCompletion(){let e=h(this.cursorPosition,this.model).trim(),o=this.normalise(this.formattedCompletion),r=0,n=Math.min(o.length,e.length);for(let i=1;i<=n;i++){let s=e.slice(-i),l=o.slice(0,i);if(s===l)r=i;else break}return r>0&&(this.formattedCompletion=this.formattedCompletion.slice(r)),this}preventDuplicateLines(){for(let e=this.cursorPosition.lineNumber+1;e<this.cursorPosition.lineNumber+3&&e<this.lineCount;e++){let o=this.model.getLineContent(e);if(this.normalise(o)===this.normalise(this.originalCompletion))return this.formattedCompletion="",this}return this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}trimStart(){let e=this.formattedCompletion.search(/\S/);return e>this.cursorPosition.column-1&&(this.formattedCompletion=this.formattedCompletion.slice(e)),this}format(e){return this.originalCompletion=e,this.formattedCompletion=e,this.ignoreBlankLines().removeDuplicatesFromStartOfCompletion().preventDuplicateLines().removeInvalidLineBreaks().trimStart(),this.formattedCompletion}};var Me=25,E=[],H=(t,e)=>E.filter(o=>{let r=e.getValueInRange(o.range);return f(t,e)===o.textBeforeCursorInLine&&o.range.startLineNumber===t.lineNumber&&t.column===o.range.startColumn||o.completion.startsWith(r)&&o.range.startLineNumber===t.lineNumber&&t.column>=o.range.startColumn-r.length&&t.column<=o.range.endColumn}),K=t=>{E.length>=Me&&E.shift(),E.push(t)},V=()=>{E.length=0};var Y={scrollBeyondLastColumn:0,codeLens:!1,minimap:{enabled:!1},quickSuggestions:!1,folding:!1,foldingHighlight:!1,foldingImportsByDefault:!1,links:!1,fontSize:14,wordWrap:"on",automaticLayout:!0,formatOnPaste:!0,inlineSuggest:{enabled:!0,mode:void 0}};var z={llama:"llama3-70b-8192"},O="llama",J="https://api.groq.com/openai/v1/chat/completions";var Q=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var X=(t,e)=>{let o=y(t,e);return!!o&&!Q.has(o)},Z=(t,e)=>{let o=j(t,e).trim(),r=f(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var ee=(t,e,o,r)=>{let n=(t.match(/\n/g)||[]).length,i=G(t),s=y(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+n,endColumn:t.includes(s)?o.lineNumber===e.startLineNumber&&n===0?o.column+i:i:o.column}},te=(t,e,o)=>new R(t,e).format(o),u=t=>({items:t,enableForwardStability:!0});var L=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!X(this.cursorPosition,this.model)&&!Z(this.cursorPosition,this.model)}};var I=class{static getModel(){return this.model}static setModel(e){this.model=e}};I.model=O;var $=I;var B=class{constructor(e){this.error=e}logError(e,o,r){console.error(`${e}: ${o}`,r)}monacopilotError(e){this.logError("MONACO_PILOT_ERROR",e,this.error)}apiError(e){this.logError("API_ERROR",e,this.error)}completionError(e){this.logError("COMPLETION_ERROR",e,this.error)}predictionError(e){this.logError("PREDICTION_ERROR",e,this.error)}editorError(e){this.logError("EDITOR_ERROR",e,this.error)}unexpectedError(){this.error instanceof Error?this.logError("UNEXPECTED_ERROR",this.error.message,this.error.stack):this.logError("UNKNOWN_ERROR",String(this.error))}},a=t=>new B(t);var T="<<CURSOR>>",oe=t=>t==="javascript"?"latest JavaScript":t,re=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code";default:return"completing the code"}},ne=t=>{let e=oe(t.language),o=re(t.editorState.completionMode);return`You are an expert ${e||""} code completion assistant known for exceptional skill in ${o}.`},Re=(t,e)=>{if(!t?.length&&!e)return"";let o=U(t),r=oe(e);return`The code is written${r?` in ${r}`:""}${o?` using ${o}`:""}.`},ie=t=>{let{filename:e,language:o,technologies:r,editorState:n,textBeforeCursor:i,textAfterCursor:s,externalContext:l}=t,c=re(n.completionMode),p=e?`the file named ${e}`:"a larger project",m=`You will be presented with a code snippet in '<code>' tag where the cursor location is marked with '${T}'. Your task is to assist with ${c}. This code is part of ${p}. Please `;switch(n.completionMode){case"fill-in-the-middle":m+=`generate a completion to fill the middle of the code around '${T}'. Ensure the completion replaces '${T}' precisely, maintaining consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break;case"completion":m+=`provide the necessary completion for '${T}' while ensuring consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break}m+=` Output only the necessary completion code, without additional explanations or content.${Re(r,o)}`;let C=`${i}${T}${s}
5
4
 
6
- `;return c&&c.length>0&&(h+=c.map(m=>`// Path: ${m.path}
7
- ${m.content}
5
+ `;return l&&l.length>0&&(C+=l.map(d=>`// Path: ${d.path}
6
+ ${d.content}
8
7
  `).join(`
9
- `)),a+=`
8
+ `)),m+=`
10
9
 
11
10
  <code>
12
- ${h}
13
- </code>`,a.endsWith(".")?a:`${a}.`};var ve=2e3,Se=new Set(['"',"'","}","]",")",","," ",":","."]),re=(e,t)=>{let r=t.getLineContent(e.lineNumber).substring(e.column-1);return/^\s*$/.test(r)},ne=(e,t)=>{let o=t.getLineContent(e.lineNumber),r=J(o,e.column-1);return!Se.has(r)&&!!r},T=(e,t)=>{let o=t.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:e.lineNumber,endColumn:e.column}),r=t.getValueInRange({startLineNumber:e.lineNumber,startColumn:e.column,endLineNumber:t.getLineCount(),endColumn:t.getLineMaxColumn(t.getLineCount())});return{codeBeforeCursor:o,codeAfterCursor:r}},ie=(e,t)=>{let o=t.getLineContent(e.lineNumber),r=o.slice(e.column-1).trim(),n=o.slice(0,e.column-1).trim();return e.column<=3&&(r!==""||n!=="")},se=(e,t)=>{let o=t.getLineContent(e.lineNumber),[r,n]=[o.slice(0,e.column-1).trim(),o.slice(e.column-1).trim()];return r&&n?"fill-in-the-middle":"completion"},ce=(e,t,o=ve)=>t-e<o;var Ne="application/json",ae="Error while fetching completion item",le=async({filename:e,endpoint:t,language:o,technologies:r,externalContext:n,model:i,position:s,token:c})=>{let l=new AbortController;if(c.isCancellationRequested)return l.abort(),null;try{let{completion:p}=await b.POST(t,{completionMetadata:$e({filename:e,position:s,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":Ne},error:ae,signal:l.signal});return p||null}catch(p){return console.error(ae,p),null}},$e=({filename:e,position:t,model:o,language:r,technologies:n,externalContext:i})=>{let s=se(t,o),{codeBeforeCursor:c,codeAfterCursor:l}=T(t,o);return{filename:e,language:r,technologies:n,externalContext:i,codeBeforeCursor:c,codeAfterCursor:l,editorState:{completionMode:s}}},pe=(e,t)=>{let{codeBeforeCursor:o}=T(e,t);return`${e.lineNumber}:${e.column}:${o}`};var D=class{constructor(){this.previousLabel=0,this.previousLabelTimestamp=Date.now()-3600*1e3,this.probabilityAccept=0}},me=e=>{let t=new D,o=t.previousLabel,r=0;e.properties.afterCursorWhitespace==="true"&&(r=1);let n=(Date.now()-t.previousLabelTimestamp)/1e3,i=Math.log(1+n),s=0,c=0,l=0,p=0;if(e.prefix){s=Math.log(1+$(e.prefix));let _=e.prefix.slice(-1);c=v[_]??0}let a=e.prefix?.trimEnd();if(a){l=Math.log(1+$(a));let _=a.slice(-1);p=v[_]??0}let h=e.measurements.documentLength?Math.log(1+e.measurements.documentLength):0,m=e.measurements.promptEndPos?Math.log(1+e.measurements.promptEndPos):0,R=e.measurements.promptEndPos&&e.measurements.documentLength?(e.measurements.promptEndPos+.5)/(1+e.measurements.documentLength):0,ye=e.properties.languageId?W[e.properties.languageId]:0,g=V;g+=d[0]*o+d[1]*r+d[2]*i,g+=d[3]*s+d[4]*l,g+=d[5]*h+d[6]*m,g+=d[7]*R,g+=d[8+ye],g+=d[29+c],g+=d[125+p];let k=1/(1+Math.exp(-g));return t.probabilityAccept=k,k};var O=class{constructor(t,o,r,n){this.cursorPosition=t,this.model=o,this.language=r,this.lastCompletionTime=n}calculateContextualScore(t,o,r){let{codeBeforeCursor:n}=T(t,o),i=re(t,o),s=o.getValueLength(),c=o.getOffsetAt(t);return me({properties:{afterCursorWhitespace:String(i),languageId:r},measurements:{documentLength:s,promptEndPos:c},prefix:n})}shouldProvideCompletions(){let t=Date.now();return this.calculateContextualScore(this.cursorPosition,this.model,this.language)>K&&!ne(this.cursorPosition,this.model)&&!ie(this.cursorPosition,this.model)&&!ce(this.lastCompletionTime,t)}};var x=class{static getModel(){return this.model}static setModel(t){this.model=t}};x.model=L;var F=x;var B=class{constructor(t){this.error=t}logError(t,o,r){console.error(`${t}: ${o}`,r)}monacopilotError(t){this.logError("MONACO_PILOT_ERROR",t,this.error)}apiError(t){this.logError("API_ERROR",t,this.error)}completionError(t){this.logError("COMPLETION_ERROR",t,this.error)}predictionError(t){this.logError("PREDICTION_ERROR",t,this.error)}editorError(t){this.logError("EDITOR_ERROR",t,this.error)}unexpectedError(){this.error instanceof Error?this.logError("UNEXPECTED_ERROR",this.error.message,this.error.stack):this.logError("UNKNOWN_ERROR",String(this.error))}},u=e=>new B(e);var q=class extends Error{constructor(o,r,n){super(r);this.code=o;this.details=n;this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}},y=class extends q{constructor(t,o){super("COMPLETION_ERROR",t,o)}};var I=class{constructor(t,o){if(!t)throw new Error("Groq API key is required to initialize Copilot.");this.apiKey=t,F.setModel(o?.model||L)}async complete({completionMetadata:t}){try{let o=F.getModel(),r=this.createRequestBody(t,o),n=this.createHeaders(),i=await b.POST(U,r,{headers:n});if(!i.choices||i.choices.length===0)throw new y("No completion choices received from API");return{completion:i.choices[0].message.content}}catch(o){return o instanceof y?u(o).completionError("Failed to fetch completion"):o instanceof Error?u(o).apiError("Failed to fetch completion"):u(o).apiError("Unknown error during completion"),{error:"Failed to generate completion"}}}createRequestBody(t,o){return{model:H[o],messages:[{role:"system",content:te(t)},{role:"user",content:oe(t)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var de={conso:"le.log($1)","new P":`romise((resolve, reject) => {
11
+ ${C}
12
+ </code>`,m.endsWith(".")?m:`${m}.`};var Oe="application/json",se=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:n,model:i,position:s,token:l})=>{let c=new AbortController;if(l.isCancellationRequested)return c.abort(),null;try{let{completion:p}=await M.POST(e,{completionMetadata:Le({filename:t,position:s,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":Oe},error:"Error while fetching completion item",signal:c.signal});return p||null}catch(p){return a(p).completionError("Error while fetching completion item"),null}},Le=({filename:t,position:e,model:o,language:r,technologies:n,externalContext:i})=>{let s=Ie(e,o),l=h(e,o),c=S(e,o);return{filename:t,language:r,technologies:n,externalContext:i,textBeforeCursor:l,textAfterCursor:c,editorState:{completionMode:s}}},Ie=(t,e)=>{let o=h(t,e),r=S(t,e);return o&&r?"fill-in-the-middle":"completion"};var b=class{constructor(e,o){if(!e)throw new Error("Groq API key is required to initialize Copilot.");this.apiKey=e,$.setModel(o?.model||O)}async complete({completionMetadata:e}){try{let o=$.getModel(),r=this.createRequestBody(e,o),n=this.createHeaders(),i=await M.POST(J,r,{headers:n});if(!i.choices||i.choices.length===0)throw new Error("No completion choices received from API");return{completion:i.choices[0].message.content}}catch(o){return o instanceof Error?a(o).apiError("Failed to fetch completion"):a(o).apiError("Unknown error while fetching completion"),{error:"Failed to generate completion"}}}createRequestBody(e,o){return{model:z[o],messages:[{role:"system",content:ne(e)},{role:"user",content:ie(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var le={conso:"le.log($1)","new P":`romise((resolve, reject) => {
14
13
  $1
15
14
  })`,"new A":"rray","new S":"et","throw n":"ew Error($1)",setTimeout:`(() => {
16
15
  $1
@@ -26,4 +25,4 @@ ${h}
26
25
  $1
27
26
  }`,"=>":` {
28
27
  $1
29
- }`,"new M":"ap","new W":"eakMap"};var ue=[{language:"javascript",snippets:de}];var A=class{constructor(){this.predictions=new Map,this.loadPredictions()}predictCode(t,o){try{let r=this.predictions.get(t);if(!r)return"";let n=N(o);return this.findMatchingPrediction(r,n)}catch(r){return u(r).predictionError("Error while predicting code"),""}}loadPredictions(){ue.forEach(t=>{this.predictions.set(t.language,t.snippets)})}findMatchingPrediction(t,o){for(let[r,n]of Object.entries(t))if(o.startsWith(N(r)))return n;return""}};var P=xe(require("react")),Ee=require("@monaco-editor/react");var De=new A,w=new Map,ge=Date.now(),Fe=Y(le,250),fe=({monaco:e,filename:t,endpoint:o,technologies:r,language:n,externalContext:i})=>{if(!(!n||!o))try{let s=e.languages.registerInlineCompletionsProvider(n,{provideInlineCompletions:async(c,l,p,a)=>Be(e,c,l,p,a,{language:n,filename:t,endpoint:o,technologies:r,externalContext:i}),freeInlineCompletions:()=>{}});return()=>{s.dispose(),w.clear()}}catch(s){u(s).editorError("Error while registering copilot")}},Be=async(e,t,o,r,n,i)=>{if(!new O(o,t,i.language,ge).shouldProvideCompletions())return C([]);let c=pe(o,t),l=w.get(c);if(l&&!l.isExpired())return C([l.completion]);if(n.isCancellationRequested)return C([]);let p=t.getValue(),a=new e.Range(o.lineNumber,o.column,o.lineNumber,o.column),h=De.predictCode(i.language,X(p,o.lineNumber));if(h){let m=he(h,a,!0);return Ce(c,m),C([m])}try{let m=await Fe({...i,code:p,model:t,position:o,token:n});if(m){ge=Date.now();let R=he(m,a);return Ce(c,R),C([R])}}catch(m){u(m).completionError("Failed to fetch completion item")}return C([])},he=(e,t,o=!1)=>({insertText:{snippet:e},range:t,completeBracketPairs:o}),Ce=(e,t)=>{w.set(e,{completion:t,timestamp:Date.now(),isExpired:()=>Date.now()-w.get(e).timestamp>6e4})},C=e=>({items:e,enableForwardStability:!0});var qe=({filename:e,endpoint:t,technologies:o,externalContext:r,onMount:n,...i})=>{let s=P.default.useRef(),c=P.default.useCallback((l,p)=>{try{s.current=fe({monaco:p,filename:e,endpoint:t,technologies:o,externalContext:r,language:i.language})}catch(a){u(a).monacopilotError("Error while registering copilot")}n?.(l,p)},[e,t,o,r,n,i.language]);return P.default.useEffect(()=>()=>{s.current?.()},[]),P.default.createElement(Ee.Editor,{...i,onMount:c,options:S(i.options,G)})},Te=qe;var f=require("@monaco-editor/react");0&&(module.exports={Copilot,DiffEditor,loader,useMonaco});
28
+ }`,"new M":"ap","new W":"eakMap"};var ae=[{language:"javascript",snippets:le}];var v=class{constructor(){this.predictions=new Map,this.loadPredictions()}predict(e,o){try{let r=this.predictions.get(e);if(!r)return"";let n=A(o);return this.findMatchingPrediction(r,n)}catch(r){return a(r).predictionError("Error while predicting next text snippet"),""}}loadPredictions(){ae.forEach(e=>{this.predictions.set(e.language,e.snippets)})}findMatchingPrediction(e,o){for(let[r,n]of Object.entries(e))if(o.startsWith(A(r)))return n;return""}};var P=Te(require("react")),pe=require("@monaco-editor/react");var be=new v,ve=200,Ne=F(se,ve),we=async({monaco:t,model:e,position:o,context:r,token:n,hasCompletionBeenAccepted:i,onShowCompletion:s,options:l})=>{if(i)return u([]);let c=e.getValue(),p=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column);if(!new L(o,e).shouldProvideCompletions())return u([]);let m=H(o,e).map(d=>({insertText:d.completion,range:d.range}));if(m.length)return s(),u(m);if(n.isCancellationRequested)return u([]);let C=be.predict(l.language,e.getLineContent(o.lineNumber));if(C)return s(),u([{insertText:{snippet:C},range:p}]);try{let d=await Ne({...l,text:c,model:e,position:o,token:n});if(d){let N=te(e,o,d),k=ee(N,p,o,e);return K({completion:N,range:k,textBeforeCursorInLine:f(o,e)}),s(),u([{insertText:N,range:k}])}}catch(d){a(d).completionError("Failed to fetch completion item")}return u([])},me=we;var D=!1,_=!1,ce=({monaco:t,editor:e,...o})=>{try{let r=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:async(n,i,s,l)=>me({monaco:t,model:n,position:i,context:s,token:l,hasCompletionBeenAccepted:D,onShowCompletion:()=>_=!0,options:o}),freeInlineCompletions:()=>{}});return e.onKeyDown(n=>{_&&(n.keyCode===t.KeyCode.Tab||n.keyCode===t.KeyCode.RightArrow&&n.metaKey)?(D=!0,_=!1):D=!1}),()=>{r.dispose(),V()}}catch(r){a(r).editorError("Error while registering Copilot")}};var Ae=({filename:t,endpoint:e,technologies:o,externalContext:r,onMount:n,...i})=>{let s=P.default.useRef(),l=P.default.useCallback((c,p)=>{try{e&&i.language&&(s.current=ce({monaco:p,editor:c,filename:t,technologies:o,externalContext:r,endpoint:e,language:i.language}))}catch(m){a(m).monacopilotError("Error while registering copilot")}n?.(c,p)},[e,t,n,i.language,o,r]);return P.default.useEffect(()=>()=>{s.current?.()},[]),P.default.createElement(pe.Editor,{...i,onMount:l,options:w(i.options,Y)})},de=Ae;var g=require("@monaco-editor/react");0&&(module.exports={Copilot,DiffEditor,loader,useMonaco});
package/build/index.mjs CHANGED
@@ -1,16 +1,15 @@
1
- var q={scrollBeyondLastColumn:0,codeLens:!1,minimap:{enabled:!1},quickSuggestions:!1,folding:!1,foldingHighlight:!1,foldingImportsByDefault:!1,links:!1,fontSize:14,wordWrap:"on",automaticLayout:!0};var k={llama:"llama3-70b-8192"},P="llama",j="https://api.groq.com/openai/v1/chat/completions";var G={javascript:1,typescript:2,typescriptreact:3,python:4,vue:5,php:6,dart:7,javascriptreact:8,go:9,css:10,cpp:11,html:12,scss:13,markdown:14,csharp:15,java:16,json:17,rust:18,ruby:19,c:20},A={" ":1,"!":2,'"':3,"#":4,$:5,"%":6,"&":7,"'":8,"(":9,")":10,"*":11,"+":12,",":13,"-":14,".":15,"/":16,0:17,1:18,2:19,3:20,4:21,5:22,6:23,7:24,8:25,9:26,":":27,";":28,"<":29,"=":30,">":31,"?":32,"@":33,A:34,B:35,C:36,D:37,E:38,F:39,G:40,H:41,I:42,J:43,K:44,L:45,M:46,N:47,O:48,P:49,Q:50,R:51,S:52,T:53,U:54,V:55,W:56,X:57,Y:58,Z:59,"[":60,"\\":61,"]":62,"^":63,_:64,"`":65,a:66,b:67,c:68,d:69,e:70,f:71,g:72,h:73,i:74,j:75,k:76,l:77,m:78,n:79,o:80,p:81,q:82,r:83,s:84,t:85,u:86,v:87,w:88,x:89,y:90,z:91,"{":92,"|":93,"}":94,"~":95},d=[.9978708359643611,.7001905605239328,-.1736749244124868,-.22994157947320112,.13406692641682572,-.007751370662011853,.0057783222035240715,.41910878254476003,-.1621657125711092,.13770814958908187,-.06036011308184006,-.07351180985800129,0,-.05584878151248109,.30618794079412015,-.1282197982598485,.10951859303997555,.1700461782788777,-.3346057842644757,.22497985923128136,0,-.44038101825774356,-.6540115939236782,.16595600081341702,.20733910722385135,-.1337033766105696,-.06923072125290894,-.05806684191976292,.3583334671633344,-.47357732824944315,.17810871365594377,.42268219963946685,0,0,-.16379620467004602,-.43893868831061167,0,.11570094006709251,.9326431262654882,-.9990110509203912,-.44125275652726503,-.15840786997162004,-.4600396256644451,-.018814811994044403,.09230944537175266,.025814790934742798,-1.0940162204190154,-.9407503631235489,-.9854303778694269,-1.1045822488262245,-1.1417299456573262,-1.5623704405345513,-.4157473855795939,-1.0244257735561713,-.7477401944601753,-1.1275109699068402,-.0714715633552533,-1.1408628006786907,-1.0409898655074672,-.2288889836518878,-.5469549893760344,-.181946611106845,.1264329316374918,0,0,.312206968554707,-.3656436392517924,.23655650686038968,.1014912419901576,0,.06287549221765308,0,0,.19027065218932154,-.8519502045974378,0,.23753599905971923,.2488809322489166,.019969251907983224,0,.06916505526229488,.29053356359188204,-.14484456555431657,.014768129429370188,-.15051464926341374,.07614835502776021,-.3317489901313935,0,0,.04921938684669103,-.28248576768353445,-.9708816204525345,-1.3560464522265527,.014165375212383239,-.23924166472544983,.10006595730248855,.09867233147279562,.32330430333220644,-.058625706114180595,.17149853105783947,.4436484054395367,.047189049576707255,.16832520944790552,.1117259900942179,-.35469010329927253,0,-.1528189124465582,-.3804848349564939,.07278077320753953,.13263786480064088,.22920682659292527,1.1512955314336537,0,.016939862282340023,.4242994650403408,.12759835577444986,-.5577261135825583,-.19764560943067672,-.4042102444736004,.12063461617733708,-.2933966817484834,.2715683893968593,0,-.7138548251238751,0,-.023066228703035277,0,-.06383043976746139,.09683723720709651,-.7337151424080791,0,-.27191370124625525,.2819781269656171,-.08711496549050252,.11048604909969338,-.0934849550450534,.0721001250772912,.2589126797890794,.6729582659532254,-.21921032738244908,-.21535277468651456,-.45474006124091354,-.05861820126419139,-.007875306207720204,-.056661261678809284,.17727881404222662,.23603713348534658,.17485861412377932,-.5737483768696752,-.38220029570342745,-.5202722985519168,-.37187947527657256,.47155277792990113,-.12077912346691123,.47825628981545326,.4736704404000214,-.1615218651546898,.18362447973513005,0,0,-.18183417425866824,0,0,-.2538532305733833,-.1303692690676528,-.4073577969188216,.04172985870928789,-.1704527388573901,0,0,.7536858953385828,-.44703159588787644,0,-.7246484085580873,-.21378128540782063,0,.037461090552656146,-.16205852364367032,-.10973952064404884,.017468043407647377,-.1288980387397392,0,0,0,-1.218692715379445,.05536949662193305,-.3763799844799116,-.1845001725624579,-.1615576298149558,0,-.15373262203249874,-.04603412604270418,0,-.3068149681460828,.09412352468269412,0,.09116543650609721,.06065865264082559,.05688267379386188,-.05873945477722306,0,.14532465133322153,.1870857769705463,.36304258043185555,.1411392422180405,.0630388629716367,0,-1.1170522012450395,.16133697772771127,.15908534390781448,-.23485453704002232,-.1419980841417892,.21909510179526218,.39948420260153766,.40802294284289187,.15403767653746853,0,.19764784115096676,.584914157527457,0,-.4573883817015294],H=-.3043572714994554,U=.15;var W=(e,t=1e3)=>{let o=null;return(...n)=>(o&&clearTimeout(o),new Promise((i,s)=>{o=setTimeout(()=>{e(...n).then(i).catch(s)},t)}))},w=(e,t)=>{let o={...t};for(let r in e)typeof e[r]=="object"&&!Array.isArray(e[r])?t[r]&&typeof t[r]=="object"&&!Array.isArray(t[r])?o[r]=w(e[r],t[r]):o[r]={...e[r]}:o[r]=e[r];return o},V=e=>!e||e.length===0?"":e.length===1?e[0]:`${e.slice(0,-1).join(", ")} and ${e.slice(-1)}`,_=e=>e.split("").reverse().join("");var K=(e,t)=>e[t]||"",v=e=>e.split(`
2
- `)[e.split(`
3
- `).length-1].length;var Y=(e,t)=>e.split(`
4
- `)[t-1];var z=async(e,t,o={})=>{let r={"Content-Type":"application/json",...o.headers},n=t==="POST"&&o.body?JSON.stringify(o.body):void 0,i=await fetch(e,{method:t,headers:r,body:n,signal:o.signal});if(!i.ok)throw new Error(`${o.error||"Network error"}: ${i.statusText}`);return i.json()},Ce=(e,t)=>z(e,"GET",t),fe=(e,t,o)=>z(e,"POST",{...o,body:t}),R={GET:Ce,POST:fe};var f="<<CURSOR>>",J=e=>e==="javascript"?"latest JavaScript":e,X=e=>{switch(e){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code";default:return"completing the code"}},Q=e=>{let t=J(e.language),o=X(e.editorState.completionMode);return`You are an expert ${t||""} code completion assistant known for exceptional skill in ${o}.`},Ee=(e,t)=>{if(!e?.length&&!t)return"";let o=V(e),r=J(t);return`The code is written${r?` in ${r}`:""}${o?` using ${o}`:""}.`},Z=e=>{let{filename:t,language:o,technologies:r,editorState:n,codeBeforeCursor:i,codeAfterCursor:s,externalContext:c}=e,l=X(n.completionMode),p=t?`the file named ${t}`:"a larger project",a=`You will be presented with a code snippet in '<code>' tag where the cursor location is marked with '${f}'. Your task is to assist with ${l}. This code is part of ${p}. Please `;switch(n.completionMode){case"fill-in-the-middle":a+=`generate a completion to fill the middle of the code around '${f}'. Ensure the completion replaces '${f}' precisely, maintaining consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break;case"completion":a+=`provide the necessary completion for '${f}' while ensuring consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break}a+=` Output only the necessary completion code, without additional explanations or content.${Ee(r,o)}`;let h=`${i}${f}${s}
1
+ var _=(t,e=1e3)=>{let o=null;return(...n)=>(o&&clearTimeout(o),new Promise((i,s)=>{o=setTimeout(()=>{t(...n).then(i).catch(s)},e)}))},b=(t,e)=>{let o={...e};for(let r in t)typeof t[r]=="object"&&!Array.isArray(t[r])?e[r]&&typeof e[r]=="object"&&!Array.isArray(e[r])?o[r]=b(t[r],e[r]):o[r]={...t[r]}:o[r]=t[r];return o},k=t=>!t||t.length===0?"":t.length===1?t[0]:`${t.slice(0,-1).join(", ")} and ${t.slice(-1)}`,v=t=>t.split("").reverse().join("");var T=(t,e)=>e.getLineContent(t.lineNumber)[t.column-1],q=(t,e)=>e.getLineContent(t.lineNumber).slice(t.column-1),f=(t,e)=>e.getLineContent(t.lineNumber).slice(0,t.column-1),F=t=>{let e=t.split(`
2
+ `);return e[e.length-1].length};var C=(t,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),N=(t,e)=>e.getValueInRange({startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var U=async(t,e,o={})=>{let r={"Content-Type":"application/json",...o.headers},n=e==="POST"&&o.body?JSON.stringify(o.body):void 0,i=await fetch(t,{method:e,headers:r,body:n,signal:o.signal});if(!i.ok)throw new Error(`${o.error||"Network error"}: ${i.statusText}`);return i.json()},ae=(t,e)=>U(t,"GET",e),me=(t,e,o)=>U(t,"POST",{...o,body:e}),P={GET:ae,POST:me};var x=class{constructor(e,o){this.formattedCompletion="";this.originalCompletion="";this.model=e,this.cursorPosition=o,this.lineCount=e.getLineCount()}ignoreBlankLines(){return this.formattedCompletion.trimStart()===""&&this.originalCompletion!==`
3
+ `&&(this.formattedCompletion=this.formattedCompletion.trim()),this}normalise(e){return e?.trim()??""}removeDuplicatesFromStartOfCompletion(){let e=C(this.cursorPosition,this.model).trim(),o=this.normalise(this.formattedCompletion),r=0,n=Math.min(o.length,e.length);for(let i=1;i<=n;i++){let s=e.slice(-i),l=o.slice(0,i);if(s===l)r=i;else break}return r>0&&(this.formattedCompletion=this.formattedCompletion.slice(r)),this}preventDuplicateLines(){for(let e=this.cursorPosition.lineNumber+1;e<this.cursorPosition.lineNumber+3&&e<this.lineCount;e++){let o=this.model.getLineContent(e);if(this.normalise(o)===this.normalise(this.originalCompletion))return this.formattedCompletion="",this}return this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}trimStart(){let e=this.formattedCompletion.search(/\S/);return e>this.cursorPosition.column-1&&(this.formattedCompletion=this.formattedCompletion.slice(e)),this}format(e){return this.originalCompletion=e,this.formattedCompletion=e,this.ignoreBlankLines().removeDuplicatesFromStartOfCompletion().preventDuplicateLines().removeInvalidLineBreaks().trimStart(),this.formattedCompletion}};var ce=25,h=[],j=(t,e)=>h.filter(o=>{let r=e.getValueInRange(o.range);return f(t,e)===o.textBeforeCursorInLine&&o.range.startLineNumber===t.lineNumber&&t.column===o.range.startColumn||o.completion.startsWith(r)&&o.range.startLineNumber===t.lineNumber&&t.column>=o.range.startColumn-r.length&&t.column<=o.range.endColumn}),G=t=>{h.length>=ce&&h.shift(),h.push(t)},W=()=>{h.length=0};var H={scrollBeyondLastColumn:0,codeLens:!1,minimap:{enabled:!1},quickSuggestions:!1,folding:!1,foldingHighlight:!1,foldingImportsByDefault:!1,links:!1,fontSize:14,wordWrap:"on",automaticLayout:!0,formatOnPaste:!0,inlineSuggest:{enabled:!0,mode:void 0}};var K={llama:"llama3-70b-8192"},y="llama",V="https://api.groq.com/openai/v1/chat/completions";var Y=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var z=(t,e)=>{let o=T(t,e);return!!o&&!Y.has(o)},J=(t,e)=>{let o=q(t,e).trim(),r=f(t,e).trim();return t.column<=3&&(o!==""||r!=="")};var Q=(t,e,o,r)=>{let n=(t.match(/\n/g)||[]).length,i=F(t),s=T(o,r);return{startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:o.lineNumber+n,endColumn:t.includes(s)?o.lineNumber===e.startLineNumber&&n===0?o.column+i:i:o.column}},X=(t,e,o)=>new x(t,e).format(o),u=t=>({items:t,enableForwardStability:!0});var M=class{constructor(e,o){this.cursorPosition=e,this.model=o}shouldProvideCompletions(){return!z(this.cursorPosition,this.model)&&!J(this.cursorPosition,this.model)}};var R=class{static getModel(){return this.model}static setModel(e){this.model=e}};R.model=y;var w=R;var A=class{constructor(e){this.error=e}logError(e,o,r){console.error(`${e}: ${o}`,r)}monacopilotError(e){this.logError("MONACO_PILOT_ERROR",e,this.error)}apiError(e){this.logError("API_ERROR",e,this.error)}completionError(e){this.logError("COMPLETION_ERROR",e,this.error)}predictionError(e){this.logError("PREDICTION_ERROR",e,this.error)}editorError(e){this.logError("EDITOR_ERROR",e,this.error)}unexpectedError(){this.error instanceof Error?this.logError("UNEXPECTED_ERROR",this.error.message,this.error.stack):this.logError("UNKNOWN_ERROR",String(this.error))}},a=t=>new A(t);var E="<<CURSOR>>",Z=t=>t==="javascript"?"latest JavaScript":t,ee=t=>{switch(t){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code";default:return"completing the code"}},te=t=>{let e=Z(t.language),o=ee(t.editorState.completionMode);return`You are an expert ${e||""} code completion assistant known for exceptional skill in ${o}.`},pe=(t,e)=>{if(!t?.length&&!e)return"";let o=k(t),r=Z(e);return`The code is written${r?` in ${r}`:""}${o?` using ${o}`:""}.`},oe=t=>{let{filename:e,language:o,technologies:r,editorState:n,textBeforeCursor:i,textAfterCursor:s,externalContext:l}=t,c=ee(n.completionMode),p=e?`the file named ${e}`:"a larger project",m=`You will be presented with a code snippet in '<code>' tag where the cursor location is marked with '${E}'. Your task is to assist with ${c}. This code is part of ${p}. Please `;switch(n.completionMode){case"fill-in-the-middle":m+=`generate a completion to fill the middle of the code around '${E}'. Ensure the completion replaces '${E}' precisely, maintaining consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break;case"completion":m+=`provide the necessary completion for '${E}' while ensuring consistency, semantic accuracy, and relevance to the context. The completion must start exactly from the cursor position without any preceding or following characters, and it should not introduce any syntactical or semantic errors to the existing code.`;break}m+=` Output only the necessary completion code, without additional explanations or content.${pe(r,o)}`;let g=`${i}${E}${s}
5
4
 
6
- `;return c&&c.length>0&&(h+=c.map(m=>`// Path: ${m.path}
7
- ${m.content}
5
+ `;return l&&l.length>0&&(g+=l.map(d=>`// Path: ${d.path}
6
+ ${d.content}
8
7
  `).join(`
9
- `)),a+=`
8
+ `)),m+=`
10
9
 
11
10
  <code>
12
- ${h}
13
- </code>`,a.endsWith(".")?a:`${a}.`};var Te=2e3,ye=new Set(['"',"'","}","]",")",","," ",":","."]),ee=(e,t)=>{let r=t.getLineContent(e.lineNumber).substring(e.column-1);return/^\s*$/.test(r)},te=(e,t)=>{let o=t.getLineContent(e.lineNumber),r=K(o,e.column-1);return!ye.has(r)&&!!r},E=(e,t)=>{let o=t.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:e.lineNumber,endColumn:e.column}),r=t.getValueInRange({startLineNumber:e.lineNumber,startColumn:e.column,endLineNumber:t.getLineCount(),endColumn:t.getLineMaxColumn(t.getLineCount())});return{codeBeforeCursor:o,codeAfterCursor:r}},oe=(e,t)=>{let o=t.getLineContent(e.lineNumber),r=o.slice(e.column-1).trim(),n=o.slice(0,e.column-1).trim();return e.column<=3&&(r!==""||n!=="")},re=(e,t)=>{let o=t.getLineContent(e.lineNumber),[r,n]=[o.slice(0,e.column-1).trim(),o.slice(e.column-1).trim()];return r&&n?"fill-in-the-middle":"completion"},ne=(e,t,o=Te)=>t-e<o;var Pe="application/json",ie="Error while fetching completion item",se=async({filename:e,endpoint:t,language:o,technologies:r,externalContext:n,model:i,position:s,token:c})=>{let l=new AbortController;if(c.isCancellationRequested)return l.abort(),null;try{let{completion:p}=await R.POST(t,{completionMetadata:Re({filename:e,position:s,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":Pe},error:ie,signal:l.signal});return p||null}catch(p){return console.error(ie,p),null}},Re=({filename:e,position:t,model:o,language:r,technologies:n,externalContext:i})=>{let s=re(t,o),{codeBeforeCursor:c,codeAfterCursor:l}=E(t,o);return{filename:e,language:r,technologies:n,externalContext:i,codeBeforeCursor:c,codeAfterCursor:l,editorState:{completionMode:s}}},ce=(e,t)=>{let{codeBeforeCursor:o}=E(e,t);return`${e.lineNumber}:${e.column}:${o}`};var S=class{constructor(){this.previousLabel=0,this.previousLabelTimestamp=Date.now()-3600*1e3,this.probabilityAccept=0}},ae=e=>{let t=new S,o=t.previousLabel,r=0;e.properties.afterCursorWhitespace==="true"&&(r=1);let n=(Date.now()-t.previousLabelTimestamp)/1e3,i=Math.log(1+n),s=0,c=0,l=0,p=0;if(e.prefix){s=Math.log(1+v(e.prefix));let I=e.prefix.slice(-1);c=A[I]??0}let a=e.prefix?.trimEnd();if(a){l=Math.log(1+v(a));let I=a.slice(-1);p=A[I]??0}let h=e.measurements.documentLength?Math.log(1+e.measurements.documentLength):0,m=e.measurements.promptEndPos?Math.log(1+e.measurements.promptEndPos):0,y=e.measurements.promptEndPos&&e.measurements.documentLength?(e.measurements.promptEndPos+.5)/(1+e.measurements.documentLength):0,he=e.properties.languageId?G[e.properties.languageId]:0,g=H;g+=d[0]*o+d[1]*r+d[2]*i,g+=d[3]*s+d[4]*l,g+=d[5]*h+d[6]*m,g+=d[7]*y,g+=d[8+he],g+=d[29+c],g+=d[125+p];let B=1/(1+Math.exp(-g));return t.probabilityAccept=B,B};var M=class{constructor(t,o,r,n){this.cursorPosition=t,this.model=o,this.language=r,this.lastCompletionTime=n}calculateContextualScore(t,o,r){let{codeBeforeCursor:n}=E(t,o),i=ee(t,o),s=o.getValueLength(),c=o.getOffsetAt(t);return ae({properties:{afterCursorWhitespace:String(i),languageId:r},measurements:{documentLength:s,promptEndPos:c},prefix:n})}shouldProvideCompletions(){let t=Date.now();return this.calculateContextualScore(this.cursorPosition,this.model,this.language)>U&&!te(this.cursorPosition,this.model)&&!oe(this.cursorPosition,this.model)&&!ne(this.lastCompletionTime,t)}};var L=class{static getModel(){return this.model}static setModel(t){this.model=t}};L.model=P;var N=L;var $=class{constructor(t){this.error=t}logError(t,o,r){console.error(`${t}: ${o}`,r)}monacopilotError(t){this.logError("MONACO_PILOT_ERROR",t,this.error)}apiError(t){this.logError("API_ERROR",t,this.error)}completionError(t){this.logError("COMPLETION_ERROR",t,this.error)}predictionError(t){this.logError("PREDICTION_ERROR",t,this.error)}editorError(t){this.logError("EDITOR_ERROR",t,this.error)}unexpectedError(){this.error instanceof Error?this.logError("UNEXPECTED_ERROR",this.error.message,this.error.stack):this.logError("UNKNOWN_ERROR",String(this.error))}},u=e=>new $(e);var D=class extends Error{constructor(o,r,n){super(r);this.code=o;this.details=n;this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor)}},T=class extends D{constructor(t,o){super("COMPLETION_ERROR",t,o)}};var F=class{constructor(t,o){if(!t)throw new Error("Groq API key is required to initialize Copilot.");this.apiKey=t,N.setModel(o?.model||P)}async complete({completionMetadata:t}){try{let o=N.getModel(),r=this.createRequestBody(t,o),n=this.createHeaders(),i=await R.POST(j,r,{headers:n});if(!i.choices||i.choices.length===0)throw new T("No completion choices received from API");return{completion:i.choices[0].message.content}}catch(o){return o instanceof T?u(o).completionError("Failed to fetch completion"):o instanceof Error?u(o).apiError("Failed to fetch completion"):u(o).apiError("Unknown error during completion"),{error:"Failed to generate completion"}}}createRequestBody(t,o){return{model:k[o],messages:[{role:"system",content:Q(t)},{role:"user",content:Z(t)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var le={conso:"le.log($1)","new P":`romise((resolve, reject) => {
11
+ ${g}
12
+ </code>`,m.endsWith(".")?m:`${m}.`};var de="application/json",re=async({filename:t,endpoint:e,language:o,technologies:r,externalContext:n,model:i,position:s,token:l})=>{let c=new AbortController;if(l.isCancellationRequested)return c.abort(),null;try{let{completion:p}=await P.POST(e,{completionMetadata:ue({filename:t,position:s,model:i,language:o,technologies:r,externalContext:n})},{headers:{"Content-Type":de},error:"Error while fetching completion item",signal:c.signal});return p||null}catch(p){return a(p).completionError("Error while fetching completion item"),null}},ue=({filename:t,position:e,model:o,language:r,technologies:n,externalContext:i})=>{let s=fe(e,o),l=C(e,o),c=N(e,o);return{filename:t,language:r,technologies:n,externalContext:i,textBeforeCursor:l,textAfterCursor:c,editorState:{completionMode:s}}},fe=(t,e)=>{let o=C(t,e),r=N(t,e);return o&&r?"fill-in-the-middle":"completion"};var S=class{constructor(e,o){if(!e)throw new Error("Groq API key is required to initialize Copilot.");this.apiKey=e,w.setModel(o?.model||y)}async complete({completionMetadata:e}){try{let o=w.getModel(),r=this.createRequestBody(e,o),n=this.createHeaders(),i=await P.POST(V,r,{headers:n});if(!i.choices||i.choices.length===0)throw new Error("No completion choices received from API");return{completion:i.choices[0].message.content}}catch(o){return o instanceof Error?a(o).apiError("Failed to fetch completion"):a(o).apiError("Unknown error while fetching completion"),{error:"Failed to generate completion"}}}createRequestBody(e,o){return{model:K[o],messages:[{role:"system",content:te(e)},{role:"user",content:oe(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var ne={conso:"le.log($1)","new P":`romise((resolve, reject) => {
14
13
  $1
15
14
  })`,"new A":"rray","new S":"et","throw n":"ew Error($1)",setTimeout:`(() => {
16
15
  $1
@@ -26,4 +25,4 @@ ${h}
26
25
  $1
27
26
  }`,"=>":` {
28
27
  $1
29
- }`,"new M":"ap","new W":"eakMap"};var pe=[{language:"javascript",snippets:le}];var b=class{constructor(){this.predictions=new Map,this.loadPredictions()}predictCode(t,o){try{let r=this.predictions.get(t);if(!r)return"";let n=_(o);return this.findMatchingPrediction(r,n)}catch(r){return u(r).predictionError("Error while predicting code"),""}}loadPredictions(){pe.forEach(t=>{this.predictions.set(t.language,t.snippets)})}findMatchingPrediction(t,o){for(let[r,n]of Object.entries(t))if(o.startsWith(_(r)))return n;return""}};import x from"react";import{Editor as Oe}from"@monaco-editor/react";var Me=new b,O=new Map,me=Date.now(),Le=W(se,250),ge=({monaco:e,filename:t,endpoint:o,technologies:r,language:n,externalContext:i})=>{if(!(!n||!o))try{let s=e.languages.registerInlineCompletionsProvider(n,{provideInlineCompletions:async(c,l,p,a)=>be(e,c,l,p,a,{language:n,filename:t,endpoint:o,technologies:r,externalContext:i}),freeInlineCompletions:()=>{}});return()=>{s.dispose(),O.clear()}}catch(s){u(s).editorError("Error while registering copilot")}},be=async(e,t,o,r,n,i)=>{if(!new M(o,t,i.language,me).shouldProvideCompletions())return C([]);let c=ce(o,t),l=O.get(c);if(l&&!l.isExpired())return C([l.completion]);if(n.isCancellationRequested)return C([]);let p=t.getValue(),a=new e.Range(o.lineNumber,o.column,o.lineNumber,o.column),h=Me.predictCode(i.language,Y(p,o.lineNumber));if(h){let m=de(h,a,!0);return ue(c,m),C([m])}try{let m=await Le({...i,code:p,model:t,position:o,token:n});if(m){me=Date.now();let y=de(m,a);return ue(c,y),C([y])}}catch(m){u(m).completionError("Failed to fetch completion item")}return C([])},de=(e,t,o=!1)=>({insertText:{snippet:e},range:t,completeBracketPairs:o}),ue=(e,t)=>{O.set(e,{completion:t,timestamp:Date.now(),isExpired:()=>Date.now()-O.get(e).timestamp>6e4})},C=e=>({items:e,enableForwardStability:!0});var xe=({filename:e,endpoint:t,technologies:o,externalContext:r,onMount:n,...i})=>{let s=x.useRef(),c=x.useCallback((l,p)=>{try{s.current=ge({monaco:p,filename:e,endpoint:t,technologies:o,externalContext:r,language:i.language})}catch(a){u(a).monacopilotError("Error while registering copilot")}n?.(l,p)},[e,t,o,r,n,i.language]);return x.useEffect(()=>()=>{s.current?.()},[]),x.createElement(Oe,{...i,onMount:c,options:w(i.options,q)})},Ie=xe;import{DiffEditor as Xt,useMonaco as Qt,loader as Zt}from"@monaco-editor/react";export{F as Copilot,Xt as DiffEditor,Ie as default,Zt as loader,Qt as useMonaco};
28
+ }`,"new M":"ap","new W":"eakMap"};var ie=[{language:"javascript",snippets:ne}];var O=class{constructor(){this.predictions=new Map,this.loadPredictions()}predict(e,o){try{let r=this.predictions.get(e);if(!r)return"";let n=v(o);return this.findMatchingPrediction(r,n)}catch(r){return a(r).predictionError("Error while predicting next text snippet"),""}}loadPredictions(){ie.forEach(e=>{this.predictions.set(e.language,e.snippets)})}findMatchingPrediction(e,o){for(let[r,n]of Object.entries(e))if(o.startsWith(v(r)))return n;return""}};import L from"react";import{Editor as Te}from"@monaco-editor/react";var ge=new O,Ce=200,he=_(re,Ce),Ee=async({monaco:t,model:e,position:o,context:r,token:n,hasCompletionBeenAccepted:i,onShowCompletion:s,options:l})=>{if(i)return u([]);let c=e.getValue(),p=new t.Range(o.lineNumber,o.column,o.lineNumber,o.column);if(!new M(o,e).shouldProvideCompletions())return u([]);let m=j(o,e).map(d=>({insertText:d.completion,range:d.range}));if(m.length)return s(),u(m);if(n.isCancellationRequested)return u([]);let g=ge.predict(l.language,e.getLineContent(o.lineNumber));if(g)return s(),u([{insertText:{snippet:g},range:p}]);try{let d=await he({...l,text:c,model:e,position:o,token:n});if(d){let I=X(e,o,d),D=Q(I,p,o,e);return G({completion:I,range:D,textBeforeCursorInLine:f(o,e)}),s(),u([{insertText:I,range:D}])}}catch(d){a(d).completionError("Failed to fetch completion item")}return u([])},se=Ee;var $=!1,B=!1,le=({monaco:t,editor:e,...o})=>{try{let r=t.languages.registerInlineCompletionsProvider(o.language,{provideInlineCompletions:async(n,i,s,l)=>se({monaco:t,model:n,position:i,context:s,token:l,hasCompletionBeenAccepted:$,onShowCompletion:()=>B=!0,options:o}),freeInlineCompletions:()=>{}});return e.onKeyDown(n=>{B&&(n.keyCode===t.KeyCode.Tab||n.keyCode===t.KeyCode.RightArrow&&n.metaKey)?($=!0,B=!1):$=!1}),()=>{r.dispose(),W()}}catch(r){a(r).editorError("Error while registering Copilot")}};var Pe=({filename:t,endpoint:e,technologies:o,externalContext:r,onMount:n,...i})=>{let s=L.useRef(),l=L.useCallback((c,p)=>{try{e&&i.language&&(s.current=le({monaco:p,editor:c,filename:t,technologies:o,externalContext:r,endpoint:e,language:i.language}))}catch(m){a(m).monacopilotError("Error while registering copilot")}n?.(c,p)},[e,t,n,i.language,o,r]);return L.useEffect(()=>()=>{s.current?.()},[]),L.createElement(Te,{...i,onMount:l,options:b(i.options,H)})},xe=Pe;import{DiffEditor as Qt,useMonaco as Xt,loader as Zt}from"@monaco-editor/react";export{S as Copilot,Qt as DiffEditor,xe as default,Zt as loader,Xt as useMonaco};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monacopilot",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "description": "Extended Monaco Editor with AI auto-completion and new themes for React.",
5
5
  "main": "./build/index.js",
6
6
  "module": "./build/index.mjs",
@@ -45,6 +45,10 @@
45
45
  "ai-editor"
46
46
  ],
47
47
  "homepage": "https://monacopilot.vercel.app",
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "https://github.com/arshad-yaseen/monacopilot"
51
+ },
48
52
  "license": "MIT",
49
53
  "author": "Arshad Yaseen <m@arshadyaseen.com>",
50
54
  "peerDependencies": {