Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/platform/image/node/imageServiceImpl.ts
13401 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import { RequestType } from '@vscode/copilot-api';
7
import { URI } from '../../../util/vs/base/common/uri';
8
import { ICAPIClientService } from '../../endpoint/common/capiClient';
9
import { IImageService } from '../common/imageService';
10
11
export class ImageServiceImpl implements IImageService {
12
declare readonly _serviceBrand: undefined;
13
14
constructor(
15
@ICAPIClientService private readonly capiClient: ICAPIClientService,
16
) { }
17
18
async uploadChatImageAttachment(binaryData: Uint8Array, name: string, mimeType: string | undefined, token: string | undefined): Promise<URI> {
19
if (!mimeType || !token) {
20
throw new Error('Missing required mimeType or token for image upload');
21
}
22
23
const sanitizedName = name.replace(/[^a-zA-Z0-9._-]/g, '');
24
let uploadName = sanitizedName;
25
26
// can catch unexpected types like "IMAGE/JPEG", "image/svg+xml", or "image/png; charset=UTF-8"
27
const subtypeMatch = mimeType.toLowerCase().match(/^[^\/]+\/([^+;]+)/);
28
const subtype = subtypeMatch?.[1];
29
30
// add the extension if it is missing.
31
if (subtype && !uploadName.toLowerCase().endsWith(`.${subtype}`)) {
32
uploadName = `${uploadName}.${subtype}`;
33
}
34
35
try {
36
const response = await this.capiClient.makeRequest<Response>({
37
method: 'POST',
38
body: binaryData,
39
headers: {
40
'Content-Type': 'application/octet-stream',
41
Authorization: `Bearer ${token}`,
42
}
43
}, { type: RequestType.ChatAttachmentUpload, uploadName, mimeType });
44
if (!response.ok) {
45
throw new Error(`Image upload failed: ${response.status} ${response.statusText}`);
46
}
47
const result = await response.json() as { url: string };
48
return URI.parse(result.url);
49
} catch (error) {
50
throw new Error(`Error uploading image: ${error}`);
51
}
52
}
53
54
async resizeImage(data: Uint8Array, mimeType: string): Promise<{ data: Uint8Array; mimeType: string }> {
55
return { data, mimeType };
56
}
57
}
58
59