@gratux/sdk 0.0.0-stage → 1.0.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/README.md +193 -2
- package/dist/api-types.d.ts +644 -0
- package/dist/api-types.js +2 -0
- package/dist/host-entry.d.ts +16 -0
- package/dist/host-entry.js +43 -0
- package/dist/host.d.ts +108 -0
- package/dist/host.js +172 -0
- package/dist/index.d.ts +36 -0
- package/dist/index.js +81 -0
- package/dist/language-types.d.ts +135 -0
- package/dist/language-types.js +38 -0
- package/dist/manifest.d.ts +142 -0
- package/dist/manifest.js +45 -0
- package/dist/runtime.d.ts +29 -0
- package/dist/runtime.js +1136 -0
- package/dist/types.d.ts +147 -0
- package/dist/types.js +206 -0
- package/package.json +55 -4
- package/templates/basic/README.md +17 -0
- package/templates/basic/gratux.json +19 -0
- package/templates/basic/src/extension.ts +7 -0
- package/templates/basic/tsconfig.json +15 -0
- package/templates/webview/README.md +17 -0
- package/templates/webview/gratux.json +19 -0
- package/templates/webview/src/extension.ts +43 -0
- package/templates/webview/tsconfig.json +15 -0
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,1136 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildDocument = exports.normaliseProviderResults = exports.invokeProvider = exports.SDK_VERSION = void 0;
|
|
4
|
+
exports.createExtensionApi = createExtensionApi;
|
|
5
|
+
const types_1 = require("./types");
|
|
6
|
+
const host_1 = require("./host");
|
|
7
|
+
Object.defineProperty(exports, "buildDocument", { enumerable: true, get: function () { return host_1.buildDocument; } });
|
|
8
|
+
Object.defineProperty(exports, "invokeProvider", { enumerable: true, get: function () { return host_1.invokeProvider; } });
|
|
9
|
+
Object.defineProperty(exports, "normaliseProviderResults", { enumerable: true, get: function () { return host_1.normaliseProviderResults; } });
|
|
10
|
+
exports.SDK_VERSION = "1.0.0";
|
|
11
|
+
function disposable(fn) {
|
|
12
|
+
let done = false;
|
|
13
|
+
return {
|
|
14
|
+
dispose() {
|
|
15
|
+
if (done)
|
|
16
|
+
return;
|
|
17
|
+
done = true;
|
|
18
|
+
try {
|
|
19
|
+
fn();
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
/* ignore */
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function selectorToJson(selector) {
|
|
28
|
+
if (selector === undefined)
|
|
29
|
+
return undefined;
|
|
30
|
+
return selector;
|
|
31
|
+
}
|
|
32
|
+
function decodeBase64(value) {
|
|
33
|
+
const binary = atob(value);
|
|
34
|
+
const bytes = new Uint8Array(binary.length);
|
|
35
|
+
for (let index = 0; index < binary.length; index++)
|
|
36
|
+
bytes[index] = binary.charCodeAt(index);
|
|
37
|
+
return bytes;
|
|
38
|
+
}
|
|
39
|
+
function createExtensionApi(binding) {
|
|
40
|
+
const transport = binding.transport;
|
|
41
|
+
const state = binding.state;
|
|
42
|
+
const post = (method, params = {}) => transport.post(method, params);
|
|
43
|
+
const sync = (method, params = {}) => transport.callSync(method, params);
|
|
44
|
+
// ------------------------------------------------------------------ events
|
|
45
|
+
const nativeEmitters = new Map();
|
|
46
|
+
const nativeTopics = new Set();
|
|
47
|
+
function nativeEvent(topic) {
|
|
48
|
+
let emitter = nativeEmitters.get(topic);
|
|
49
|
+
if (!emitter) {
|
|
50
|
+
emitter = new types_1.EventEmitter();
|
|
51
|
+
nativeEmitters.set(topic, emitter);
|
|
52
|
+
const bound = emitter;
|
|
53
|
+
if (!nativeTopics.has(topic)) {
|
|
54
|
+
nativeTopics.add(topic);
|
|
55
|
+
if (!state.listeners[topic])
|
|
56
|
+
state.listeners[topic] = [];
|
|
57
|
+
state.listeners[topic].push((payload) => bound.fire(payload));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return emitter.event;
|
|
61
|
+
}
|
|
62
|
+
const onDidExecuteCommand = nativeEvent("commands.didExecute");
|
|
63
|
+
// ------------------------------------------------------------- document
|
|
64
|
+
function snapshot() {
|
|
65
|
+
try {
|
|
66
|
+
const raw = sync("editor.getState");
|
|
67
|
+
if (!raw)
|
|
68
|
+
return undefined;
|
|
69
|
+
state.document = raw;
|
|
70
|
+
state.documentVersion = raw.version;
|
|
71
|
+
return raw;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function documentFrom(snap) {
|
|
78
|
+
const payload = {
|
|
79
|
+
uri: snap.uri,
|
|
80
|
+
path: snap.path,
|
|
81
|
+
languageId: snap.languageId,
|
|
82
|
+
text: snap.text,
|
|
83
|
+
version: snap.version,
|
|
84
|
+
line: 0,
|
|
85
|
+
character: 0,
|
|
86
|
+
offset: 0,
|
|
87
|
+
};
|
|
88
|
+
const base = (0, host_1.buildDocument)(payload);
|
|
89
|
+
const doc = base;
|
|
90
|
+
Object.defineProperty(base, "isDirty", { get: () => snap.dirty, enumerable: true });
|
|
91
|
+
Object.defineProperty(base, "save", {
|
|
92
|
+
value: async () => (await post("editor.save")).saved,
|
|
93
|
+
enumerable: false,
|
|
94
|
+
});
|
|
95
|
+
return doc;
|
|
96
|
+
}
|
|
97
|
+
function activeDocument() {
|
|
98
|
+
const snap = snapshot();
|
|
99
|
+
return snap ? documentFrom(snap) : undefined;
|
|
100
|
+
}
|
|
101
|
+
function currentSnapshot() {
|
|
102
|
+
const snap = snapshot();
|
|
103
|
+
if (!snap) {
|
|
104
|
+
// An empty untitled document keeps editor APIs usable when no file is open.
|
|
105
|
+
return {
|
|
106
|
+
uri: "file:///gratux/untitled",
|
|
107
|
+
path: "",
|
|
108
|
+
languageId: "",
|
|
109
|
+
text: "",
|
|
110
|
+
version: 0,
|
|
111
|
+
dirty: false,
|
|
112
|
+
selections: [],
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
return snap;
|
|
116
|
+
}
|
|
117
|
+
function selectionOf(snap, index = 0) {
|
|
118
|
+
const range = snap.selections[index];
|
|
119
|
+
if (!range)
|
|
120
|
+
return undefined;
|
|
121
|
+
const text = snap.text;
|
|
122
|
+
const start = Math.min(range.anchor, range.head);
|
|
123
|
+
const end = Math.max(range.anchor, range.head);
|
|
124
|
+
return new types_1.Selection((0, types_1.positionAt)(text, range.anchor), (0, types_1.positionAt)(text, range.head));
|
|
125
|
+
}
|
|
126
|
+
function documentPayload(extra = {}) {
|
|
127
|
+
const snap = currentSnapshot();
|
|
128
|
+
return {
|
|
129
|
+
uri: snap.uri,
|
|
130
|
+
path: snap.path,
|
|
131
|
+
languageId: snap.languageId,
|
|
132
|
+
text: snap.text,
|
|
133
|
+
version: snap.version,
|
|
134
|
+
dirty: snap.dirty,
|
|
135
|
+
...extra,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
// ------------------------------------------------------------- commands
|
|
139
|
+
const commands = {
|
|
140
|
+
registerCommand(id, callback, thisArg) {
|
|
141
|
+
if (!id)
|
|
142
|
+
throw new Error("registerCommand: id is required");
|
|
143
|
+
state.commands[id] = thisArg ? callback.bind(thisArg) : callback;
|
|
144
|
+
void post("commands.register", { id });
|
|
145
|
+
return disposable(() => {
|
|
146
|
+
delete state.commands[id];
|
|
147
|
+
void post("commands.unregister", { id });
|
|
148
|
+
});
|
|
149
|
+
},
|
|
150
|
+
executeCommand(id, ...args) {
|
|
151
|
+
return post("commands.execute", { id, args });
|
|
152
|
+
},
|
|
153
|
+
getCommands() {
|
|
154
|
+
return post("commands.list");
|
|
155
|
+
},
|
|
156
|
+
onDidExecuteCommand,
|
|
157
|
+
};
|
|
158
|
+
// --------------------------------------------------------------- window
|
|
159
|
+
function message(severity, messageText, optionsOrItem, ...rest) {
|
|
160
|
+
let options = {};
|
|
161
|
+
let items = rest;
|
|
162
|
+
if (typeof optionsOrItem === "string") {
|
|
163
|
+
items = [optionsOrItem, ...rest];
|
|
164
|
+
}
|
|
165
|
+
else if (optionsOrItem) {
|
|
166
|
+
options = optionsOrItem;
|
|
167
|
+
}
|
|
168
|
+
return post("window.showMessage", {
|
|
169
|
+
severity,
|
|
170
|
+
message: messageText,
|
|
171
|
+
detail: options.detail ?? "",
|
|
172
|
+
modal: options.modal ?? false,
|
|
173
|
+
items,
|
|
174
|
+
}).then((result) => (result && result.index >= 0 ? items[result.index] : undefined));
|
|
175
|
+
}
|
|
176
|
+
const webviewViewEmitters = new Map();
|
|
177
|
+
function viewEmitters(viewId) {
|
|
178
|
+
let entry = webviewViewEmitters.get(viewId);
|
|
179
|
+
if (!entry) {
|
|
180
|
+
entry = {
|
|
181
|
+
message: new types_1.EventEmitter(),
|
|
182
|
+
visibility: new types_1.EventEmitter(),
|
|
183
|
+
dispose: new types_1.EventEmitter(),
|
|
184
|
+
};
|
|
185
|
+
webviewViewEmitters.set(viewId, entry);
|
|
186
|
+
}
|
|
187
|
+
return entry;
|
|
188
|
+
}
|
|
189
|
+
const windowApi = {
|
|
190
|
+
showInformationMessage: ((m, o, ...items) => message("info", m, o, ...items)),
|
|
191
|
+
showWarningMessage: ((m, o, ...items) => message("warning", m, o, ...items)),
|
|
192
|
+
showErrorMessage: ((m, o, ...items) => message("error", m, o, ...items)),
|
|
193
|
+
showQuickPick: (async (items, options) => {
|
|
194
|
+
const normalised = items.map((item) => typeof item === "string" ? { label: item } : item);
|
|
195
|
+
const result = await post("window.showQuickPick", {
|
|
196
|
+
title: options?.title ?? "",
|
|
197
|
+
placeholder: options?.placeHolder ?? "",
|
|
198
|
+
canPickMany: options?.canPickMany ?? false,
|
|
199
|
+
items: normalised.map((item) => ({
|
|
200
|
+
label: item.label,
|
|
201
|
+
description: item.description ?? "",
|
|
202
|
+
detail: item.detail ?? "",
|
|
203
|
+
picked: item.picked ?? false,
|
|
204
|
+
})),
|
|
205
|
+
});
|
|
206
|
+
if (!result)
|
|
207
|
+
return undefined;
|
|
208
|
+
if (options?.canPickMany && Array.isArray(result.indices)) {
|
|
209
|
+
return result.indices.map((i) => normalised[i]).filter(Boolean);
|
|
210
|
+
}
|
|
211
|
+
if (typeof result.index === "number" && result.index >= 0) {
|
|
212
|
+
const picked = normalised[result.index];
|
|
213
|
+
return (picked?.value ?? picked);
|
|
214
|
+
}
|
|
215
|
+
return undefined;
|
|
216
|
+
}),
|
|
217
|
+
showInputBox: (options) => post("window.showInputBox", {
|
|
218
|
+
title: options?.title ?? "",
|
|
219
|
+
prompt: options?.prompt ?? "",
|
|
220
|
+
placeHolder: options?.placeHolder ?? "",
|
|
221
|
+
value: options?.value ?? "",
|
|
222
|
+
password: options?.password ?? false,
|
|
223
|
+
}).then((result) => result?.value),
|
|
224
|
+
showCustomDialog: (options) => post("window.showDialog", {
|
|
225
|
+
title: options.title,
|
|
226
|
+
message: options.message ?? "",
|
|
227
|
+
buttons: options.buttons ?? ["OK"],
|
|
228
|
+
}).then((result) => (result?.index ?? 0)),
|
|
229
|
+
createStatusBarItem(options) {
|
|
230
|
+
const id = `status-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
|
|
231
|
+
let text = "";
|
|
232
|
+
let tooltip;
|
|
233
|
+
let commandId;
|
|
234
|
+
let visible = false;
|
|
235
|
+
const push = (show) => {
|
|
236
|
+
void post("window.setStatusBarItem", {
|
|
237
|
+
id,
|
|
238
|
+
text,
|
|
239
|
+
tooltip: tooltip ?? "",
|
|
240
|
+
command: commandId ?? "",
|
|
241
|
+
alignment: options?.alignment ?? types_1.StatusBarAlignment.Left,
|
|
242
|
+
priority: options?.priority ?? 0,
|
|
243
|
+
visible: show,
|
|
244
|
+
});
|
|
245
|
+
};
|
|
246
|
+
const item = {
|
|
247
|
+
id,
|
|
248
|
+
get text() {
|
|
249
|
+
return text;
|
|
250
|
+
},
|
|
251
|
+
set text(value) {
|
|
252
|
+
text = value ?? "";
|
|
253
|
+
if (visible)
|
|
254
|
+
push(true);
|
|
255
|
+
},
|
|
256
|
+
get tooltip() {
|
|
257
|
+
return tooltip;
|
|
258
|
+
},
|
|
259
|
+
set tooltip(value) {
|
|
260
|
+
tooltip = value;
|
|
261
|
+
if (visible)
|
|
262
|
+
push(true);
|
|
263
|
+
},
|
|
264
|
+
get command() {
|
|
265
|
+
return commandId;
|
|
266
|
+
},
|
|
267
|
+
set command(value) {
|
|
268
|
+
commandId = value;
|
|
269
|
+
if (visible)
|
|
270
|
+
push(true);
|
|
271
|
+
},
|
|
272
|
+
show() {
|
|
273
|
+
visible = true;
|
|
274
|
+
push(true);
|
|
275
|
+
},
|
|
276
|
+
hide() {
|
|
277
|
+
visible = false;
|
|
278
|
+
push(false);
|
|
279
|
+
},
|
|
280
|
+
dispose() {
|
|
281
|
+
void post("window.disposeStatusBarItem", { id });
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
state.statusItems[id] = {};
|
|
285
|
+
return item;
|
|
286
|
+
},
|
|
287
|
+
createOutputChannel(name) {
|
|
288
|
+
const id = `out-${name}`;
|
|
289
|
+
if (!state.outputChannels[id])
|
|
290
|
+
state.outputChannels[id] = [];
|
|
291
|
+
void post("window.createOutputChannel", { id, name });
|
|
292
|
+
return {
|
|
293
|
+
name,
|
|
294
|
+
append(value) {
|
|
295
|
+
state.outputChannels[id].push(value);
|
|
296
|
+
void post("window.appendOutput", { id, text: value, name });
|
|
297
|
+
},
|
|
298
|
+
appendLine(value) {
|
|
299
|
+
this.append(`${value}\n`);
|
|
300
|
+
},
|
|
301
|
+
clear() {
|
|
302
|
+
state.outputChannels[id] = [];
|
|
303
|
+
void post("window.clearOutput", { id });
|
|
304
|
+
},
|
|
305
|
+
show() {
|
|
306
|
+
void post("window.showOutput", { id });
|
|
307
|
+
},
|
|
308
|
+
hide() {
|
|
309
|
+
void post("window.hideOutput", { id });
|
|
310
|
+
},
|
|
311
|
+
dispose() {
|
|
312
|
+
delete state.outputChannels[id];
|
|
313
|
+
void post("window.disposeOutput", { id });
|
|
314
|
+
},
|
|
315
|
+
};
|
|
316
|
+
},
|
|
317
|
+
createLogOutputChannel(name) {
|
|
318
|
+
const channel = this.createOutputChannel(name);
|
|
319
|
+
const stamp = () => new Date().toISOString().substring(11, 23);
|
|
320
|
+
const original = channel.appendLine.bind(channel);
|
|
321
|
+
channel.appendLine = (value) => original(`[${stamp()}] ${value}`);
|
|
322
|
+
channel.info = (m) => channel.appendLine(`INFO ${m}`);
|
|
323
|
+
channel.warn = (m) => channel.appendLine(`WARN ${m}`);
|
|
324
|
+
channel.error = (m) => channel.appendLine(`ERROR ${m instanceof Error ? m.message : m}`);
|
|
325
|
+
channel.debug = (m) => channel.appendLine(`DEBUG ${m}`);
|
|
326
|
+
return channel;
|
|
327
|
+
},
|
|
328
|
+
async withProgress(options, task) {
|
|
329
|
+
const started = await post("window.progressStart", {
|
|
330
|
+
title: options.title,
|
|
331
|
+
cancellable: options.cancellable ?? false,
|
|
332
|
+
});
|
|
333
|
+
const id = started?.id ?? "";
|
|
334
|
+
const cts = new types_1.CancellationTokenSource();
|
|
335
|
+
const cancelListener = nativeEvent("window.progressCancelled")((event) => {
|
|
336
|
+
if (event?.id === id)
|
|
337
|
+
cts.cancel();
|
|
338
|
+
});
|
|
339
|
+
const progress = {
|
|
340
|
+
report(value) {
|
|
341
|
+
void post("window.progressReport", { id, ...value });
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
try {
|
|
345
|
+
return await task(progress, cts.token);
|
|
346
|
+
}
|
|
347
|
+
finally {
|
|
348
|
+
cancelListener.dispose();
|
|
349
|
+
cts.dispose();
|
|
350
|
+
void post("window.progressEnd", { id });
|
|
351
|
+
}
|
|
352
|
+
},
|
|
353
|
+
registerWebviewViewProvider(viewId, provider) {
|
|
354
|
+
state.webviewViews[viewId] = { provider };
|
|
355
|
+
void post("window.registerWebviewViewProvider", { viewId });
|
|
356
|
+
return disposable(() => {
|
|
357
|
+
delete state.webviewViews[viewId];
|
|
358
|
+
void post("window.unregisterWebviewViewProvider", { viewId });
|
|
359
|
+
});
|
|
360
|
+
},
|
|
361
|
+
async showView(viewId) {
|
|
362
|
+
await post("window.showView", { viewId });
|
|
363
|
+
},
|
|
364
|
+
onDidChangeActiveWebviewView: nativeEvent("window.activeWebviewView"),
|
|
365
|
+
};
|
|
366
|
+
/** Called by the host shim when Kotlin opens a contributed view. */
|
|
367
|
+
function resolveWebviewView(viewId, payload) {
|
|
368
|
+
const registration = state.webviewViews[viewId];
|
|
369
|
+
if (!registration)
|
|
370
|
+
return;
|
|
371
|
+
const emitters = viewEmitters(viewId);
|
|
372
|
+
let html = "";
|
|
373
|
+
const webview = {
|
|
374
|
+
get html() {
|
|
375
|
+
return html;
|
|
376
|
+
},
|
|
377
|
+
set html(value) {
|
|
378
|
+
html = value ?? "";
|
|
379
|
+
void post("window.webviewHtml", { viewId, html });
|
|
380
|
+
},
|
|
381
|
+
options: { enableScripts: true },
|
|
382
|
+
postMessage: (message) => post("window.webviewPostMessage", { viewId, message }).then((result) => Boolean(result?.delivered)),
|
|
383
|
+
onDidReceiveMessage: emitters.message.event,
|
|
384
|
+
asWebviewUri: (path) => {
|
|
385
|
+
const extensionPath = String(binding.manifest.__extensionPath ?? "").replace(/[\\/]+$/, "");
|
|
386
|
+
let relativePath = path;
|
|
387
|
+
if (path.startsWith("file:"))
|
|
388
|
+
relativePath = types_1.Uri.parse(path).fsPath;
|
|
389
|
+
if (extensionPath && (relativePath === extensionPath || relativePath.startsWith(`${extensionPath}/`))) {
|
|
390
|
+
relativePath = relativePath.slice(extensionPath.length);
|
|
391
|
+
}
|
|
392
|
+
else if (relativePath.startsWith("/")) {
|
|
393
|
+
throw new Error("Webview resources must be inside the extension package");
|
|
394
|
+
}
|
|
395
|
+
const segments = relativePath.split(/[\\/]+/).filter((segment) => segment && segment !== ".");
|
|
396
|
+
if (segments.some((segment) => segment === "..")) {
|
|
397
|
+
throw new Error("Webview resource path cannot escape the extension package");
|
|
398
|
+
}
|
|
399
|
+
return types_1.Uri.parse(`https://gratux.extension/${encodeURIComponent(binding.extensionId)}/${segments.map(encodeURIComponent).join("/")}`);
|
|
400
|
+
},
|
|
401
|
+
};
|
|
402
|
+
const view = {
|
|
403
|
+
viewId,
|
|
404
|
+
title: payload.title ?? viewId,
|
|
405
|
+
visible: payload.visible ?? true,
|
|
406
|
+
webview,
|
|
407
|
+
show() {
|
|
408
|
+
void post("window.showView", { viewId });
|
|
409
|
+
},
|
|
410
|
+
onDidChangeVisibility: emitters.visibility.event,
|
|
411
|
+
onDidDispose: emitters.dispose.event,
|
|
412
|
+
};
|
|
413
|
+
const subscriptions = [];
|
|
414
|
+
try {
|
|
415
|
+
void Promise.resolve(state.webviewViews[viewId].provider.resolveWebviewView(view, { subscriptions }, {
|
|
416
|
+
isCancellationRequested: false,
|
|
417
|
+
onCancellationRequested: () => disposable(() => { }),
|
|
418
|
+
})).catch((error) => {
|
|
419
|
+
binding.log("error", `view provider ${viewId} failed: ${String(error)}`);
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
catch (error) {
|
|
423
|
+
binding.log("error", `view provider ${viewId} failed: ${String(error)}`);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
// ------------------------------------------------------------- workspace
|
|
427
|
+
function workspaceInfo() {
|
|
428
|
+
try {
|
|
429
|
+
return sync("workspace.info");
|
|
430
|
+
}
|
|
431
|
+
catch {
|
|
432
|
+
return { root: "", name: "", folders: [] };
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
function configuration(section = "") {
|
|
436
|
+
return {
|
|
437
|
+
get(key, defaultValue) {
|
|
438
|
+
const full = section ? `${section}.${key}` : key;
|
|
439
|
+
try {
|
|
440
|
+
const result = sync("config.get", { key: full });
|
|
441
|
+
return (result?.found ? result.value : defaultValue);
|
|
442
|
+
}
|
|
443
|
+
catch {
|
|
444
|
+
return defaultValue;
|
|
445
|
+
}
|
|
446
|
+
},
|
|
447
|
+
has(key) {
|
|
448
|
+
const full = section ? `${section}.${key}` : key;
|
|
449
|
+
try {
|
|
450
|
+
return Boolean(sync("config.get", { key: full })?.found);
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
return false;
|
|
454
|
+
}
|
|
455
|
+
},
|
|
456
|
+
async update(key, value, target = "workspace") {
|
|
457
|
+
const full = section ? `${section}.${key}` : key;
|
|
458
|
+
await post("config.update", { key: full, value, target });
|
|
459
|
+
},
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
const workspace = {
|
|
463
|
+
get rootPath() {
|
|
464
|
+
return workspaceInfo().root;
|
|
465
|
+
},
|
|
466
|
+
get name() {
|
|
467
|
+
return workspaceInfo().name;
|
|
468
|
+
},
|
|
469
|
+
get rootUri() {
|
|
470
|
+
return types_1.Uri.file(workspaceInfo().root);
|
|
471
|
+
},
|
|
472
|
+
get folders() {
|
|
473
|
+
return workspaceInfo().folders.map((folder) => ({
|
|
474
|
+
uri: types_1.Uri.file(folder.path),
|
|
475
|
+
name: folder.name,
|
|
476
|
+
path: folder.path,
|
|
477
|
+
}));
|
|
478
|
+
},
|
|
479
|
+
getInfo() {
|
|
480
|
+
const info = workspaceInfo();
|
|
481
|
+
return {
|
|
482
|
+
root: info.root,
|
|
483
|
+
name: info.name,
|
|
484
|
+
folders: info.folders.map((folder) => ({
|
|
485
|
+
uri: types_1.Uri.file(folder.path),
|
|
486
|
+
name: folder.name,
|
|
487
|
+
path: folder.path,
|
|
488
|
+
})),
|
|
489
|
+
};
|
|
490
|
+
},
|
|
491
|
+
relativePath(path) {
|
|
492
|
+
const root = workspaceInfo().root.replace(/\/+$/, "");
|
|
493
|
+
if (root && path.startsWith(`${root}/`))
|
|
494
|
+
return path.substring(root.length + 1);
|
|
495
|
+
return path;
|
|
496
|
+
},
|
|
497
|
+
findFiles(include, exclude, maxResults = 200) {
|
|
498
|
+
return post("workspace.findFiles", { include, exclude: exclude ?? "", maxResults });
|
|
499
|
+
},
|
|
500
|
+
async openFile(path, options) {
|
|
501
|
+
await post("workspace.openFile", {
|
|
502
|
+
path,
|
|
503
|
+
line: options?.line ?? 0,
|
|
504
|
+
column: options?.column ?? 0,
|
|
505
|
+
preview: options?.preview ?? true,
|
|
506
|
+
});
|
|
507
|
+
},
|
|
508
|
+
async saveAll() {
|
|
509
|
+
const result = await post("workspace.saveAll");
|
|
510
|
+
return Boolean(result?.saved);
|
|
511
|
+
},
|
|
512
|
+
watch(pattern = "**/*", options) {
|
|
513
|
+
const unsubscribers = [];
|
|
514
|
+
const created = new types_1.EventEmitter();
|
|
515
|
+
const changed = new types_1.EventEmitter();
|
|
516
|
+
const deleted = new types_1.EventEmitter();
|
|
517
|
+
let watchId = "";
|
|
518
|
+
void post("workspace.watch", {
|
|
519
|
+
pattern,
|
|
520
|
+
recursive: options?.recursive ?? true,
|
|
521
|
+
}).then((result) => {
|
|
522
|
+
watchId = result?.id ?? "";
|
|
523
|
+
});
|
|
524
|
+
const entry = (topic, emitter) => {
|
|
525
|
+
unsubscribers.push(nativeEvent(topic)((event) => {
|
|
526
|
+
if (!watchId || event?.watchId === watchId)
|
|
527
|
+
emitter.fire({ path: event.path });
|
|
528
|
+
}));
|
|
529
|
+
};
|
|
530
|
+
entry("workspace.fileCreated", created);
|
|
531
|
+
entry("workspace.fileChanged", changed);
|
|
532
|
+
entry("workspace.fileDeleted", deleted);
|
|
533
|
+
const watcher = {
|
|
534
|
+
pattern,
|
|
535
|
+
onDidCreate: created.event,
|
|
536
|
+
onDidChange: changed.event,
|
|
537
|
+
onDidDelete: deleted.event,
|
|
538
|
+
dispose() {
|
|
539
|
+
unsubscribers.forEach((d) => d.dispose());
|
|
540
|
+
if (watchId)
|
|
541
|
+
void post("workspace.unwatch", { id: watchId });
|
|
542
|
+
created.dispose();
|
|
543
|
+
changed.dispose();
|
|
544
|
+
deleted.dispose();
|
|
545
|
+
},
|
|
546
|
+
};
|
|
547
|
+
return watcher;
|
|
548
|
+
},
|
|
549
|
+
getConfiguration(section) {
|
|
550
|
+
return configuration(section);
|
|
551
|
+
},
|
|
552
|
+
onDidChangeWorkspaceFolders: nativeEvent("workspace.didChangeRoot"),
|
|
553
|
+
onDidCreateFiles: nativeEvent("workspace.fileCreated"),
|
|
554
|
+
onDidChangeFiles: nativeEvent("workspace.fileChanged"),
|
|
555
|
+
onDidDeleteFiles: nativeEvent("workspace.fileDeleted"),
|
|
556
|
+
};
|
|
557
|
+
// ------------------------------------------------------------------- fs
|
|
558
|
+
const fs = {
|
|
559
|
+
readFile: (path) => post("fs.readFile", { path }),
|
|
560
|
+
readFileBytes: async (path) => decodeBase64(await post("fs.readFileBytes", { path })),
|
|
561
|
+
readFileSync: (path) => sync("fs.readFileSync", { path }) ?? "",
|
|
562
|
+
writeFile: async (path, content) => {
|
|
563
|
+
await post("fs.writeFile", { path, content });
|
|
564
|
+
},
|
|
565
|
+
writeFileSync: (path, content) => {
|
|
566
|
+
sync("fs.writeFileSync", { path, content });
|
|
567
|
+
},
|
|
568
|
+
exists: (path) => Boolean(sync("fs.exists", { path })),
|
|
569
|
+
stat: (path) => post("fs.stat", { path }),
|
|
570
|
+
statSync: (path) => sync("fs.stat", { path }),
|
|
571
|
+
readDirectory: (path) => post("fs.readDirectory", { path }),
|
|
572
|
+
createDirectory: async (path) => {
|
|
573
|
+
await post("fs.createDirectory", { path });
|
|
574
|
+
},
|
|
575
|
+
delete: async (path, options) => {
|
|
576
|
+
await post("fs.delete", { path, recursive: options?.recursive ?? true });
|
|
577
|
+
},
|
|
578
|
+
rename: async (from, to) => {
|
|
579
|
+
await post("fs.rename", { from, to });
|
|
580
|
+
},
|
|
581
|
+
copy: async (from, to) => {
|
|
582
|
+
await post("fs.copy", { from, to });
|
|
583
|
+
},
|
|
584
|
+
resolveWorkspacePath(relative) {
|
|
585
|
+
const info = workspaceInfo();
|
|
586
|
+
if (!info.root)
|
|
587
|
+
return undefined;
|
|
588
|
+
const parts = [];
|
|
589
|
+
for (const segment of relative.split("/")) {
|
|
590
|
+
if (!segment || segment === ".")
|
|
591
|
+
continue;
|
|
592
|
+
if (segment === "..") {
|
|
593
|
+
if (!parts.length)
|
|
594
|
+
return undefined;
|
|
595
|
+
parts.pop();
|
|
596
|
+
}
|
|
597
|
+
else {
|
|
598
|
+
parts.push(segment);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
const resolved = `${info.root.replace(/\/+$/, "")}/${parts.join("/")}`;
|
|
602
|
+
return resolved.startsWith(info.root) ? resolved : undefined;
|
|
603
|
+
},
|
|
604
|
+
onDidChange: nativeEvent("fs.didChange"),
|
|
605
|
+
};
|
|
606
|
+
// --------------------------------------------------------------- editor
|
|
607
|
+
const editor = {
|
|
608
|
+
getActiveDocument() {
|
|
609
|
+
return activeDocument();
|
|
610
|
+
},
|
|
611
|
+
getActiveEditorState() {
|
|
612
|
+
const snap = snapshot();
|
|
613
|
+
if (!snap)
|
|
614
|
+
return undefined;
|
|
615
|
+
const doc = documentFrom(snap);
|
|
616
|
+
const selections = snap.selections.map((range) => new types_1.Selection((0, types_1.positionAt)(snap.text, range.anchor), (0, types_1.positionAt)(snap.text, range.head)));
|
|
617
|
+
const primary = selections[0];
|
|
618
|
+
if (!primary)
|
|
619
|
+
return undefined;
|
|
620
|
+
return {
|
|
621
|
+
document: doc,
|
|
622
|
+
selection: primary,
|
|
623
|
+
selections,
|
|
624
|
+
visibleRanges: [new types_1.Range(new types_1.Position(0, 0), (0, types_1.positionAt)(snap.text, snap.text.length))],
|
|
625
|
+
};
|
|
626
|
+
},
|
|
627
|
+
getText() {
|
|
628
|
+
return currentSnapshot().text;
|
|
629
|
+
},
|
|
630
|
+
getSelection() {
|
|
631
|
+
return selectionOf(currentSnapshot());
|
|
632
|
+
},
|
|
633
|
+
getSelections() {
|
|
634
|
+
const snap = currentSnapshot();
|
|
635
|
+
return snap.selections.map((range) => new types_1.Selection((0, types_1.positionAt)(snap.text, range.anchor), (0, types_1.positionAt)(snap.text, range.head)));
|
|
636
|
+
},
|
|
637
|
+
insertText: async (text) => (await post("editor.insertText", { text })).ok,
|
|
638
|
+
replaceSelection: async (text) => (await post("editor.replaceSelection", { text })).ok,
|
|
639
|
+
replaceRange: async (start, end, text) => (await post("editor.replaceRange", { start, end, text })).ok,
|
|
640
|
+
applyEdits: async (edits) => (await post("editor.applyEdits", { edits })).ok,
|
|
641
|
+
setSelection: async (start, end) => (await post("editor.setSelection", { anchor: start, head: end ?? start })).ok,
|
|
642
|
+
revealLine: async (line, column) => (await post("editor.revealLine", { line, column: column ?? 1 })).ok,
|
|
643
|
+
save: async () => (await post("editor.save")).saved,
|
|
644
|
+
openFile: async (path, options) => (await post("workspace.openFile", { path, line: options?.line ?? 0, column: options?.column ?? 0 })).ok,
|
|
645
|
+
find: (query, options) => post("editor.find", { query, ...options }),
|
|
646
|
+
replaceAll: (query, replacement, options) => post("editor.replaceAll", { query, replacement, caseSensitive: options?.caseSensitive ?? false })
|
|
647
|
+
.then((r) => r?.count ?? 0),
|
|
648
|
+
setDecorations: async (owner, decorations) => (await post("editor.setDecorations", { owner, decorations })).ok,
|
|
649
|
+
clearDecorations: async (owner) => (await post("editor.clearDecorations", { owner })).ok,
|
|
650
|
+
onDidChangeActiveDocument: nativeEvent("editor.activeChanged"),
|
|
651
|
+
onDidChangeDocument: nativeEvent("editor.documentChanged"),
|
|
652
|
+
onDidChangeSelection: nativeEvent("editor.selectionChanged"),
|
|
653
|
+
onDidSaveDocument: nativeEvent("editor.saved"),
|
|
654
|
+
};
|
|
655
|
+
// ------------------------------------------------------------ languages
|
|
656
|
+
let providerSequence = 0;
|
|
657
|
+
function registerProvider(type, selector, provider, triggerCharacters) {
|
|
658
|
+
const id = ++providerSequence;
|
|
659
|
+
if (!state.providers[type])
|
|
660
|
+
state.providers[type] = [];
|
|
661
|
+
state.providers[type].push({ id, selector, provider, triggerCharacters });
|
|
662
|
+
void post("languages.registerProvider", {
|
|
663
|
+
type,
|
|
664
|
+
selector: selectorToJson(selector),
|
|
665
|
+
triggerCharacters: triggerCharacters ?? [],
|
|
666
|
+
});
|
|
667
|
+
return disposable(() => {
|
|
668
|
+
const list = state.providers[type] ?? [];
|
|
669
|
+
const index = list.findIndex((entry) => entry.id === id);
|
|
670
|
+
if (index >= 0)
|
|
671
|
+
list.splice(index, 1);
|
|
672
|
+
void post("languages.unregisterProvider", { type, id });
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
function makeCollection(name) {
|
|
676
|
+
const store = {};
|
|
677
|
+
return {
|
|
678
|
+
name,
|
|
679
|
+
set(uri, diagnostics) {
|
|
680
|
+
store[uri] = diagnostics;
|
|
681
|
+
void post("languages.setDiagnostics", { uri, diagnostics, owner: name });
|
|
682
|
+
},
|
|
683
|
+
get(uri) {
|
|
684
|
+
return store[uri] ?? [];
|
|
685
|
+
},
|
|
686
|
+
delete(uri) {
|
|
687
|
+
delete store[uri];
|
|
688
|
+
void post("languages.setDiagnostics", { uri, diagnostics: [], owner: name });
|
|
689
|
+
},
|
|
690
|
+
clear() {
|
|
691
|
+
for (const uri of Object.keys(store)) {
|
|
692
|
+
void post("languages.setDiagnostics", { uri, diagnostics: [], owner: name });
|
|
693
|
+
}
|
|
694
|
+
for (const key of Object.keys(store))
|
|
695
|
+
delete store[key];
|
|
696
|
+
},
|
|
697
|
+
dispose() {
|
|
698
|
+
this.clear();
|
|
699
|
+
},
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
const languages = {
|
|
703
|
+
register(language) {
|
|
704
|
+
void post("languages.registerLanguage", language);
|
|
705
|
+
return disposable(() => {
|
|
706
|
+
void post("languages.unregisterLanguage", { id: language.id });
|
|
707
|
+
});
|
|
708
|
+
},
|
|
709
|
+
getLanguages: () => post("languages.list"),
|
|
710
|
+
registerCompletionItemProvider: (selector, provider, triggerCharacters) => registerProvider("completion", selector, provider, triggerCharacters),
|
|
711
|
+
registerHoverProvider: (selector, provider) => registerProvider("hover", selector, provider),
|
|
712
|
+
registerDefinitionProvider: (selector, provider) => registerProvider("definition", selector, provider),
|
|
713
|
+
registerReferenceProvider: (selector, provider) => registerProvider("references", selector, provider),
|
|
714
|
+
registerDocumentFormattingEditProvider: (selector, provider) => registerProvider("formatting", selector, provider),
|
|
715
|
+
registerCodeActionProvider: (selector, provider) => registerProvider("codeActions", selector, provider),
|
|
716
|
+
registerDocumentSymbolProvider: (selector, provider) => registerProvider("symbols", selector, provider),
|
|
717
|
+
createDiagnosticCollection: (name = "diagnostics") => makeCollection(name),
|
|
718
|
+
setDiagnostics(uri, diagnostics) {
|
|
719
|
+
void post("languages.setDiagnostics", { uri, diagnostics, owner: "extension" });
|
|
720
|
+
},
|
|
721
|
+
getDiagnostics: (uri) => post("languages.getDiagnostics", uri ? { uri } : {}),
|
|
722
|
+
// Diagnostic objects are plain JSON; the native side repaints line decorations.
|
|
723
|
+
onDidChangeDiagnostics: nativeEvent("languages.diagnosticsChanged"),
|
|
724
|
+
};
|
|
725
|
+
// ------------------------------------------------------------------ lsp
|
|
726
|
+
const lsp = {
|
|
727
|
+
registerServer(spec) {
|
|
728
|
+
void post("lsp.registerServer", spec);
|
|
729
|
+
return disposable(() => {
|
|
730
|
+
void post("lsp.unregisterServer", { id: spec.id });
|
|
731
|
+
});
|
|
732
|
+
},
|
|
733
|
+
start: (id) => post("lsp.start", { id }).then((r) => Boolean(r?.ok)),
|
|
734
|
+
stop: (id) => post("lsp.stop", { id }).then((r) => Boolean(r?.ok)),
|
|
735
|
+
status: () => post("lsp.status"),
|
|
736
|
+
onDidChangeStatus: nativeEvent("lsp.statusChanged"),
|
|
737
|
+
};
|
|
738
|
+
// ------------------------------------------------------------- terminal
|
|
739
|
+
const terminalObjects = new Map();
|
|
740
|
+
const terminalCloseEmitters = new Map();
|
|
741
|
+
const terminalDataEmitters = new Map();
|
|
742
|
+
const onDidWriteTerminalData = nativeEvent("terminal.data");
|
|
743
|
+
onDidWriteTerminalData((event) => {
|
|
744
|
+
const emitter = terminalDataEmitters.get(event.id);
|
|
745
|
+
emitter?.fire(event.data);
|
|
746
|
+
});
|
|
747
|
+
const onDidCloseTerminal = nativeEvent("terminal.closed");
|
|
748
|
+
onDidCloseTerminal((event) => {
|
|
749
|
+
terminalCloseEmitters.get(event.id)?.fire({ exitCode: event.exitCode });
|
|
750
|
+
terminalDataEmitters.delete(event.id);
|
|
751
|
+
terminalCloseEmitters.delete(event.id);
|
|
752
|
+
terminalObjects.delete(event.id);
|
|
753
|
+
});
|
|
754
|
+
function makeTerminal(info) {
|
|
755
|
+
if (!terminalDataEmitters.has(info.id))
|
|
756
|
+
terminalDataEmitters.set(info.id, new types_1.EventEmitter());
|
|
757
|
+
if (!terminalCloseEmitters.has(info.id))
|
|
758
|
+
terminalCloseEmitters.set(info.id, new types_1.EventEmitter());
|
|
759
|
+
const dataEmitter = terminalDataEmitters.get(info.id);
|
|
760
|
+
const closeEmitter = terminalCloseEmitters.get(info.id);
|
|
761
|
+
const terminal = {
|
|
762
|
+
id: info.id,
|
|
763
|
+
get name() {
|
|
764
|
+
return info.name;
|
|
765
|
+
},
|
|
766
|
+
get cwd() {
|
|
767
|
+
return info.cwd;
|
|
768
|
+
},
|
|
769
|
+
get shellPath() {
|
|
770
|
+
return info.shellPath ?? "";
|
|
771
|
+
},
|
|
772
|
+
get pid() {
|
|
773
|
+
return info.pid;
|
|
774
|
+
},
|
|
775
|
+
sendText: async (text, addNewline = true) => (await post("terminal.sendText", { id: info.id, text, addNewline })).ok,
|
|
776
|
+
execute: async (command) => (await post("terminal.execute", { id: info.id, command })).ok,
|
|
777
|
+
read: () => post("terminal.read", { id: info.id }),
|
|
778
|
+
resize: async (cols, rows) => (await post("terminal.resize", { id: info.id, cols, rows })).ok,
|
|
779
|
+
show: async () => {
|
|
780
|
+
await post("terminal.show", { id: info.id });
|
|
781
|
+
},
|
|
782
|
+
close() {
|
|
783
|
+
void post("terminal.close", { id: info.id });
|
|
784
|
+
},
|
|
785
|
+
onDidWriteData: dataEmitter.event,
|
|
786
|
+
onDidClose: closeEmitter.event,
|
|
787
|
+
};
|
|
788
|
+
terminalObjects.set(info.id, terminal);
|
|
789
|
+
return terminal;
|
|
790
|
+
}
|
|
791
|
+
const terminal = {
|
|
792
|
+
createTerminal(options) {
|
|
793
|
+
const opts = typeof options === "string" ? { name: options } : options ?? {};
|
|
794
|
+
// The native id is returned synchronously so the Terminal object is usable at once.
|
|
795
|
+
const created = sync("terminal.create", {
|
|
796
|
+
name: opts.name ?? "",
|
|
797
|
+
cwd: opts.cwd ?? "",
|
|
798
|
+
env: opts.env ?? {},
|
|
799
|
+
showInPanel: opts.showInPanel ?? false,
|
|
800
|
+
});
|
|
801
|
+
return makeTerminal(created);
|
|
802
|
+
},
|
|
803
|
+
getTerminal(id) {
|
|
804
|
+
return terminalObjects.get(id);
|
|
805
|
+
},
|
|
806
|
+
get terminals() {
|
|
807
|
+
return Array.from(terminalObjects.values());
|
|
808
|
+
},
|
|
809
|
+
list: () => post("terminal.list"),
|
|
810
|
+
getProfiles: () => post("terminal.getProfiles"),
|
|
811
|
+
show: async (id) => {
|
|
812
|
+
await post("terminal.show", id ? { id } : {});
|
|
813
|
+
},
|
|
814
|
+
onDidOpenTerminal: nativeEvent("terminal.opened"),
|
|
815
|
+
onDidCloseTerminal,
|
|
816
|
+
onDidWriteTerminalData,
|
|
817
|
+
get activeTerminal() {
|
|
818
|
+
// The native side keeps track of the tab that is visible.
|
|
819
|
+
const id = sync("terminal.active").id;
|
|
820
|
+
return terminalObjects.get(id);
|
|
821
|
+
},
|
|
822
|
+
};
|
|
823
|
+
// -------------------------------------------------------------- network
|
|
824
|
+
const network = {
|
|
825
|
+
fetch: (request, token) => {
|
|
826
|
+
const options = typeof request === "string" ? { url: request } : request;
|
|
827
|
+
if (token?.isCancellationRequested)
|
|
828
|
+
return Promise.reject(new Error("Request cancelled"));
|
|
829
|
+
return post("network.fetch", options);
|
|
830
|
+
},
|
|
831
|
+
cancelAll: async () => {
|
|
832
|
+
await post("network.cancelAll");
|
|
833
|
+
},
|
|
834
|
+
async createWebSocket(url, protocols) {
|
|
835
|
+
// Permission check happens natively before the socket is created; the
|
|
836
|
+
// WebSocket itself runs in the host's JS engine (real network, no shim).
|
|
837
|
+
await post("network.authorizeWebSocket", { url });
|
|
838
|
+
const open = new types_1.EventEmitter();
|
|
839
|
+
const message = new types_1.EventEmitter();
|
|
840
|
+
const error = new types_1.EventEmitter();
|
|
841
|
+
const close = new types_1.EventEmitter();
|
|
842
|
+
const socket = new WebSocket(url, protocols);
|
|
843
|
+
socket.onopen = () => open.fire();
|
|
844
|
+
socket.onmessage = (event) => message.fire(typeof event.data === "string" ? event.data : String(event.data));
|
|
845
|
+
socket.onerror = () => error.fire({ message: "WebSocket error" });
|
|
846
|
+
socket.onclose = (event) => {
|
|
847
|
+
close.fire({ code: event.code ?? 0, reason: event.reason ?? "" });
|
|
848
|
+
};
|
|
849
|
+
const wrapper = {
|
|
850
|
+
url,
|
|
851
|
+
send: (data) => socket.send(data),
|
|
852
|
+
close: (code, reason) => socket.close(code, reason),
|
|
853
|
+
onOpen: open.event,
|
|
854
|
+
onMessage: message.event,
|
|
855
|
+
onError: error.event,
|
|
856
|
+
onClose: close.event,
|
|
857
|
+
dispose: () => socket.close(),
|
|
858
|
+
};
|
|
859
|
+
return wrapper;
|
|
860
|
+
},
|
|
861
|
+
onDidCompleteRequest: nativeEvent("network.completed"),
|
|
862
|
+
};
|
|
863
|
+
// -------------------------------------------------------------- storage
|
|
864
|
+
function localMemento(prefix) {
|
|
865
|
+
const cache = {};
|
|
866
|
+
return {
|
|
867
|
+
get(key, defaultValue) {
|
|
868
|
+
const full = `${prefix}${key}`;
|
|
869
|
+
if (full in cache)
|
|
870
|
+
return cache[full];
|
|
871
|
+
try {
|
|
872
|
+
const result = sync("storage.get", { key: full });
|
|
873
|
+
if (result?.found) {
|
|
874
|
+
cache[full] = result.value;
|
|
875
|
+
return result.value;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
catch {
|
|
879
|
+
/* ignore */
|
|
880
|
+
}
|
|
881
|
+
return defaultValue;
|
|
882
|
+
},
|
|
883
|
+
update(key, value) {
|
|
884
|
+
cache[`${prefix}${key}`] = value;
|
|
885
|
+
return post("storage.set", { key: `${prefix}${key}`, value }).then(() => undefined);
|
|
886
|
+
},
|
|
887
|
+
keys() {
|
|
888
|
+
return Object.keys(cache).map((entry) => entry.substring(prefix.length));
|
|
889
|
+
},
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
const storage = {
|
|
893
|
+
get(key, defaultValue) {
|
|
894
|
+
try {
|
|
895
|
+
const result = sync("storage.get", { key });
|
|
896
|
+
return (result?.found ? result.value : defaultValue);
|
|
897
|
+
}
|
|
898
|
+
catch {
|
|
899
|
+
return defaultValue;
|
|
900
|
+
}
|
|
901
|
+
},
|
|
902
|
+
async set(key, value) {
|
|
903
|
+
await post("storage.set", { key, value });
|
|
904
|
+
},
|
|
905
|
+
async delete(key) {
|
|
906
|
+
await post("storage.delete", { key });
|
|
907
|
+
},
|
|
908
|
+
keys: () => sync("storage.keys") ?? [],
|
|
909
|
+
async clear() {
|
|
910
|
+
await post("storage.clear");
|
|
911
|
+
},
|
|
912
|
+
secrets: {
|
|
913
|
+
get: (key) => post("storage.secretGet", { key }).then((r) => r?.value),
|
|
914
|
+
set: async (key, value) => {
|
|
915
|
+
await post("storage.secretSet", { key, value });
|
|
916
|
+
},
|
|
917
|
+
delete: async (key) => {
|
|
918
|
+
await post("storage.secretDelete", { key });
|
|
919
|
+
},
|
|
920
|
+
},
|
|
921
|
+
onDidChange: nativeEvent("storage.didChange"),
|
|
922
|
+
};
|
|
923
|
+
// --------------------------------------------------------------- config
|
|
924
|
+
const config = {
|
|
925
|
+
get(key, defaultValue) {
|
|
926
|
+
return configuration().get(key, defaultValue);
|
|
927
|
+
},
|
|
928
|
+
has: (key) => configuration().has(key),
|
|
929
|
+
update: (key, value, target) => configuration().update(key, value, target),
|
|
930
|
+
onDidChange: nativeEvent("config.didChange"),
|
|
931
|
+
getConfiguration: (section) => configuration(section),
|
|
932
|
+
};
|
|
933
|
+
// -------------------------------------------------------------- android
|
|
934
|
+
const android = {
|
|
935
|
+
showNotification: async (options) => (await post("android.showNotification", options)).ok,
|
|
936
|
+
copyToClipboard: async (text) => (await post("android.copyToClipboard", { text })).ok,
|
|
937
|
+
readClipboard: () => post("android.readClipboard"),
|
|
938
|
+
share: async (options) => (await post("android.share", options)).ok,
|
|
939
|
+
openUrl: async (url) => (await post("android.openUrl", { url })).ok,
|
|
940
|
+
getDeviceInfo: () => sync("android.deviceInfo"),
|
|
941
|
+
pickDocument: (options) => post("android.pickDocument", options ?? {}),
|
|
942
|
+
readDocument: (uri) => post("android.readDocument", { uri }),
|
|
943
|
+
readDocumentBytes: async (uri) => decodeBase64(await post("android.readDocumentBytes", { uri })),
|
|
944
|
+
writeDocument: async (uri, content) => (await post("android.writeDocument", { uri, content })).ok,
|
|
945
|
+
onDidChangeLifecycle: nativeEvent("android.lifecycle"),
|
|
946
|
+
};
|
|
947
|
+
// ------------------------------------------------------------------- ai
|
|
948
|
+
const streamHandles = new Map();
|
|
949
|
+
function streamEmitters(requestId) {
|
|
950
|
+
let entry = streamHandles.get(requestId);
|
|
951
|
+
if (!entry) {
|
|
952
|
+
entry = { chunks: new types_1.EventEmitter(), done: new types_1.EventEmitter(), error: new types_1.EventEmitter() };
|
|
953
|
+
streamHandles.set(requestId, entry);
|
|
954
|
+
}
|
|
955
|
+
return entry;
|
|
956
|
+
}
|
|
957
|
+
nativeEvent("ai.chunk")((event) => {
|
|
958
|
+
streamEmitters(event.requestId).chunks.fire(event.chunk);
|
|
959
|
+
});
|
|
960
|
+
nativeEvent("ai.done")((event) => {
|
|
961
|
+
streamEmitters(event.requestId).done.fire(event.text);
|
|
962
|
+
});
|
|
963
|
+
nativeEvent("ai.error")((event) => {
|
|
964
|
+
streamEmitters(event.requestId).error.fire(event.error);
|
|
965
|
+
});
|
|
966
|
+
const ai = {
|
|
967
|
+
getProviders: () => post("ai.providers"),
|
|
968
|
+
request: (options) => post("ai.request", options).then((r) => r.text),
|
|
969
|
+
stream(options) {
|
|
970
|
+
const requestId = options.requestId ?? `ai-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
|
|
971
|
+
const emitters = streamEmitters(requestId);
|
|
972
|
+
if (options.onChunk)
|
|
973
|
+
emitters.chunks.event(options.onChunk);
|
|
974
|
+
if (options.onDone)
|
|
975
|
+
emitters.done.event(options.onDone);
|
|
976
|
+
if (options.onError)
|
|
977
|
+
emitters.error.event(options.onError);
|
|
978
|
+
const textPromise = new Promise((resolve, reject) => {
|
|
979
|
+
emitters.done.event((text) => resolve(text));
|
|
980
|
+
emitters.error.event((error) => reject(new Error(error)));
|
|
981
|
+
});
|
|
982
|
+
void post("ai.stream", { ...options, requestId });
|
|
983
|
+
const handle = {
|
|
984
|
+
requestId,
|
|
985
|
+
text: textPromise,
|
|
986
|
+
dispose: () => {
|
|
987
|
+
void post("ai.cancel", { requestId });
|
|
988
|
+
},
|
|
989
|
+
};
|
|
990
|
+
return handle;
|
|
991
|
+
},
|
|
992
|
+
cancel: (requestId) => post("ai.cancel", { requestId }).then((r) => Boolean(r?.ok)),
|
|
993
|
+
getModels: (provider) => post("ai.models", provider ? { provider } : {}),
|
|
994
|
+
onDidRegisterProvider: nativeEvent("ai.providerRegistered"),
|
|
995
|
+
};
|
|
996
|
+
// ------------------------------------------------------------------ env
|
|
997
|
+
let cachedEnv;
|
|
998
|
+
function envInfo() {
|
|
999
|
+
if (!cachedEnv) {
|
|
1000
|
+
try {
|
|
1001
|
+
cachedEnv = sync("env.info");
|
|
1002
|
+
}
|
|
1003
|
+
catch {
|
|
1004
|
+
cachedEnv = {};
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
return cachedEnv;
|
|
1008
|
+
}
|
|
1009
|
+
const env = {
|
|
1010
|
+
get appVersion() {
|
|
1011
|
+
return String(envInfo().appVersion ?? "");
|
|
1012
|
+
},
|
|
1013
|
+
get sdkVersion() {
|
|
1014
|
+
return String(envInfo().sdkVersion ?? exports.SDK_VERSION);
|
|
1015
|
+
},
|
|
1016
|
+
get platform() {
|
|
1017
|
+
return String(envInfo().platform ?? "android");
|
|
1018
|
+
},
|
|
1019
|
+
get arch() {
|
|
1020
|
+
return String(envInfo().arch ?? "");
|
|
1021
|
+
},
|
|
1022
|
+
get prefix() {
|
|
1023
|
+
return String(envInfo().prefix ?? "");
|
|
1024
|
+
},
|
|
1025
|
+
get home() {
|
|
1026
|
+
return String(envInfo().home ?? "");
|
|
1027
|
+
},
|
|
1028
|
+
get workspace() {
|
|
1029
|
+
return String(envInfo().workspace ?? "");
|
|
1030
|
+
},
|
|
1031
|
+
get isTermuxInstalled() {
|
|
1032
|
+
return Boolean(envInfo().isTermuxInstalled);
|
|
1033
|
+
},
|
|
1034
|
+
};
|
|
1035
|
+
// ----------------------------------------------------------- permissions
|
|
1036
|
+
let granted;
|
|
1037
|
+
const onDidChangePermissions = nativeEvent("permissions.didChange");
|
|
1038
|
+
onDidChangePermissions(() => {
|
|
1039
|
+
granted = undefined;
|
|
1040
|
+
});
|
|
1041
|
+
const permissions = {
|
|
1042
|
+
check(permission) {
|
|
1043
|
+
try {
|
|
1044
|
+
if (!granted) {
|
|
1045
|
+
const info = sync("permissions.list");
|
|
1046
|
+
granted = info?.granted ?? [];
|
|
1047
|
+
}
|
|
1048
|
+
return granted.includes(permission);
|
|
1049
|
+
}
|
|
1050
|
+
catch {
|
|
1051
|
+
return false;
|
|
1052
|
+
}
|
|
1053
|
+
},
|
|
1054
|
+
getGranted() {
|
|
1055
|
+
try {
|
|
1056
|
+
return sync("permissions.list").granted ?? [];
|
|
1057
|
+
}
|
|
1058
|
+
catch {
|
|
1059
|
+
return [];
|
|
1060
|
+
}
|
|
1061
|
+
},
|
|
1062
|
+
getDeclared() {
|
|
1063
|
+
try {
|
|
1064
|
+
return sync("permissions.list").declared ?? [];
|
|
1065
|
+
}
|
|
1066
|
+
catch {
|
|
1067
|
+
return [];
|
|
1068
|
+
}
|
|
1069
|
+
},
|
|
1070
|
+
async request(permission) {
|
|
1071
|
+
const result = await post("permissions.request", { permission });
|
|
1072
|
+
return Boolean(result?.granted);
|
|
1073
|
+
},
|
|
1074
|
+
onDidChange: onDidChangePermissions,
|
|
1075
|
+
};
|
|
1076
|
+
const api = {
|
|
1077
|
+
version: exports.SDK_VERSION,
|
|
1078
|
+
commands,
|
|
1079
|
+
window: windowApi,
|
|
1080
|
+
workspace,
|
|
1081
|
+
fs,
|
|
1082
|
+
editor,
|
|
1083
|
+
languages,
|
|
1084
|
+
lsp,
|
|
1085
|
+
terminal,
|
|
1086
|
+
network,
|
|
1087
|
+
storage,
|
|
1088
|
+
config,
|
|
1089
|
+
android,
|
|
1090
|
+
ai,
|
|
1091
|
+
env,
|
|
1092
|
+
permissions,
|
|
1093
|
+
};
|
|
1094
|
+
// -------------------------------------------------------------- context
|
|
1095
|
+
const extensionPath = String(binding.manifest.__extensionPath ?? "");
|
|
1096
|
+
const logChannel = windowApi.createLogOutputChannel(String(binding.manifest.name ?? binding.extensionId));
|
|
1097
|
+
const globalState = localMemento("global.");
|
|
1098
|
+
const workspaceState = localMemento("workspace.");
|
|
1099
|
+
const context = {
|
|
1100
|
+
extensionId: binding.extensionId,
|
|
1101
|
+
extensionPath,
|
|
1102
|
+
extension: {
|
|
1103
|
+
id: binding.extensionId,
|
|
1104
|
+
packageJSON: binding.manifest,
|
|
1105
|
+
extensionUri: types_1.Uri.file(extensionPath),
|
|
1106
|
+
},
|
|
1107
|
+
subscriptions: [],
|
|
1108
|
+
globalState,
|
|
1109
|
+
workspaceState,
|
|
1110
|
+
storage: localMemento("state."),
|
|
1111
|
+
log: logChannel,
|
|
1112
|
+
asAbsolutePath(relativePath) {
|
|
1113
|
+
return `${extensionPath.replace(/\/+$/, "")}/${relativePath.replace(/^\/+/, "")}`;
|
|
1114
|
+
},
|
|
1115
|
+
};
|
|
1116
|
+
const internal = {
|
|
1117
|
+
resolveWebviewView,
|
|
1118
|
+
deliverViewMessage(viewId, message) {
|
|
1119
|
+
viewEmitters(viewId).message.fire(message);
|
|
1120
|
+
},
|
|
1121
|
+
setViewVisibility(viewId, visible) {
|
|
1122
|
+
viewEmitters(viewId).visibility.fire(visible);
|
|
1123
|
+
},
|
|
1124
|
+
disposeView(viewId) {
|
|
1125
|
+
const emitters = webviewViewEmitters.get(viewId);
|
|
1126
|
+
if (!emitters)
|
|
1127
|
+
return;
|
|
1128
|
+
emitters.dispose.fire();
|
|
1129
|
+
emitters.dispose.dispose();
|
|
1130
|
+
emitters.message.dispose();
|
|
1131
|
+
emitters.visibility.dispose();
|
|
1132
|
+
webviewViewEmitters.delete(viewId);
|
|
1133
|
+
},
|
|
1134
|
+
};
|
|
1135
|
+
return { api, context, internal };
|
|
1136
|
+
}
|