@coze-editor/code-language-typescript 0.1.0-alpha.0fd19e

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 coze-dev
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.
@@ -0,0 +1,615 @@
1
+ // src/index.ts
2
+ import { typescriptLanguage } from "@codemirror/lang-javascript";
3
+
4
+ // src/service.ts
5
+ import { URI } from "vscode-uri";
6
+ import {
7
+ MarkupKind
8
+ } from "vscode-languageserver-types";
9
+ import {
10
+ DiagnosticCategory,
11
+ displayPartsToString
12
+ } from "typescript";
13
+ import mitt from "mitt";
14
+ import { wrap } from "comlink";
15
+ import createFuzzySearch from "@nozbe/microfuzz";
16
+ import {
17
+ MarkerTag,
18
+ textDocumentField
19
+ } from "@coze-editor/code-language-shared";
20
+
21
+ // src/utils.ts
22
+ function tagToString(tag) {
23
+ let tagLabel = `*@${tag.name}*`;
24
+ if (tag.name === "param" && tag.text) {
25
+ const [paramName, ...rest] = tag.text;
26
+ tagLabel += `\`${paramName.text}\``;
27
+ if (rest.length > 0) {
28
+ tagLabel += ` \u2014 ${rest.map((r) => r.text).join(" ")}`;
29
+ }
30
+ } else if (Array.isArray(tag.text)) {
31
+ tagLabel += ` \u2014 ${tag.text.map((r) => r.text).join(" ")}`;
32
+ } else if (tag.text) {
33
+ tagLabel += ` \u2014 ${tag.text}`;
34
+ }
35
+ return tagLabel;
36
+ }
37
+
38
+ // src/as.ts
39
+ import { CompletionItemKind } from "vscode-languageserver-types";
40
+ import { ScriptElementKind } from "typescript";
41
+ function asCompletionItemKind(kind) {
42
+ switch (kind) {
43
+ case ScriptElementKind.primitiveType:
44
+ case ScriptElementKind.keyword:
45
+ return CompletionItemKind.Keyword;
46
+ case ScriptElementKind.constElement:
47
+ case ScriptElementKind.letElement:
48
+ case ScriptElementKind.variableElement:
49
+ case ScriptElementKind.localVariableElement:
50
+ case ScriptElementKind.alias:
51
+ case ScriptElementKind.parameterElement:
52
+ return CompletionItemKind.Variable;
53
+ case ScriptElementKind.memberVariableElement:
54
+ case ScriptElementKind.memberGetAccessorElement:
55
+ case ScriptElementKind.memberSetAccessorElement:
56
+ return CompletionItemKind.Field;
57
+ case ScriptElementKind.functionElement:
58
+ case ScriptElementKind.localFunctionElement:
59
+ return CompletionItemKind.Function;
60
+ case ScriptElementKind.memberFunctionElement:
61
+ case ScriptElementKind.constructSignatureElement:
62
+ case ScriptElementKind.callSignatureElement:
63
+ case ScriptElementKind.indexSignatureElement:
64
+ return CompletionItemKind.Method;
65
+ case ScriptElementKind.enumElement:
66
+ return CompletionItemKind.Enum;
67
+ case ScriptElementKind.enumMemberElement:
68
+ return CompletionItemKind.EnumMember;
69
+ case ScriptElementKind.moduleElement:
70
+ case ScriptElementKind.externalModuleName:
71
+ return CompletionItemKind.Module;
72
+ case ScriptElementKind.classElement:
73
+ case ScriptElementKind.typeElement:
74
+ return CompletionItemKind.Class;
75
+ case ScriptElementKind.interfaceElement:
76
+ return CompletionItemKind.Interface;
77
+ case ScriptElementKind.warning:
78
+ return CompletionItemKind.Text;
79
+ case ScriptElementKind.scriptElement:
80
+ return CompletionItemKind.File;
81
+ case ScriptElementKind.directory:
82
+ return CompletionItemKind.Folder;
83
+ case ScriptElementKind.string:
84
+ return CompletionItemKind.Constant;
85
+ }
86
+ return CompletionItemKind.Property;
87
+ }
88
+
89
+ // src/service.ts
90
+ var identRe = /^[\w$]+$/;
91
+ function isDiagnostic(v) {
92
+ return Boolean(v);
93
+ }
94
+ function isChangeDesc(v) {
95
+ return Boolean(v);
96
+ }
97
+ var TypeScriptLanguageService = class {
98
+ worker = null;
99
+ starting = null;
100
+ _cachedFiles = /* @__PURE__ */ Object.create(null);
101
+ events = mitt();
102
+ async synchronize(paths) {
103
+ await this.starting;
104
+ if (!this.worker) {
105
+ throw new Error("TypeScript LanguageService is not initialized");
106
+ }
107
+ const files = {};
108
+ paths.forEach((path) => {
109
+ files[path] = this._cachedFiles[path] ?? "";
110
+ });
111
+ await this.worker.syncFiles(files);
112
+ return this.worker;
113
+ }
114
+ onTextDocumentDidChange = (ctx) => {
115
+ const { textDocument } = ctx;
116
+ const text = textDocument.getText();
117
+ const uri = URI.parse(textDocument.uri);
118
+ const path = uri.fsPath;
119
+ this._cachedFiles[path] = text;
120
+ };
121
+ doHover = async (ctx) => {
122
+ const { textDocument } = ctx;
123
+ const uri = URI.parse(textDocument.uri);
124
+ const path = uri.fsPath;
125
+ const worker = await this.synchronize([path]);
126
+ const info = await worker.getQuickInfoAtPosition(path, ctx.offset);
127
+ if (!info) {
128
+ return;
129
+ }
130
+ const tags = info.tags ? info.tags.map((tag) => tagToString(tag)).join(" \n\n") : "";
131
+ const contents = displayPartsToString(info.displayParts);
132
+ const documentation = displayPartsToString(info.documentation);
133
+ return {
134
+ kind: MarkupKind.Markdown,
135
+ value: `\`\`\`ts
136
+ ${contents}
137
+ \`\`\`
138
+ ${documentation}${tags ? `
139
+
140
+ ${tags}` : ""}`
141
+ };
142
+ };
143
+ async synchronizeByURI(uri, content) {
144
+ await this.onTextDocumentDidChange({
145
+ textDocument: {
146
+ uri,
147
+ getText() {
148
+ return content;
149
+ }
150
+ }
151
+ });
152
+ }
153
+ async validateByURI(uri) {
154
+ return this.doValidation({
155
+ textDocument: {
156
+ uri
157
+ }
158
+ });
159
+ }
160
+ doValidation = async (ctx) => {
161
+ const { textDocument } = ctx;
162
+ const uri = URI.parse(textDocument.uri);
163
+ const path = uri.fsPath;
164
+ const worker = await this.synchronize([path]);
165
+ try {
166
+ const diagnostics = [
167
+ ...await worker.getSyntacticDiagnostics(path),
168
+ ...await worker.getSemanticDiagnostics(path),
169
+ ...await worker.getSuggestionDiagnostics(path)
170
+ ];
171
+ const categoryToSeverityMap = {
172
+ [DiagnosticCategory.Error]: "error",
173
+ [DiagnosticCategory.Warning]: "warning",
174
+ [DiagnosticCategory.Message]: "info",
175
+ [DiagnosticCategory.Suggestion]: "hint"
176
+ };
177
+ return diagnostics.map((d) => {
178
+ if (typeof d.start !== "number" || !categoryToSeverityMap[d.category]) {
179
+ return;
180
+ }
181
+ const tags = [];
182
+ if (d.reportsUnnecessary) {
183
+ tags.push(MarkerTag.Unnecessary);
184
+ }
185
+ if (d.reportsDeprecated) {
186
+ tags.push(MarkerTag.Deprecated);
187
+ }
188
+ return {
189
+ from: d.start,
190
+ to: d.start + (d.length ?? 0),
191
+ severity: categoryToSeverityMap[d.category],
192
+ message: typeof d.messageText === "string" ? d.messageText : d.messageText.messageText,
193
+ tags
194
+ };
195
+ }).filter((v) => isDiagnostic(v));
196
+ } catch (e) {
197
+ return [];
198
+ }
199
+ };
200
+ doComplete = async (ctx) => {
201
+ const uri = URI.parse(ctx.textDocument.uri);
202
+ const path = uri.fsPath;
203
+ const content = ctx.textDocument.getText();
204
+ const worker = await this.synchronize([path]);
205
+ const result = await worker.getCompletionsAtPosition(path, ctx.offset);
206
+ if (!result) {
207
+ return null;
208
+ }
209
+ const items = result.entries.map((entry) => ({
210
+ label: entry.name,
211
+ kind: asCompletionItemKind(entry.kind)
212
+ }));
213
+ const fuzzySearch = createFuzzySearch(items, {
214
+ key: "label"
215
+ });
216
+ let i = ctx.offset - 1;
217
+ let query = "";
218
+ while (i >= 0) {
219
+ const char = content.slice(i, i + 1);
220
+ if (char === "\n") {
221
+ break;
222
+ }
223
+ if (!identRe.test(char) && i + 1 <= ctx.offset) {
224
+ break;
225
+ }
226
+ i--;
227
+ }
228
+ query = content.slice(i + 1, ctx.offset);
229
+ const charBefore = content.slice(ctx.offset - 1, ctx.offset);
230
+ const triggerCharacters = [".", "'", '"'];
231
+ if (triggerCharacters.includes(charBefore)) {
232
+ return {
233
+ isIncomplete: true,
234
+ items
235
+ };
236
+ }
237
+ return query ? {
238
+ isIncomplete: true,
239
+ items: fuzzySearch(query).map((v) => ({
240
+ ...v.item,
241
+ textEdit: {
242
+ range: {
243
+ start: ctx.textDocument.positionAt(i + 1),
244
+ end: ctx.textDocument.positionAt(ctx.offset)
245
+ },
246
+ newText: v.item.label
247
+ }
248
+ }))
249
+ } : {
250
+ isIncomplete: true,
251
+ items: []
252
+ };
253
+ };
254
+ async resolveCompletionItem(ctx, item) {
255
+ const uri = URI.parse(ctx.textDocument.uri);
256
+ const path = uri.fsPath;
257
+ const worker = await this.synchronize([path]);
258
+ const details = await worker.getCompletionEntryDetails(
259
+ path,
260
+ ctx.offset,
261
+ item.label,
262
+ void 0,
263
+ void 0,
264
+ void 0,
265
+ void 0
266
+ );
267
+ if (!details) {
268
+ return item;
269
+ }
270
+ const documentationString = createDocumentationString(details);
271
+ return {
272
+ label: details.name,
273
+ detail: displayPartsToString(details == null ? void 0 : details.displayParts),
274
+ documentation: documentationString ? {
275
+ kind: MarkupKind.Markdown,
276
+ value: documentationString
277
+ } : void 0
278
+ };
279
+ }
280
+ async format(state, options = {}) {
281
+ const { textDocument, originalRangeFor } = state.field(textDocumentField);
282
+ const uri = URI.parse(textDocument.uri);
283
+ const path = uri.fsPath;
284
+ const worker = await this.synchronize([path]);
285
+ const edits = await worker.getFormattingEditsForDocument(path, {
286
+ indentSize: 2,
287
+ tabSize: 2,
288
+ convertTabsToSpaces: true,
289
+ newLineCharacter: "\n",
290
+ ...options
291
+ });
292
+ if (!edits) {
293
+ return {
294
+ changes: []
295
+ };
296
+ }
297
+ const changes = edits.map((edit) => {
298
+ const range = originalRangeFor({
299
+ from: edit.span.start,
300
+ to: edit.span.start + edit.span.length
301
+ });
302
+ if (range) {
303
+ return {
304
+ ...range,
305
+ insert: edit.newText
306
+ };
307
+ }
308
+ }).filter((v) => isChangeDesc(v));
309
+ return {
310
+ changes
311
+ };
312
+ }
313
+ async getTypeInformation(ctx) {
314
+ const { textDocument } = ctx;
315
+ const uri = URI.parse(textDocument.uri);
316
+ const path = uri.fsPath;
317
+ const worker = await this.synchronize([path]);
318
+ const info = await worker.getTypeInfoAtPosition(path, ctx.offset);
319
+ return info;
320
+ }
321
+ async doSignatureHelp(ctx) {
322
+ const uri = URI.parse(ctx.textDocument.uri);
323
+ const path = uri.fsPath;
324
+ const worker = await this.synchronize([path]);
325
+ const info = await worker.getSignatureHelpItems(path, ctx.offset, {});
326
+ if (!info) {
327
+ return null;
328
+ }
329
+ const ret = {
330
+ activeSignature: info.selectedItemIndex,
331
+ activeParameter: info.argumentIndex,
332
+ signatures: []
333
+ };
334
+ info.items.forEach((item) => {
335
+ const signature = {
336
+ label: "",
337
+ parameters: []
338
+ };
339
+ signature.documentation = {
340
+ kind: MarkupKind.Markdown,
341
+ value: displayPartsToString(item.documentation)
342
+ };
343
+ signature.label += displayPartsToString(item.prefixDisplayParts);
344
+ item.parameters.forEach((p, i, a) => {
345
+ const label = displayPartsToString(p.displayParts);
346
+ const parameter = {
347
+ label,
348
+ documentation: {
349
+ kind: MarkupKind.Markdown,
350
+ value: displayPartsToString(p.documentation)
351
+ }
352
+ };
353
+ signature.label += label;
354
+ signature.parameters.push(parameter);
355
+ if (i < a.length - 1) {
356
+ signature.label += displayPartsToString(item.separatorDisplayParts);
357
+ }
358
+ });
359
+ signature.label += displayPartsToString(item.suffixDisplayParts);
360
+ ret.signatures.push(signature);
361
+ });
362
+ return ret;
363
+ }
364
+ // async findDefinition(ctx) {
365
+ // const uri = URI.parse(ctx.textDocument.uri)
366
+ // const path = uri.fsPath
367
+ // const worker = await this.synchronize([path])
368
+ // const info = await worker.getDefinitionAtPosition(path, ctx.offset)
369
+ // if (!info) {
370
+ // return
371
+ // }
372
+ // return info.map(def => {
373
+ // return {
374
+ // from: def.textSpan.start,
375
+ // to: def.textSpan.start + def.textSpan.length,
376
+ // }
377
+ // })
378
+ // }
379
+ initialize(tsWorker, options) {
380
+ this.worker = wrap(tsWorker);
381
+ this.starting = this.worker.initialize({
382
+ compilerOptions: (options == null ? void 0 : options.compilerOptions) ?? {},
383
+ initialFiles: {
384
+ ...this.extraFiles,
385
+ ...(options == null ? void 0 : options.initialFiles) ?? {}
386
+ }
387
+ });
388
+ }
389
+ extraFiles = /* @__PURE__ */ Object.create(null);
390
+ async addExtraFiles(files) {
391
+ this.extraFiles = Object.assign({}, this.extraFiles, files);
392
+ await this.starting;
393
+ if (this.worker) {
394
+ await this.worker.syncFiles(files);
395
+ this.events.emit("refresh-diagnostics");
396
+ }
397
+ }
398
+ };
399
+ function createDocumentationString(details) {
400
+ let documentationString = displayPartsToString(details.documentation);
401
+ if (details.tags) {
402
+ for (const tag of details.tags) {
403
+ documentationString += `
404
+
405
+ ${tagToString(tag)}`;
406
+ }
407
+ }
408
+ return documentationString;
409
+ }
410
+ var typescriptLanguageService = new TypeScriptLanguageService();
411
+
412
+ // src/extensions/index.ts
413
+ import { textDocumentField as textDocumentField2 } from "@coze-editor/code-language-shared";
414
+
415
+ // src/extensions/type-information.ts
416
+ import {
417
+ EditorView,
418
+ hoverTooltip,
419
+ ViewPlugin
420
+ } from "@codemirror/view";
421
+ import {
422
+ StateField,
423
+ StateEffect,
424
+ Facet
425
+ } from "@codemirror/state";
426
+ var cmdKeyPressedState = StateField.define({
427
+ create: () => false,
428
+ update: (value, tr) => {
429
+ for (const effect of tr.effects) {
430
+ if (effect.is(setCmdKeyPressedEffect)) {
431
+ return effect.value;
432
+ }
433
+ }
434
+ return value;
435
+ }
436
+ });
437
+ var setCmdKeyPressedEffect = StateEffect.define();
438
+ var cmdKeyEventPlugin = ViewPlugin.fromClass(
439
+ class {
440
+ dispose;
441
+ constructor(view) {
442
+ const onKeyDown = (event) => {
443
+ if (event.metaKey && !view.state.field(cmdKeyPressedState)) {
444
+ view.dispatch({ effects: setCmdKeyPressedEffect.of(true) });
445
+ }
446
+ };
447
+ const onKeyUp = (event) => {
448
+ if (!event.metaKey && view.state.field(cmdKeyPressedState)) {
449
+ view.dispatch({ effects: setCmdKeyPressedEffect.of(false) });
450
+ }
451
+ };
452
+ const onBlur = () => {
453
+ if (view.state.field(cmdKeyPressedState)) {
454
+ view.dispatch({ effects: setCmdKeyPressedEffect.of(false) });
455
+ }
456
+ };
457
+ window.addEventListener("keydown", onKeyDown);
458
+ window.addEventListener("keyup", onKeyUp);
459
+ window.addEventListener("blur", onBlur);
460
+ this.dispose = () => {
461
+ window.removeEventListener("keydown", onKeyDown);
462
+ window.removeEventListener("keyup", onKeyUp);
463
+ window.removeEventListener("blur", onBlur);
464
+ };
465
+ }
466
+ destroy() {
467
+ this.dispose();
468
+ }
469
+ }
470
+ );
471
+ var getTypeInformationFacet = Facet.define({
472
+ combine(values) {
473
+ return values[values.length - 1];
474
+ }
475
+ });
476
+ var cmdHoverTooltipSource = async (view, pos, side) => {
477
+ const word = view.state.wordAt(pos);
478
+ if (!word) {
479
+ return null;
480
+ }
481
+ if (!view.state.facet(getTypeInformationFacet)) {
482
+ return null;
483
+ }
484
+ const doTypeInfoFn = view.state.facet(getTypeInformationFacet);
485
+ const info = await (doTypeInfoFn == null ? void 0 : doTypeInfoFn(view.state, word.from));
486
+ if (!info) {
487
+ return null;
488
+ }
489
+ return {
490
+ pos: word.from,
491
+ end: word.to,
492
+ above: true,
493
+ create() {
494
+ var _a;
495
+ const dom = document.createElement("div");
496
+ dom.className = "cm-type-tooltip";
497
+ const cmdPressed = view.state.field(cmdKeyPressedState, false);
498
+ dom.style.display = cmdPressed ? "block" : "none";
499
+ if ((_a = info == null ? void 0 : info.properties) == null ? void 0 : _a.length) {
500
+ const propsDiv = document.createElement("div");
501
+ propsDiv.className = "cm-type-tooltip-properties";
502
+ const propsHeader = document.createElement("div");
503
+ propsHeader.className = "cm-type-tooltip-props-header";
504
+ propsHeader.textContent = "Properties:";
505
+ propsDiv.appendChild(propsHeader);
506
+ const propsList = document.createElement("ul");
507
+ propsList.className = "cm-type-tooltip-props-list";
508
+ info.properties.forEach((prop) => {
509
+ if (prop && typeof prop.name === "string" && typeof prop.type === "string") {
510
+ const propItem = document.createElement("li");
511
+ propItem.className = "cm-type-tooltip-prop-item";
512
+ const propName = document.createElement("span");
513
+ propName.className = "cm-type-tooltip-prop-name";
514
+ propName.textContent = prop.name;
515
+ propItem.appendChild(propName);
516
+ const separator = document.createTextNode(": ");
517
+ propItem.appendChild(separator);
518
+ const propType = document.createElement("span");
519
+ propType.className = "cm-type-tooltip-prop-type";
520
+ propType.textContent = prop.type;
521
+ propItem.appendChild(propType);
522
+ propsList.appendChild(propItem);
523
+ }
524
+ });
525
+ propsDiv.appendChild(propsList);
526
+ dom.appendChild(propsDiv);
527
+ }
528
+ return {
529
+ dom,
530
+ update(update) {
531
+ for (const tr of update.transactions) {
532
+ for (const effect of tr.effects) {
533
+ if (effect.is(setCmdKeyPressedEffect)) {
534
+ const show = effect.value;
535
+ dom.style.display = show ? "block" : "none";
536
+ break;
537
+ }
538
+ }
539
+ }
540
+ }
541
+ };
542
+ }
543
+ };
544
+ };
545
+ var tooltipTheme = EditorView.theme({
546
+ ".cm-tooltip .cm-type-tooltip": {
547
+ padding: "0 10px 6px 10px",
548
+ maxWidth: "350px"
549
+ },
550
+ ".cm-type-tooltip-properties": {
551
+ paddingTop: "6px"
552
+ },
553
+ ".cm-type-tooltip-props-header": {
554
+ fontWeight: "bold",
555
+ marginBottom: "4px",
556
+ color: "#E06C75"
557
+ },
558
+ ".cm-type-tooltip-props-list": {
559
+ listStyle: "none",
560
+ margin: "0"
561
+ },
562
+ ".cm-type-tooltip-prop-item": {
563
+ marginBottom: "3px"
564
+ },
565
+ ".cm-type-tooltip-prop-name": {
566
+ color: "#E5C07B"
567
+ },
568
+ ".cm-type-tooltip-prop-type": {
569
+ color: "#ABB2BF"
570
+ }
571
+ });
572
+ function typeInformation(getTypeInformation) {
573
+ return [
574
+ getTypeInformationFacet.of(getTypeInformation),
575
+ tooltipTheme,
576
+ cmdKeyPressedState,
577
+ cmdKeyEventPlugin,
578
+ hoverTooltip(cmdHoverTooltipSource, {
579
+ hoverTime: 300
580
+ })
581
+ ];
582
+ }
583
+ var type_information_default = typeInformation;
584
+
585
+ // src/extensions/index.ts
586
+ var extensions = [
587
+ type_information_default(async (state, pos) => {
588
+ const { textDocument, generatedRangeFor } = state.field(textDocumentField2);
589
+ const range = generatedRangeFor({ from: pos, to: pos });
590
+ const offset = range == null ? void 0 : range.from;
591
+ if (typeof offset !== "number") {
592
+ return null;
593
+ }
594
+ const result = await typescriptLanguageService.getTypeInformation({
595
+ textDocument,
596
+ offset
597
+ });
598
+ return result;
599
+ })
600
+ ];
601
+ var extensions_default = extensions;
602
+
603
+ // src/index.ts
604
+ var typescript = {
605
+ language: typescriptLanguage,
606
+ languageService: typescriptLanguageService,
607
+ extensions: extensions_default
608
+ };
609
+ export {
610
+ TypeScriptLanguageService,
611
+ typescript,
612
+ typescriptLanguage,
613
+ typescriptLanguageService
614
+ };
615
+ //# sourceMappingURL=index.js.map