monacopilot 0.9.15 → 0.9.17

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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Arshad Yaseen
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Arshad Yaseen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,278 +1,178 @@
1
- ![Hero Image](https://i.postimg.cc/PrsQ1KLb/Frame-1.png)
2
-
3
- # Monacopilot
4
-
5
- **Monacopilot** integrates AI auto-completion into the Monaco Editor, inspired by GitHub Copilot.
6
-
7
- ## Table of Contents
8
-
9
- - [Demo](#demo)
10
- - [Installation](#installation)
11
- - [Usage](#usage)
12
- - [Configuration Options](#configuration-options)
13
- - [External Context](#external-context)
14
- - [Changing the Provider and Model](#changing-the-provider-and-model)
15
- - [Filename](#filename)
16
- - [Completions for Specific Technologies](#completions-for-specific-technologies)
17
- - [Guides](#guides)
18
- - [Next.js Integration](#nextjs-integration)
19
- - [Cost Overview](#cost-overview)
20
- - [FAQ](#faq)
21
- - [Contributing](#contributing)
22
-
23
- ## Demo
24
-
25
- https://github.com/user-attachments/assets/4af4e24a-1b05-4bee-84aa-1521ad7098cd
26
-
27
- ## Installation
28
-
29
- To install Monacopilot, run:
30
-
31
- ```bash
32
- npm install monacopilot
33
- ```
34
-
35
- ## Usage
36
-
37
- #### Setting Up the API Key
38
-
39
- Start by obtaining an API key from the [Groq console](https://console.groq.com/keys). Once you have your API key, define it as an environment variable in your project:
40
-
41
- ```bash
42
- # .env.local
43
- GROQ_API_KEY=your-api-key
44
- ```
45
-
46
- #### API Handler
47
-
48
- Set up an API handler to manage auto-completion requests. An example using Express.js:
49
-
50
- ```javascript
51
- const express = require('express');
52
- const bodyParser = require('body-parser');
53
- const { Copilot } = require('monacopilot');
54
-
55
- const app = express();
56
-
57
- const copilot = new Copilot(process.env.GROQ_API_KEY);
58
-
59
- app.use(bodyParser.json());
60
-
61
- app.post('/copilot', async (req, res) => {
62
- const completion = await copilot.complete(req.body);
63
- res.status(200).json(completion);
64
- });
65
-
66
- app.listen(3000)
67
- ```
68
-
69
- #### Register Copilot with the Monaco Editor
70
-
71
- Next, register Copilot with the Monaco editor.
72
-
73
- ```javascript
74
- import * as monaco from 'monaco-editor';
75
- import { registerCopilot } from 'monacopilot';
76
-
77
- const editor = monaco.editor.create(document.getElementById('container'), {
78
- language: 'javascript'
79
- });
80
-
81
- registerCopilot(monaco, editor, {
82
- endpoint: 'https://api.example.com/copilot',
83
- language: 'javascript',
84
- });
85
- ```
86
-
87
- ## Configuration Options
88
-
89
- ### External Context
90
-
91
- Enhance the accuracy and relevance of Copilot's completions by providing additional code context from your workspace.
92
-
93
- ```javascript
94
- registerCopilot(monaco, editor, {
95
- // ...other options
96
- externalContext: [
97
- {
98
- path: './utils.js',
99
- content: 'export const reverse = (str) => str.split("").reverse().join("")'
100
- }
101
- ]
102
- });
103
- ```
104
-
105
- By providing external context, Copilot can offer more intelligent suggestions. For example, if you start typing `const isPalindrome = `, Copilot may suggest using the `reverse` function from `utils.js`.
106
-
107
- ### Changing the Provider and Model
108
-
109
- You can specify a different provider and model for completions by setting the `provider` and `model` parameters in the `Copilot` instance.
110
-
111
- ```javascript
112
- const copilot = new Copilot(process.env.OPENAI_API_KEY, {
113
- provider: 'openai',
114
- model: 'gpt-4o'
115
- });
116
- ```
117
-
118
- The default provider is `groq` and the default model is `llama-3-70b`.
119
-
120
- | Provider | Model | Description | Avg. Response Time |
121
- |----------|-------------|----------------------------------------------------|--------------------|
122
- | Groq | llama-3-70b | Fast and efficient, suitable for most tasks | <0.5s |
123
- | OpenAI | gpt-4o-mini | Mini version of gpt-4o, cheaper | 1.5-3s |
124
- | OpenAI | gpt-4o | Highly intelligent, ideal for complex completions | 1-2s |
125
-
126
- ### Filename
127
-
128
- Specify the name of the file being edited to receive more contextually relevant completions.
129
-
130
- ```javascript
131
- registerCopilot(monaco, editor, {
132
- // ...other options
133
- filename: 'utils.js' // e.g., "index.js", "utils/objects.js"
134
- });
135
- ```
136
-
137
- Now, the completions will be more relevant to utilities.
138
-
139
- ### Completions for Specific Technologies
140
-
141
- Enable completions tailored to specific technologies by using the `technologies` option.
142
-
143
- ```javascript
144
- registerCopilot(monaco, editor, {
145
- // ...other options
146
- technologies: ['react', 'next.js', 'tailwindcss']
147
- });
148
- ```
149
-
150
- This configuration will provide completions relevant to React, Next.js, and Tailwind CSS.
151
-
152
- ## Guides
153
-
154
- ### Next.js Integration
155
-
156
- Follow the steps below to integrate AI auto-completion into your Next.js project.
157
-
158
- #### Setting Up the API Key
159
-
160
- Start by obtaining an API key from the [Groq console](https://console.groq.com/keys). Once you have your API key, define it as an environment variable in your project:
161
-
162
- ```bash
163
- # .env.local
164
- GROQ_API_KEY=your-api-key
165
- ```
166
-
167
- #### API Handler
168
-
169
- Set up an API handler to manage auto-completion requests.
170
-
171
- **App Router:**
172
-
173
- ```javascript
174
- // app/api/copilot/route.ts
175
- import { Copilot } from 'monacopilot';
176
-
177
- const copilot = new Copilot(process.env.GROQ_API_KEY);
178
-
179
- export async function POST(req) {
180
- const body = await req.json();
181
- const completion = await copilot.complete(body);
182
-
183
- return Response.json(completion, { status: 200 });
184
- }
185
- ```
186
-
187
- **Pages Router:**
188
-
189
- ```javascript
190
- // pages/api/copilot.ts
191
- import { NextApiRequest, NextApiResponse } from 'next';
192
- import { Copilot } from 'monacopilot';
193
-
194
- const copilot = new Copilot(process.env.GROQ_API_KEY);
195
-
196
- export default async function handler(req, res) {
197
- const completion = await copilot.complete(req.body);
198
-
199
- res.status(200).json(completion);
200
- }
201
- ```
202
-
203
- #### Install Monaco Editor
204
-
205
- Install a React-compatible Monaco editor package such as `@monaco-editor/react`:
206
-
207
- ```bash
208
- npm install @monaco-editor/react
209
- ```
210
-
211
- #### Register Copilot with the Monaco Editor
212
-
213
- Next, register Copilot with the Monaco editor.
214
-
215
- ```tsx
216
- 'use client';
217
-
218
- import { useEffect, useState } from 'react';
219
- import MonacoEditor from '@monaco-editor/react';
220
- import { registerCopilot, type Monaco, type StandaloneCodeEditor } from 'monacopilot';
221
-
222
- export default function CodeEditor() {
223
- const [editor, setEditor] = useState<StandaloneCodeEditor | null>(null);
224
- const [monaco, setMonaco] = useState<Monaco | null>(null);
225
-
226
- useEffect(() => {
227
- if (!monaco || !editor) return;
228
-
229
- const copilot = registerCopilot(
230
- monaco,
231
- editor,
232
- {
233
- endpoint: '/api/copilot',
234
- language: 'javascript',
235
- },
236
- );
237
-
238
- return () => {
239
- copilot.deregister();
240
- };
241
- }, [monaco, editor]);
242
-
243
- return (
244
- <MonacoEditor
245
- language="javascript"
246
- onMount={(editor, monaco) => {
247
- setEditor(editor);
248
- setMonaco(monaco);
249
- }}
250
- />
251
- );
252
- }
253
- ```
254
- ---
255
-
256
- ## Cost Overview
257
-
258
- The cost of completions is very affordable. See the table below for an estimate of the costs you will need to pay for completions.
259
-
260
- | Provider | Model | Avg. Cost per 1000 Code Completions |
261
- |------------|-------------|-------------------------------------|
262
- | Groq | llama-3-70b | $0.939 |
263
- | OpenAI | gpt-4o-mini | $0.821 |
264
- | OpenAI | gpt-4o | $3.46 |
265
-
266
- > **Note:** Currently, Groq does not implement billing, allowing free usage of their API. During this free period, you will experience minimal rate limiting and some latency in completions. You can opt for Groq's enterprise plan to benefit from increased rate limits and get quick completions without visible latency.
267
-
268
- ## FAQ
269
-
270
- ### Is AI Auto Completion Free?
271
-
272
- You use your own Groq or OpenAI API key for AI auto-completion. The cost of completions is very affordable, and we implement various methods to minimize these costs as much as possible. Costs vary depending on the model you use; see this [cost overview](#cost-overview) for an idea of the cost.
273
-
274
- ## Contributing
275
-
276
- For guidelines on contributing, Please read the [contributing guide](https://github.com/arshad-yaseen/monacopilot/blob/main/CONTRIBUTING.md).
277
-
278
- We welcome contributions from the community to enhance Monacopilot's capabilities and make it even more powerful ❤️
1
+ ![Hero Image](https://i.postimg.cc/PrsQ1KLb/Frame-1.png)
2
+
3
+ # Monacopilot
4
+
5
+ **Monacopilot** integrates AI auto-completion into the Monaco Editor, inspired by GitHub Copilot.
6
+
7
+ ## Table of Contents
8
+
9
+ - [Examples](#examples)
10
+ - [Installation](#installation)
11
+ - [Usage](#usage)
12
+ - [Configuration Options](#configuration-options)
13
+ - [External Context](#external-context)
14
+ - [Changing the Provider and Model](#changing-the-provider-and-model)
15
+ - [Filename](#filename)
16
+ - [Completions for Specific Technologies](#completions-for-specific-technologies)
17
+ - [Cost Overview](#cost-overview)
18
+ - [FAQ](#faq)
19
+ - [Contributing](#contributing)
20
+
21
+ ## Demo
22
+
23
+ https://github.com/user-attachments/assets/4af4e24a-1b05-4bee-84aa-1521ad7098cd
24
+
25
+ ## Examples
26
+
27
+ Here are some examples of how to use Monacopilot in different project setups:
28
+
29
+ - Next.js ([app](https://github.com/arshad-yaseen/monacopilot/tree/main/examples/nextjs/app) | [pages](https://github.com/arshad-yaseen/monacopilot/tree/main/examples/nextjs/pages))
30
+
31
+ ## Installation
32
+
33
+ To install Monacopilot, run:
34
+
35
+ ```bash
36
+ npm install monacopilot
37
+ ```
38
+
39
+ ## Usage
40
+
41
+ #### Setting Up the API Key
42
+
43
+ Start by obtaining an API key from the [Groq console](https://console.groq.com/keys). Once you have your API key, define it as an environment variable in your project:
44
+
45
+ ```bash
46
+ # .env.local
47
+ GROQ_API_KEY=your-api-key
48
+ ```
49
+
50
+ #### API Handler
51
+
52
+ Set up an API handler to manage auto-completion requests. An example using Express.js:
53
+
54
+ ```javascript
55
+ const express = require('express');
56
+ const {Copilot} = require('monacopilot');
57
+
58
+ const app = express();
59
+ const port = process.env.PORT || 3000;
60
+ const copilot = new Copilot(process.env.GROQ_API_KEY);
61
+
62
+ app.use(express.json());
63
+
64
+ app.post('/copilot', async (req, res) => {
65
+ const completion = await copilot.complete(req.body);
66
+ res.status(200).json(completion);
67
+ });
68
+
69
+ app.listen(port);
70
+ ```
71
+
72
+ #### Register Copilot with the Monaco Editor
73
+
74
+ Next, register Copilot with the Monaco editor.
75
+
76
+ ```javascript
77
+ import * as monaco from 'monaco-editor';
78
+ import {registerCopilot} from 'monacopilot';
79
+
80
+ const editor = monaco.editor.create(document.getElementById('container'), {
81
+ language: 'javascript',
82
+ });
83
+
84
+ registerCopilot(monaco, editor, {
85
+ endpoint: 'https://api.example.com/copilot',
86
+ language: 'javascript',
87
+ });
88
+ ```
89
+
90
+ ## Configuration Options
91
+
92
+ ### External Context
93
+
94
+ Enhance the accuracy and relevance of Copilot's completions by providing additional code context from your workspace.
95
+
96
+ ```javascript
97
+ registerCopilot(monaco, editor, {
98
+ // ...other options
99
+ externalContext: [
100
+ {
101
+ path: './utils.js',
102
+ content:
103
+ 'export const reverse = (str) => str.split("").reverse().join("")',
104
+ },
105
+ ],
106
+ });
107
+ ```
108
+
109
+ By providing external context, Copilot can offer more intelligent suggestions. For example, if you start typing `const isPalindrome = `, Copilot may suggest using the `reverse` function from `utils.js`.
110
+
111
+ ### Changing the Provider and Model
112
+
113
+ You can specify a different provider and model for completions by setting the `provider` and `model` parameters in the `Copilot` instance.
114
+
115
+ ```javascript
116
+ const copilot = new Copilot(process.env.OPENAI_API_KEY, {
117
+ provider: 'openai',
118
+ model: 'gpt-4o',
119
+ });
120
+ ```
121
+
122
+ The default provider is `groq` and the default model is `llama-3-70b`.
123
+
124
+ | Provider | Model | Description | Avg. Response Time |
125
+ | -------- | ----------- | ------------------------------------------------- | ------------------ |
126
+ | Groq | llama-3-70b | Fast and efficient, suitable for most tasks | <0.5s |
127
+ | OpenAI | gpt-4o-mini | Mini version of gpt-4o, cheaper | 1.5-3s |
128
+ | OpenAI | gpt-4o | Highly intelligent, ideal for complex completions | 1-2s |
129
+
130
+ ### Filename
131
+
132
+ Specify the name of the file being edited to receive more contextually relevant completions.
133
+
134
+ ```javascript
135
+ registerCopilot(monaco, editor, {
136
+ // ...other options
137
+ filename: 'utils.js', // e.g., "index.js", "utils/objects.js"
138
+ });
139
+ ```
140
+
141
+ Now, the completions will be more relevant to utilities.
142
+
143
+ ### Completions for Specific Technologies
144
+
145
+ Enable completions tailored to specific technologies by using the `technologies` option.
146
+
147
+ ```javascript
148
+ registerCopilot(monaco, editor, {
149
+ // ...other options
150
+ technologies: ['react', 'next.js', 'tailwindcss'],
151
+ });
152
+ ```
153
+
154
+ This configuration will provide completions relevant to React, Next.js, and Tailwind CSS.
155
+
156
+ ## Cost Overview
157
+
158
+ The cost of completions is very affordable. See the table below for an estimate of the costs you will need to pay for completions.
159
+
160
+ | Provider | Model | Avg. Cost per 1000 Code Completions |
161
+ | -------- | ----------- | ----------------------------------- |
162
+ | Groq | llama-3-70b | $0.939 |
163
+ | OpenAI | gpt-4o-mini | $0.821 |
164
+ | OpenAI | gpt-4o | $3.46 |
165
+
166
+ > **Note:** Currently, Groq does not implement billing, allowing free usage of their API. During this free period, you will experience minimal rate limiting and some latency in completions. You can opt for Groq's enterprise plan to benefit from increased rate limits and get quick completions without visible latency.
167
+
168
+ ## FAQ
169
+
170
+ ### Is AI Auto Completion Free?
171
+
172
+ You use your own Groq or OpenAI API key for AI auto-completion. The cost of completions is very affordable, and we implement various methods to minimize these costs as much as possible. Costs vary depending on the model you use; see this [cost overview](#cost-overview) for an idea of the cost.
173
+
174
+ ## Contributing
175
+
176
+ For guidelines on contributing, Please read the [contributing guide](https://github.com/arshad-yaseen/monacopilot/blob/main/CONTRIBUTING.md).
177
+
178
+ We welcome contributions from the community to enhance Monacopilot's capabilities and make it even more powerful ❤️
package/build/index.js CHANGED
@@ -1,19 +1,19 @@
1
- "use strict";var S=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var ce=(o,e)=>{for(var t in e)S(o,t,{get:e[t],enumerable:!0})},ue=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of pe(e))!de.call(o,n)&&n!==t&&S(o,n,{get:()=>e[n],enumerable:!(r=me(e,n))||r.enumerable});return o};var Ce=o=>ue(S({},"__esModule",{value:!0}),o);var Me={};ce(Me,{Copilot:()=>M,registerCopilot:()=>se});module.exports=Ce(Me);var F={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini"},_={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"]},k="llama-3-70b",H="groq",U={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions"},q={temperature:.3};var j=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var f=class f{static getInstance(){return f.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logError(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}styleMessage(e,t){let r=this.getTimestamp(),n="Please create an issue on GitHub if the issue persists.",i=80,l="\u2500".repeat(i-2),s=`\u250C${l}\u2510`,a=`\u2514${l}\u2518`,m=((C,le)=>{let ae=C.split(" "),A=[],g="";return ae.forEach($=>{(g+$).length>le&&(A.push(g.trim()),g=""),g+=$+" "}),g.trim()&&A.push(g.trim()),A})(e,i-4),u=[s,...m.map(C=>`\u2502 ${C.padEnd(i-4)} \u2502`),a].join(`
1
+ "use strict";var A=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var pe=Object.prototype.hasOwnProperty;var ce=(o,e)=>{for(var t in e)A(o,t,{get:e[t],enumerable:!0})},de=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of me(e))!pe.call(o,n)&&n!==t&&A(o,n,{get:()=>e[n],enumerable:!(r=ae(e,n))||r.enumerable});return o};var ue=o=>de(A({},"__esModule",{value:!0}),o);var ye={};ce(ye,{Copilot:()=>y,registerCopilot:()=>ie});module.exports=ue(ye);var k={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini"},w={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"]},F="llama-3-70b",H="groq",U={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions"},q={temperature:.3};var j=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var f=class f{static getInstance(){return f.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logError(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}styleMessage(e,t){let r=this.getTimestamp(),n="Please create an issue on GitHub if the issue persists.",i=80,s="\u2500".repeat(i-2),l=`\u250C${s}\u2510`,a=`\u2514${s}\u2518`,m=((C,se)=>{let le=C.split(" "),N=[],g="";return le.forEach(B=>{(g+B).length>se&&(N.push(g.trim()),g=""),g+=B+" "}),g.trim()&&N.push(g.trim()),N})(e,i-4),u=[l,...m.map(C=>`\u2502 ${C.padEnd(i-4)} \u2502`),a].join(`
2
2
  `);return`
3
3
  \x1B[1m\x1B[37m[${r}]\x1B[0m \x1B[31m[${t}]\x1B[0m \x1B[2m${n}\x1B[0m
4
4
  ${u}
5
- `}logError(e,t){console.error(this.styleMessage(t.message,e))}getTimestamp(){return new Date().toISOString()}};f.instance=new f;var w=f;var p=(o,e)=>w.getInstance().handleError(o,e);var V=()=>{},W=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((l,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{l(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},T=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var P=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],G=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),h=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),K=o=>{let e=o.split(`
6
- `);return e[e.length-1].length};var E=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),D=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var Y=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},n=e==="POST"&&t.body?JSON.stringify(t.body):void 0,i=await fetch(o,{method:e,headers:r,body:n,signal:t.signal});if(!i.ok)throw new Error(`${t.error||"Network error"}: ${i.statusText}`);return i.json()},ge=(o,e)=>Y(o,"GET",e),he=(o,e,t)=>Y(o,"POST",{...t,body:e}),x={GET:ge,POST:he};var J=(o,e)=>{let t=P(o,e);return!!t&&!j.has(t)},X=(o,e)=>{let t=G(o,e).trim(),r=h(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var y="<<CURSOR>>",z=o=>o==="javascript"?"latest JavaScript":o,Z=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Q=o=>{let e=z(o.language),t=Z(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},fe=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${T(o)}`:"",r=z(e);return`The code is written${r?` in ${r}`:""}${t}.`},ee=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:l,externalContext:s}=o,a=Z(n),d=e?`the file named "${e}"`:"a larger project",m=`You are tasked with ${a} for a code snippet. The code is part of ${d}.
5
+ `}logError(e,t){console.error(this.styleMessage(t.message,e))}getTimestamp(){return new Date().toISOString()}};f.instance=new f;var _=f;var p=(o,e)=>_.getInstance().handleError(o,e);var V=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((s,l)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=l,t=setTimeout(()=>{s(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},E=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var T=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],W=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),h=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),G=o=>{let e=o.split(`
6
+ `);return e[e.length-1].length+1};var S=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),D=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var Y=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},n=e==="POST"&&t.body?JSON.stringify(t.body):void 0,i=await fetch(o,{method:e,headers:r,body:n,signal:t.signal});if(!i.ok)throw new Error(`${t.error||"Network error"}: ${i.statusText}`);return i.json()},Ce=(o,e)=>Y(o,"GET",e),ge=(o,e,t)=>Y(o,"POST",{...t,body:e}),P={GET:Ce,POST:ge};var K=(o,e)=>{let t=T(o,e);return!!t&&!j.has(t)},J=(o,e)=>{let t=W(o,e).trim(),r=h(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var x="<<CURSOR>>",X=o=>o==="javascript"?"latest JavaScript":o,z=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Z=o=>{let e=X(o.language),t=z(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},he=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${E(o)}`:"",r=X(e);return`The code is written${r?` in ${r}`:""}${t}.`},Q=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:s,externalContext:l}=o,a=z(n),c=e?`the file named "${e}"`:"a larger project",m=`You are tasked with ${a} for a code snippet. The code is part of ${c}.
7
7
 
8
- `;return m+=fe(r,t),m+=`
8
+ `;return m+=he(r,t),m+=`
9
9
 
10
10
  Here are the details about how the completion should be generated:
11
- - The cursor position is marked with '${y}'.
11
+ - The cursor position is marked with '${x}'.
12
12
  - Your completion must start exactly at the cursor position.
13
13
  - Do not repeat any code that appears before or after the cursor.
14
14
  - Ensure your completion does not introduce any syntactical or logical errors.
15
- `,n==="fill-in-the-middle"?m+=` - If filling in the middle, replace '${y}' entirely with your completion.
16
- `:n==="completion"&&(m+=` - If completing the code, start from '${y}' and provide a logical continuation.
15
+ `,n==="fill-in-the-middle"?m+=` - If filling in the middle, replace '${x}' entirely with your completion.
16
+ `:n==="completion"&&(m+=` - If completing the code, start from '${x}' and provide a logical continuation.
17
17
  `),m+=` - Optimize for readability and performance where possible.
18
18
 
19
19
  Remember to output only the completion code without any additional explanation, and do not wrap it in markdown code syntax, such as three backticks (\`\`\`).
@@ -21,13 +21,16 @@ Here are the details about how the completion should be generated:
21
21
  Here's the code snippet for completion:
22
22
 
23
23
  <code>
24
- ${i}${y}${l}
25
- </code>`,s&&s.length>0&&(m+=`
24
+ ${i}${x}${s}
25
+ </code>`,l&&l.length>0&&(m+=`
26
26
 
27
27
  Additional context from related files:
28
28
 
29
- `,m+=s.map(u=>`// Path: ${u.path}
29
+ `,m+=l.map(u=>`// Path: ${u.path}
30
30
  ${u.content}
31
31
  `).join(`
32
- `)),m.endsWith(".")?m:`${m}.`};var Ee="application/json",te=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:l})=>{try{let{completion:s}=await x.POST(e,{completionMetadata:Te({filename:o,position:l,model:i,language:t,technologies:r,externalContext:n})},{headers:{"Content-Type":Ee},error:"Error while fetching completion item"});return s}catch(s){return s instanceof Error&&(s.message==="Cancelled"||s.name==="AbortError")||p(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},Te=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let l=Pe(e,t),s=E(e,t),a=D(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:s,textAfterCursor:a,editorState:{completionMode:l}}},Pe=(o,e)=>{let t=E(o,e),r=D(o,e);return t&&r?"fill-in-the-middle":"completion"};var M=class{constructor(e,t){let r=t?.model||k,n=t?.provider||H;if(!e)throw new Error(`Please provide ${n} API key.`);this.apiKey=e,this.model=r,this.provider=n}async complete({completionMetadata:e}){try{let t=this.createRequestBody(e),r=this.createHeaders(),n=this.getEndpoint(),i=await x.POST(n,t,{headers:r});if(!i.choices?.length)throw new Error("No completion choices received from API");return{completion:i.choices[0].message.content}}catch(t){return{error:p(t,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}getEndpoint(){return U[this.provider]}getModelId(){if(!_[this.provider].includes(this.model))throw new Error(`Model ${this.model} is not supported by ${this.provider} provider. Supported models: ${T(_[this.provider])}`);return F[this.model]}createRequestBody(e){return{...q,model:this.getModelId(),messages:[{role:"system",content:Q(e)},{role:"user",content:ee(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var R=class o{constructor(e,t){this.originalCompletion="";this.formattedCompletion="";this.model=e,this.cursorPosition=t}static create(e,t){return new o(e,t)}setCompletion(e){return this.originalCompletion=e,this.formattedCompletion=e,this}ignoreBlankLines(){return this.formattedCompletion.trimStart()===""&&this.originalCompletion!==`
33
- `&&(this.formattedCompletion=this.formattedCompletion.trim()),this}normalise(e){return e?.trim()??""}removeDuplicatesFromStartOfCompletion(){let e=E(this.cursorPosition,this.model).trim(),t=this.normalise(this.formattedCompletion),r=0,n=Math.min(t.length,e.length);for(let i=1;i<=n;i++){let l=e.slice(-i),s=t.slice(0,i);if(l===s)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.model.getLineCount();e++){let t=this.model.getLineContent(e);if(this.normalise(t)===this.normalise(this.originalCompletion))return this.formattedCompletion="",this}return this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){let e=/^```[\s\S]*?\n([\s\S]*?)\n```$/,t=this.formattedCompletion.match(e);return t&&(this.formattedCompletion=t[1].trim()),this}trimStart(){let e=this.formattedCompletion.search(/\S/);return e>this.cursorPosition.column-1&&(this.formattedCompletion=this.formattedCompletion.slice(e)),this}build(){return this.formattedCompletion}};var I=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!J(this.cursorPosition,this.model)&&!X(this.cursorPosition,this.model)}};var b=class b{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(b.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return h(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};b.MAX_CACHE_SIZE=10;var O=b;var oe=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=K(o),l=P(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(l)?t.lineNumber===e.startLineNumber&&n===0?t.column+i:i:t.column}};function re(o,e,t){return R.create(o,e).setCompletion(t).ignoreBlankLines().removeDuplicatesFromStartOfCompletion().preventDuplicateLines().removeInvalidLineBreaks().removeMarkdownCodeSyntax().trimStart().build()}var c=o=>({items:o,enableForwardStability:!0});var xe=300,ne=W(te,xe),L=new O,ye=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:l})=>{if(!new I(t,e).shouldProvideCompletions())return c([]);let s=L.getCompletionCache(t,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return i(),c(s);if(r.isCancellationRequested||n)return c([]);try{let a=ne({...l,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{ne.cancel()});let d=await a;if(d){let m=re(e,t,d),u=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),C=oe(m,u,t,e);return L.addCompletionCache({completion:m,range:C,textBeforeCursorInLine:h(t,e)}),i(),c([{insertText:m,range:C}])}}catch(a){if(a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return c([]);p(a,"FETCH_COMPLETION_ITEM_ERROR")}return c([])},ie=ye;var v=!1,N=!1,se=(o,e,t)=>{let r=[];try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(l,s,a,d)=>ie({monaco:o,model:l,position:s,token:d,isCompletionAccepted:v,onShowCompletion:()=>N=!0,options:t}),freeInlineCompletions:V});r.push(n);let i=e.onKeyDown(l=>{let s=l.keyCode===o.KeyCode.Tab||l.keyCode===o.KeyCode.RightArrow&&l.metaKey;N&&s?(v=!0,N=!1):v=!1});return r.push(i),{deregister:()=>{r.forEach(l=>l.dispose()),L.clearCompletionCache(),v=!1,N=!1}}}catch(n){return p(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose())}}}};0&&(module.exports={Copilot,registerCopilot});
32
+ `)),m.endsWith(".")?m:`${m}.`};var fe="application/json",ee=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:s})=>{try{let{completion:l}=await P.POST(e,{completionMetadata:Ee({filename:o,position:s,model:i,language:t,technologies:r,externalContext:n})},{headers:{"Content-Type":fe},error:"Error while fetching completion item"});return l}catch(l){return l instanceof Error&&(l.message==="Cancelled"||l.name==="AbortError")||p(l,"FETCH_COMPLETION_ITEM_ERROR"),null}},Ee=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let s=Te(e,t),l=S(e,t),a=D(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:l,textAfterCursor:a,editorState:{completionMode:s}}},Te=(o,e)=>{let t=S(o,e),r=D(o,e);return t&&r?"fill-in-the-middle":"completion"};var y=class{constructor(e,t){let{provider:r,model:n}=t||{};if(r&&!n)throw new Error("You must provide a model when setting a provider");if(n&&!r)throw new Error("You must provide a provider when setting a model");if(this.model=n||F,this.provider=r||H,!w[this.provider].includes(this.model))throw new Error(`Model ${this.model} is not supported by ${this.provider} provider. Supported models: ${E(w[this.provider])}`);if(!e)throw new Error(`Please provide ${this.provider} API key.`);this.apiKey=e}async complete({completionMetadata:e}){try{let t=this.createRequestBody(e),r=this.createHeaders(),n=this.getEndpoint(),i=await P.POST(n,t,{headers:r});if(!i.choices?.length)throw new Error("No completion choices received from API");return{completion:i.choices[0].message.content}}catch(t){return{error:p(t,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}getEndpoint(){return U[this.provider]}getModelId(){return k[this.model]}createRequestBody(e){return{...q,model:this.getModelId(),messages:[{role:"system",content:Z(e)},{role:"user",content:Q(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var M=class o{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new o(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let t=/```[\s\S]*?```/g,r=e,n;for(;(n=t.exec(e))!==null;){let i=n[0],s=i.split(`
33
+ `).slice(1,-1).join(`
34
+ `);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
35
+
36
+ `),this}build(){return this.formattedCompletion}};var I=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!K(this.cursorPosition,this.model)&&!J(this.cursorPosition,this.model)}};var O=class O{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(O.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return h(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};O.MAX_CACHE_SIZE=10;var R=O;var te=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=G(o),s=T(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(s)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function oe(o){return M.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var d=o=>({items:o,enableForwardStability:!0});var Pe=300,re=V(ee,Pe),b=new R,xe=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{if(!new I(t,e).shouldProvideCompletions())return d([]);let l=b.getCompletionCache(t,e).map(a=>({insertText:a.completion,range:a.range}));if(l.length)return i(),d(l);if(r.isCancellationRequested||n)return d([]);try{let a=re({...s,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{re.cancel()});let c=await a;if(c){let m=oe(c),u=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),C=te(m,u,t,e);return b.addCompletionCache({completion:m,range:C,textBeforeCursorInLine:h(t,e)}),i(),d([{insertText:m,range:C}])}}catch(a){if(a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return d([]);p(a,"FETCH_COMPLETION_ITEM_ERROR")}return d([])},ne=xe;var L=!1,v=!1,ie=(o,e,t)=>{let r=[];try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,l,a,c)=>ne({monaco:o,model:s,position:l,token:c,isCompletionAccepted:L,onShowCompletion:()=>v=!0,options:t}),freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let l=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;v&&l?(L=!0,v=!1):L=!1});return r.push(i),{deregister:()=>{r.forEach(s=>s.dispose()),b.clearCompletionCache(),L=!1,v=!1}}}catch(n){return p(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose())}}}};0&&(module.exports={Copilot,registerCopilot});
package/build/index.mjs CHANGED
@@ -1,19 +1,19 @@
1
- var $={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini"},A={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"]},F="llama-3-70b",k="groq",H={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions"},U={temperature:.3};var q=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var f=class f{static getInstance(){return f.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logError(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}styleMessage(e,t){let r=this.getTimestamp(),i="Please create an issue on GitHub if the issue persists.",n=80,l="\u2500".repeat(n-2),s=`\u250C${l}\u2510`,a=`\u2514${l}\u2518`,m=((C,ie)=>{let se=C.split(" "),N=[],g="";return se.forEach(B=>{(g+B).length>ie&&(N.push(g.trim()),g=""),g+=B+" "}),g.trim()&&N.push(g.trim()),N})(e,n-4),u=[s,...m.map(C=>`\u2502 ${C.padEnd(n-4)} \u2502`),a].join(`
1
+ var B={"llama-3-70b":"llama3-70b-8192","gpt-4o":"gpt-4o-2024-08-06","gpt-4o-mini":"gpt-4o-mini"},N={groq:["llama-3-70b"],openai:["gpt-4o","gpt-4o-mini"]},k="llama-3-70b",F="groq",H={groq:"https://api.groq.com/openai/v1/chat/completions",openai:"https://api.openai.com/v1/chat/completions"},U={temperature:.3};var q=new Set(['"',"'","`","{","}","[","]","(",")",","," ",":","."]);var f=class f{static getInstance(){return f.instance}handleError(e,t){let r=this.getErrorDetails(e);return this.logError(t,r),r}getErrorDetails(e){return e instanceof Error?{message:e.message,name:e.name,stack:e.stack,context:e.context}:{message:String(e),name:"UnknownError"}}styleMessage(e,t){let r=this.getTimestamp(),n="Please create an issue on GitHub if the issue persists.",i=80,s="\u2500".repeat(i-2),l=`\u250C${s}\u2510`,a=`\u2514${s}\u2518`,m=((C,ne)=>{let ie=C.split(" "),v=[],g="";return ie.forEach($=>{(g+$).length>ne&&(v.push(g.trim()),g=""),g+=$+" "}),g.trim()&&v.push(g.trim()),v})(e,i-4),u=[l,...m.map(C=>`\u2502 ${C.padEnd(i-4)} \u2502`),a].join(`
2
2
  `);return`
3
- \x1B[1m\x1B[37m[${r}]\x1B[0m \x1B[31m[${t}]\x1B[0m \x1B[2m${i}\x1B[0m
3
+ \x1B[1m\x1B[37m[${r}]\x1B[0m \x1B[31m[${t}]\x1B[0m \x1B[2m${n}\x1B[0m
4
4
  ${u}
5
- `}logError(e,t){console.error(this.styleMessage(t.message,e))}getTimestamp(){return new Date().toISOString()}};f.instance=new f;var S=f;var p=(o,e)=>S.getInstance().handleError(o,e);var j=()=>{},V=(o,e)=>{let t=null,r=null,i=(...n)=>new Promise((l,s)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=s,t=setTimeout(()=>{l(o(...n)),r=null},e)});return i.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},i},T=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var P=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],W=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),h=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),G=o=>{let e=o.split(`
6
- `);return e[e.length-1].length};var E=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),_=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var K=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},i=e==="POST"&&t.body?JSON.stringify(t.body):void 0,n=await fetch(o,{method:e,headers:r,body:i,signal:t.signal});if(!n.ok)throw new Error(`${t.error||"Network error"}: ${n.statusText}`);return n.json()},le=(o,e)=>K(o,"GET",e),ae=(o,e,t)=>K(o,"POST",{...t,body:e}),x={GET:le,POST:ae};var Y=(o,e)=>{let t=P(o,e);return!!t&&!q.has(t)},J=(o,e)=>{let t=W(o,e).trim(),r=h(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var y="<<CURSOR>>",X=o=>o==="javascript"?"latest JavaScript":o,z=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},Z=o=>{let e=X(o.language),t=z(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},me=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${T(o)}`:"",r=X(e);return`The code is written${r?` in ${r}`:""}${t}.`},Q=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:i},textBeforeCursor:n,textAfterCursor:l,externalContext:s}=o,a=z(i),d=e?`the file named "${e}"`:"a larger project",m=`You are tasked with ${a} for a code snippet. The code is part of ${d}.
5
+ `}logError(e,t){console.error(this.styleMessage(t.message,e))}getTimestamp(){return new Date().toISOString()}};f.instance=new f;var A=f;var p=(o,e)=>A.getInstance().handleError(o,e);var j=(o,e)=>{let t=null,r=null,n=(...i)=>new Promise((s,l)=>{t&&(clearTimeout(t),r&&r("Cancelled")),r=l,t=setTimeout(()=>{s(o(...i)),r=null},e)});return n.cancel=()=>{t&&(clearTimeout(t),r&&r("Cancelled"),t=null,r=null)},n},E=o=>!o||o.length===0?"":o.length===1?o[0]:`${o.slice(0,-1).join(", ")} and ${o.slice(-1)}`;var T=(o,e)=>e.getLineContent(o.lineNumber)[o.column-1],V=(o,e)=>e.getLineContent(o.lineNumber).slice(o.column-1),h=(o,e)=>e.getLineContent(o.lineNumber).slice(0,o.column-1),W=o=>{let e=o.split(`
6
+ `);return e[e.length-1].length+1};var w=(o,e)=>e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:o.lineNumber,endColumn:o.column}),_=(o,e)=>e.getValueInRange({startLineNumber:o.lineNumber,startColumn:o.column,endLineNumber:e.getLineCount(),endColumn:e.getLineMaxColumn(e.getLineCount())});var G=async(o,e,t={})=>{let r={"Content-Type":"application/json",...t.headers},n=e==="POST"&&t.body?JSON.stringify(t.body):void 0,i=await fetch(o,{method:e,headers:r,body:n,signal:t.signal});if(!i.ok)throw new Error(`${t.error||"Network error"}: ${i.statusText}`);return i.json()},se=(o,e)=>G(o,"GET",e),le=(o,e,t)=>G(o,"POST",{...t,body:e}),P={GET:se,POST:le};var Y=(o,e)=>{let t=T(o,e);return!!t&&!q.has(t)},K=(o,e)=>{let t=V(o,e).trim(),r=h(o,e).trim();return o.column<=3&&(t!==""||r!=="")};var x="<<CURSOR>>",J=o=>o==="javascript"?"latest JavaScript":o,X=o=>{switch(o){case"fill-in-the-middle":return"filling in the middle of the code";case"completion":return"completing the code"}},z=o=>{let e=J(o.language),t=X(o.editorState.completionMode),r=e?` ${e}`:"";return`You are an advanced AI coding assistant with expertise in ${t} for${r} programming. Your goal is to provide accurate, efficient, and context-aware code completions. Remember, your role is to act as an extension of the developer's thought process, providing intelligent and contextually appropriate code completions.`},ae=(o,e)=>{if(!o?.length&&!e)return"";let t=o?` using ${E(o)}`:"",r=J(e);return`The code is written${r?` in ${r}`:""}${t}.`},Z=o=>{let{filename:e,language:t,technologies:r,editorState:{completionMode:n},textBeforeCursor:i,textAfterCursor:s,externalContext:l}=o,a=X(n),c=e?`the file named "${e}"`:"a larger project",m=`You are tasked with ${a} for a code snippet. The code is part of ${c}.
7
7
 
8
- `;return m+=me(r,t),m+=`
8
+ `;return m+=ae(r,t),m+=`
9
9
 
10
10
  Here are the details about how the completion should be generated:
11
- - The cursor position is marked with '${y}'.
11
+ - The cursor position is marked with '${x}'.
12
12
  - Your completion must start exactly at the cursor position.
13
13
  - Do not repeat any code that appears before or after the cursor.
14
14
  - Ensure your completion does not introduce any syntactical or logical errors.
15
- `,i==="fill-in-the-middle"?m+=` - If filling in the middle, replace '${y}' entirely with your completion.
16
- `:i==="completion"&&(m+=` - If completing the code, start from '${y}' and provide a logical continuation.
15
+ `,n==="fill-in-the-middle"?m+=` - If filling in the middle, replace '${x}' entirely with your completion.
16
+ `:n==="completion"&&(m+=` - If completing the code, start from '${x}' and provide a logical continuation.
17
17
  `),m+=` - Optimize for readability and performance where possible.
18
18
 
19
19
  Remember to output only the completion code without any additional explanation, and do not wrap it in markdown code syntax, such as three backticks (\`\`\`).
@@ -21,13 +21,16 @@ Here are the details about how the completion should be generated:
21
21
  Here's the code snippet for completion:
22
22
 
23
23
  <code>
24
- ${n}${y}${l}
25
- </code>`,s&&s.length>0&&(m+=`
24
+ ${i}${x}${s}
25
+ </code>`,l&&l.length>0&&(m+=`
26
26
 
27
27
  Additional context from related files:
28
28
 
29
- `,m+=s.map(u=>`// Path: ${u.path}
29
+ `,m+=l.map(u=>`// Path: ${u.path}
30
30
  ${u.content}
31
31
  `).join(`
32
- `)),m.endsWith(".")?m:`${m}.`};var pe="application/json",ee=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:i,model:n,position:l})=>{try{let{completion:s}=await x.POST(e,{completionMetadata:de({filename:o,position:l,model:n,language:t,technologies:r,externalContext:i})},{headers:{"Content-Type":pe},error:"Error while fetching completion item"});return s}catch(s){return s instanceof Error&&(s.message==="Cancelled"||s.name==="AbortError")||p(s,"FETCH_COMPLETION_ITEM_ERROR"),null}},de=({filename:o,position:e,model:t,language:r,technologies:i,externalContext:n})=>{let l=ce(e,t),s=E(e,t),a=_(e,t);return{filename:o,language:r,technologies:i,externalContext:n,textBeforeCursor:s,textAfterCursor:a,editorState:{completionMode:l}}},ce=(o,e)=>{let t=E(o,e),r=_(o,e);return t&&r?"fill-in-the-middle":"completion"};var D=class{constructor(e,t){let r=t?.model||F,i=t?.provider||k;if(!e)throw new Error(`Please provide ${i} API key.`);this.apiKey=e,this.model=r,this.provider=i}async complete({completionMetadata:e}){try{let t=this.createRequestBody(e),r=this.createHeaders(),i=this.getEndpoint(),n=await x.POST(i,t,{headers:r});if(!n.choices?.length)throw new Error("No completion choices received from API");return{completion:n.choices[0].message.content}}catch(t){return{error:p(t,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}getEndpoint(){return H[this.provider]}getModelId(){if(!A[this.provider].includes(this.model))throw new Error(`Model ${this.model} is not supported by ${this.provider} provider. Supported models: ${T(A[this.provider])}`);return $[this.model]}createRequestBody(e){return{...U,model:this.getModelId(),messages:[{role:"system",content:Z(e)},{role:"user",content:Q(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var M=class o{constructor(e,t){this.originalCompletion="";this.formattedCompletion="";this.model=e,this.cursorPosition=t}static create(e,t){return new o(e,t)}setCompletion(e){return this.originalCompletion=e,this.formattedCompletion=e,this}ignoreBlankLines(){return this.formattedCompletion.trimStart()===""&&this.originalCompletion!==`
33
- `&&(this.formattedCompletion=this.formattedCompletion.trim()),this}normalise(e){return e?.trim()??""}removeDuplicatesFromStartOfCompletion(){let e=E(this.cursorPosition,this.model).trim(),t=this.normalise(this.formattedCompletion),r=0,i=Math.min(t.length,e.length);for(let n=1;n<=i;n++){let l=e.slice(-n),s=t.slice(0,n);if(l===s)r=n;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.model.getLineCount();e++){let t=this.model.getLineContent(e);if(this.normalise(t)===this.normalise(this.originalCompletion))return this.formattedCompletion="",this}return this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){let e=/^```[\s\S]*?\n([\s\S]*?)\n```$/,t=this.formattedCompletion.match(e);return t&&(this.formattedCompletion=t[1].trim()),this}trimStart(){let e=this.formattedCompletion.search(/\S/);return e>this.cursorPosition.column-1&&(this.formattedCompletion=this.formattedCompletion.slice(e)),this}build(){return this.formattedCompletion}};var R=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!Y(this.cursorPosition,this.model)&&!J(this.cursorPosition,this.model)}};var O=class O{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(O.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let i=r.getValueInRange(e.range);return h(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,i)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};O.MAX_CACHE_SIZE=10;var I=O;var te=(o,e,t,r)=>{let i=(o.match(/\n/g)||[]).length,n=G(o),l=P(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+i,endColumn:o.includes(l)?t.lineNumber===e.startLineNumber&&i===0?t.column+n:n:t.column}};function oe(o,e,t){return M.create(o,e).setCompletion(t).ignoreBlankLines().removeDuplicatesFromStartOfCompletion().preventDuplicateLines().removeInvalidLineBreaks().removeMarkdownCodeSyntax().trimStart().build()}var c=o=>({items:o,enableForwardStability:!0});var ue=300,re=V(ee,ue),b=new I,Ce=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:i,onShowCompletion:n,options:l})=>{if(!new R(t,e).shouldProvideCompletions())return c([]);let s=b.getCompletionCache(t,e).map(a=>({insertText:a.completion,range:a.range}));if(s.length)return n(),c(s);if(r.isCancellationRequested||i)return c([]);try{let a=re({...l,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{re.cancel()});let d=await a;if(d){let m=oe(e,t,d),u=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),C=te(m,u,t,e);return b.addCompletionCache({completion:m,range:C,textBeforeCursorInLine:h(t,e)}),n(),c([{insertText:m,range:C}])}}catch(a){if(a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return c([]);p(a,"FETCH_COMPLETION_ITEM_ERROR")}return c([])},ne=Ce;var L=!1,v=!1,ge=(o,e,t)=>{let r=[];try{let i=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(l,s,a,d)=>ne({monaco:o,model:l,position:s,token:d,isCompletionAccepted:L,onShowCompletion:()=>v=!0,options:t}),freeInlineCompletions:j});r.push(i);let n=e.onKeyDown(l=>{let s=l.keyCode===o.KeyCode.Tab||l.keyCode===o.KeyCode.RightArrow&&l.metaKey;v&&s?(L=!0,v=!1):L=!1});return r.push(n),{deregister:()=>{r.forEach(l=>l.dispose()),b.clearCompletionCache(),L=!1,v=!1}}}catch(i){return p(i,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(n=>n.dispose())}}}};export{D as Copilot,ge as registerCopilot};
32
+ `)),m.endsWith(".")?m:`${m}.`};var me="application/json",Q=async({filename:o,endpoint:e,language:t,technologies:r,externalContext:n,model:i,position:s})=>{try{let{completion:l}=await P.POST(e,{completionMetadata:pe({filename:o,position:s,model:i,language:t,technologies:r,externalContext:n})},{headers:{"Content-Type":me},error:"Error while fetching completion item"});return l}catch(l){return l instanceof Error&&(l.message==="Cancelled"||l.name==="AbortError")||p(l,"FETCH_COMPLETION_ITEM_ERROR"),null}},pe=({filename:o,position:e,model:t,language:r,technologies:n,externalContext:i})=>{let s=ce(e,t),l=w(e,t),a=_(e,t);return{filename:o,language:r,technologies:n,externalContext:i,textBeforeCursor:l,textAfterCursor:a,editorState:{completionMode:s}}},ce=(o,e)=>{let t=w(o,e),r=_(o,e);return t&&r?"fill-in-the-middle":"completion"};var D=class{constructor(e,t){let{provider:r,model:n}=t||{};if(r&&!n)throw new Error("You must provide a model when setting a provider");if(n&&!r)throw new Error("You must provide a provider when setting a model");if(this.model=n||k,this.provider=r||F,!N[this.provider].includes(this.model))throw new Error(`Model ${this.model} is not supported by ${this.provider} provider. Supported models: ${E(N[this.provider])}`);if(!e)throw new Error(`Please provide ${this.provider} API key.`);this.apiKey=e}async complete({completionMetadata:e}){try{let t=this.createRequestBody(e),r=this.createHeaders(),n=this.getEndpoint(),i=await P.POST(n,t,{headers:r});if(!i.choices?.length)throw new Error("No completion choices received from API");return{completion:i.choices[0].message.content}}catch(t){return{error:p(t,"COPILOT_COMPLETION_FETCH_ERROR").message,completion:null}}}getEndpoint(){return H[this.provider]}getModelId(){return B[this.model]}createRequestBody(e){return{...U,model:this.getModelId(),messages:[{role:"system",content:z(e)},{role:"user",content:Z(e)}]}}createHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}};var y=class o{constructor(e){this.formattedCompletion="";this.formattedCompletion=e}static create(e){return new o(e)}setCompletion(e){return this.formattedCompletion=e,this}removeInvalidLineBreaks(){return this.formattedCompletion=this.formattedCompletion.trimEnd(),this}removeMarkdownCodeSyntax(){return this.formattedCompletion=this.removeMarkdownCodeBlocks(this.formattedCompletion),this}removeMarkdownCodeBlocks(e){let t=/```[\s\S]*?```/g,r=e,n;for(;(n=t.exec(e))!==null;){let i=n[0],s=i.split(`
33
+ `).slice(1,-1).join(`
34
+ `);r=r.replace(i,s)}return r.trim()}removeExcessiveNewlines(){return this.formattedCompletion=this.formattedCompletion.replace(/\n{3,}/g,`
35
+
36
+ `),this}build(){return this.formattedCompletion}};var M=class{constructor(e,t){this.cursorPosition=e,this.model=t}shouldProvideCompletions(){return!Y(this.cursorPosition,this.model)&&!K(this.cursorPosition,this.model)}};var R=class R{constructor(){this.cache=[]}getCompletionCache(e,t){return this.cache.filter(r=>this.isCacheItemValid(r,e,t))}addCompletionCache(e){this.cache=[...this.cache.slice(-(R.MAX_CACHE_SIZE-1)),e]}clearCompletionCache(){this.cache=[]}isCacheItemValid(e,t,r){let n=r.getValueInRange(e.range);return h(t,r).startsWith(e.textBeforeCursorInLine)&&this.isPositionValid(e,t,n)}isPositionValid(e,t,r){return e.range.startLineNumber===t.lineNumber&&t.column===e.range.startColumn||e.completion.startsWith(r)&&e.range.startLineNumber===t.lineNumber&&t.column>=e.range.startColumn-r.length&&t.column<=e.range.endColumn}};R.MAX_CACHE_SIZE=10;var I=R;var ee=(o,e,t,r)=>{let n=(o.match(/\n/g)||[]).length,i=W(o),s=T(t,r);return{startLineNumber:t.lineNumber,startColumn:t.column,endLineNumber:t.lineNumber+n,endColumn:o.includes(s)?t.lineNumber===e.startLineNumber&&n===0?t.column+(i-1):i:t.column}};function te(o){return y.create(o).removeMarkdownCodeSyntax().removeExcessiveNewlines().removeInvalidLineBreaks().build()}var d=o=>({items:o,enableForwardStability:!0});var de=300,oe=j(Q,de),O=new I,ue=async({monaco:o,model:e,position:t,token:r,isCompletionAccepted:n,onShowCompletion:i,options:s})=>{if(!new M(t,e).shouldProvideCompletions())return d([]);let l=O.getCompletionCache(t,e).map(a=>({insertText:a.completion,range:a.range}));if(l.length)return i(),d(l);if(r.isCancellationRequested||n)return d([]);try{let a=oe({...s,text:e.getValue(),model:e,position:t});r.onCancellationRequested(()=>{oe.cancel()});let c=await a;if(c){let m=te(c),u=new o.Range(t.lineNumber,t.column,t.lineNumber,t.column),C=ee(m,u,t,e);return O.addCompletionCache({completion:m,range:C,textBeforeCursorInLine:h(t,e)}),i(),d([{insertText:m,range:C}])}}catch(a){if(a instanceof Error&&(a.message==="Cancelled"||a.name==="AbortError"))return d([]);p(a,"FETCH_COMPLETION_ITEM_ERROR")}return d([])},re=ue;var b=!1,L=!1,Ce=(o,e,t)=>{let r=[];try{let n=o.languages.registerInlineCompletionsProvider(t.language,{provideInlineCompletions:(s,l,a,c)=>re({monaco:o,model:s,position:l,token:c,isCompletionAccepted:b,onShowCompletion:()=>L=!0,options:t}),freeInlineCompletions:()=>{}});r.push(n);let i=e.onKeyDown(s=>{let l=s.keyCode===o.KeyCode.Tab||s.keyCode===o.KeyCode.RightArrow&&s.metaKey;L&&l?(b=!0,L=!1):b=!1});return r.push(i),{deregister:()=>{r.forEach(s=>s.dispose()),O.clearCompletionCache(),b=!1,L=!1}}}catch(n){return p(n,"REGISTER_COPILOT_ERROR"),{deregister:()=>{r.forEach(i=>i.dispose())}}}};export{D as Copilot,Ce as registerCopilot};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "monacopilot",
3
- "version": "0.9.15",
4
- "description": "AI auto-completion for Monaco Editor",
3
+ "version": "0.9.17",
4
+ "description": "AI auto-completion plugin for Monaco Editor",
5
5
  "main": "./build/index.js",
6
6
  "module": "./build/index.mjs",
7
7
  "types": "./build/index.d.ts",
@@ -11,12 +11,13 @@
11
11
  "scripts": {
12
12
  "build": "tsup src/index.ts",
13
13
  "dev": "tsup src/index.ts --watch",
14
- "dev:test": "pnpm -C test dev",
14
+ "test": "vitest",
15
+ "dev:test-ui": "pnpm -C tests/ui dev",
15
16
  "type-check": "tsc --noEmit",
16
17
  "lint": "eslint . --ext .ts,.tsx --fix",
17
- "lint:test": "pnpm -C test lint",
18
+ "lint:test-ui": "pnpm -C tests/ui lint",
18
19
  "format": "prettier --write .",
19
- "pre-commit": "pnpm type-check && pnpm lint && pnpm lint:test",
20
+ "pre-commit": "pnpm format && pnpm type-check && pnpm lint && pnpm lint:test-ui",
20
21
  "release": "release-it"
21
22
  },
22
23
  "devDependencies": {
@@ -30,7 +31,8 @@
30
31
  "prettier": "^3.2.5",
31
32
  "release-it": "^17.2.1",
32
33
  "tsup": "^8.0.2",
33
- "typescript": "^5.4.3"
34
+ "typescript": "^5.4.3",
35
+ "vitest": "^2.0.5"
34
36
  },
35
37
  "keywords": [
36
38
  "monaco-editor",