@cascadetui/core 0.1.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.
Files changed (129) hide show
  1. package/3d/SpriteResourceManager.d.ts +74 -0
  2. package/3d/SpriteUtils.d.ts +13 -0
  3. package/3d/TextureUtils.d.ts +24 -0
  4. package/3d/ThreeRenderable.d.ts +40 -0
  5. package/3d/WGPURenderer.d.ts +61 -0
  6. package/3d/animation/ExplodingSpriteEffect.d.ts +71 -0
  7. package/3d/animation/PhysicsExplodingSpriteEffect.d.ts +76 -0
  8. package/3d/animation/SpriteAnimator.d.ts +124 -0
  9. package/3d/animation/SpriteParticleGenerator.d.ts +62 -0
  10. package/3d/canvas.d.ts +44 -0
  11. package/3d/index.d.ts +12 -0
  12. package/3d/physics/PlanckPhysicsAdapter.d.ts +19 -0
  13. package/3d/physics/RapierPhysicsAdapter.d.ts +19 -0
  14. package/3d/physics/physics-interface.d.ts +27 -0
  15. package/3d.d.ts +2 -0
  16. package/3d.js +34041 -0
  17. package/3d.js.map +155 -0
  18. package/LICENSE +21 -0
  19. package/NativeSpanFeed.d.ts +41 -0
  20. package/README.md +62 -0
  21. package/Renderable.d.ts +334 -0
  22. package/animation/Timeline.d.ts +126 -0
  23. package/ansi.d.ts +13 -0
  24. package/assets/javascript/highlights.scm +205 -0
  25. package/assets/javascript/tree-sitter-javascript.wasm +0 -0
  26. package/assets/markdown/highlights.scm +150 -0
  27. package/assets/markdown/injections.scm +27 -0
  28. package/assets/markdown/tree-sitter-markdown.wasm +0 -0
  29. package/assets/markdown_inline/highlights.scm +115 -0
  30. package/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
  31. package/assets/typescript/highlights.scm +604 -0
  32. package/assets/typescript/tree-sitter-typescript.wasm +0 -0
  33. package/assets/zig/highlights.scm +284 -0
  34. package/assets/zig/tree-sitter-zig.wasm +0 -0
  35. package/buffer.d.ts +107 -0
  36. package/console.d.ts +140 -0
  37. package/edit-buffer.d.ts +98 -0
  38. package/editor-view.d.ts +73 -0
  39. package/index-jx194wn1.js +17723 -0
  40. package/index-jx194wn1.js.map +61 -0
  41. package/index.d.ts +18 -0
  42. package/index.js +12210 -0
  43. package/index.js.map +49 -0
  44. package/lib/KeyHandler.d.ts +61 -0
  45. package/lib/RGBA.d.ts +25 -0
  46. package/lib/ascii.font.d.ts +508 -0
  47. package/lib/border.d.ts +49 -0
  48. package/lib/bunfs.d.ts +7 -0
  49. package/lib/clipboard.d.ts +29 -0
  50. package/lib/data-paths.d.ts +26 -0
  51. package/lib/debounce.d.ts +42 -0
  52. package/lib/env.d.ts +42 -0
  53. package/lib/extmarks-history.d.ts +17 -0
  54. package/lib/extmarks.d.ts +89 -0
  55. package/lib/hast-styled-text.d.ts +17 -0
  56. package/lib/index.d.ts +18 -0
  57. package/lib/keymapping.d.ts +25 -0
  58. package/lib/objects-in-viewport.d.ts +24 -0
  59. package/lib/output.capture.d.ts +24 -0
  60. package/lib/parse.keypress-kitty.d.ts +2 -0
  61. package/lib/parse.keypress.d.ts +26 -0
  62. package/lib/parse.mouse.d.ts +30 -0
  63. package/lib/queue.d.ts +15 -0
  64. package/lib/renderable.validations.d.ts +12 -0
  65. package/lib/scroll-acceleration.d.ts +43 -0
  66. package/lib/selection.d.ts +63 -0
  67. package/lib/singleton.d.ts +7 -0
  68. package/lib/stdin-buffer.d.ts +44 -0
  69. package/lib/styled-text.d.ts +63 -0
  70. package/lib/terminal-capability-detection.d.ts +30 -0
  71. package/lib/terminal-palette.d.ts +43 -0
  72. package/lib/tree-sitter/assets/update.d.ts +11 -0
  73. package/lib/tree-sitter/client.d.ts +47 -0
  74. package/lib/tree-sitter/default-parsers.d.ts +2 -0
  75. package/lib/tree-sitter/download-utils.d.ts +21 -0
  76. package/lib/tree-sitter/index.d.ts +8 -0
  77. package/lib/tree-sitter/parser.worker.d.ts +1 -0
  78. package/lib/tree-sitter/parsers-config.d.ts +38 -0
  79. package/lib/tree-sitter/resolve-ft.d.ts +2 -0
  80. package/lib/tree-sitter/types.d.ts +81 -0
  81. package/lib/tree-sitter-styled-text.d.ts +14 -0
  82. package/lib/validate-dir-name.d.ts +1 -0
  83. package/lib/yoga.options.d.ts +32 -0
  84. package/package.json +67 -0
  85. package/parser.worker.js +878 -0
  86. package/parser.worker.js.map +12 -0
  87. package/post/filters.d.ts +105 -0
  88. package/renderables/ASCIIFont.d.ts +52 -0
  89. package/renderables/Box.d.ts +72 -0
  90. package/renderables/Code.d.ts +66 -0
  91. package/renderables/Diff.d.ts +135 -0
  92. package/renderables/EditBufferRenderable.d.ts +162 -0
  93. package/renderables/FrameBuffer.d.ts +16 -0
  94. package/renderables/Input.d.ts +67 -0
  95. package/renderables/LineNumberRenderable.d.ts +74 -0
  96. package/renderables/Markdown.d.ts +150 -0
  97. package/renderables/ScrollBar.d.ts +77 -0
  98. package/renderables/ScrollBox.d.ts +116 -0
  99. package/renderables/Select.d.ts +115 -0
  100. package/renderables/Slider.d.ts +44 -0
  101. package/renderables/TabSelect.d.ts +96 -0
  102. package/renderables/Text.d.ts +36 -0
  103. package/renderables/TextBufferRenderable.d.ts +105 -0
  104. package/renderables/TextNode.d.ts +91 -0
  105. package/renderables/TextTable.d.ts +130 -0
  106. package/renderables/Textarea.d.ts +114 -0
  107. package/renderables/__tests__/renderable-test-utils.d.ts +7 -0
  108. package/renderables/composition/VRenderable.d.ts +16 -0
  109. package/renderables/composition/constructs.d.ts +35 -0
  110. package/renderables/composition/vnode.d.ts +46 -0
  111. package/renderables/index.d.ts +21 -0
  112. package/renderables/markdown-parser.d.ts +10 -0
  113. package/renderer.d.ts +382 -0
  114. package/syntax-style.d.ts +54 -0
  115. package/testing/mock-keys.d.ts +80 -0
  116. package/testing/mock-mouse.d.ts +38 -0
  117. package/testing/mock-tree-sitter-client.d.ts +23 -0
  118. package/testing/spy.d.ts +7 -0
  119. package/testing/test-recorder.d.ts +61 -0
  120. package/testing/test-renderer.d.ts +23 -0
  121. package/testing.d.ts +6 -0
  122. package/testing.js +670 -0
  123. package/testing.js.map +15 -0
  124. package/text-buffer-view.d.ts +42 -0
  125. package/text-buffer.d.ts +67 -0
  126. package/types.d.ts +126 -0
  127. package/utils.d.ts +14 -0
  128. package/zig-structs.d.ts +155 -0
  129. package/zig.d.ts +351 -0
@@ -0,0 +1,878 @@
1
+ // @bun
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __toESM = (mod, isNodeMode, target) => {
8
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
9
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
+ for (let key of __getOwnPropNames(mod))
11
+ if (!__hasOwnProp.call(to, key))
12
+ __defProp(to, key, {
13
+ get: () => mod[key],
14
+ enumerable: true
15
+ });
16
+ return to;
17
+ };
18
+ var __require = import.meta.require;
19
+
20
+ // src/lib/tree-sitter/parser.worker.ts
21
+ import { Parser, Query, Language } from "web-tree-sitter";
22
+ import { mkdir as mkdir2 } from "fs/promises";
23
+ import * as path2 from "path";
24
+
25
+ // src/lib/tree-sitter/download-utils.ts
26
+ import { mkdir, writeFile } from "fs/promises";
27
+ import * as path from "path";
28
+
29
+ class DownloadUtils {
30
+ static hashUrl(url) {
31
+ let hash = 0;
32
+ for (let i = 0;i < url.length; i++) {
33
+ const char = url.charCodeAt(i);
34
+ hash = (hash << 5) - hash + char;
35
+ hash = hash & hash;
36
+ }
37
+ return Math.abs(hash).toString(16);
38
+ }
39
+ static async downloadOrLoad(source, cacheDir, cacheSubdir, fileExtension, useHashForCache = true, filetype) {
40
+ const isUrl = source.startsWith("http://") || source.startsWith("https://");
41
+ if (isUrl) {
42
+ let cacheFileName;
43
+ if (useHashForCache) {
44
+ const hash = this.hashUrl(source);
45
+ cacheFileName = filetype ? `${filetype}-${hash}${fileExtension}` : `${hash}${fileExtension}`;
46
+ } else {
47
+ cacheFileName = path.basename(source);
48
+ }
49
+ const cacheFile = path.join(cacheDir, cacheSubdir, cacheFileName);
50
+ await mkdir(path.dirname(cacheFile), { recursive: true });
51
+ try {
52
+ const cachedContent = await Bun.file(cacheFile).arrayBuffer();
53
+ if (cachedContent.byteLength > 0) {
54
+ console.log(`Loaded from cache: ${cacheFile} (${source})`);
55
+ return { content: cachedContent, filePath: cacheFile };
56
+ }
57
+ } catch (error) {}
58
+ try {
59
+ console.log(`Downloading from URL: ${source}`);
60
+ const response = await fetch(source);
61
+ if (!response.ok) {
62
+ return { error: `Failed to fetch from ${source}: ${response.statusText}` };
63
+ }
64
+ const content = await response.arrayBuffer();
65
+ try {
66
+ await writeFile(cacheFile, Buffer.from(content));
67
+ console.log(`Cached: ${source}`);
68
+ } catch (cacheError) {
69
+ console.warn(`Failed to cache: ${cacheError}`);
70
+ }
71
+ return { content, filePath: cacheFile };
72
+ } catch (error) {
73
+ return { error: `Error downloading from ${source}: ${error}` };
74
+ }
75
+ } else {
76
+ try {
77
+ console.log(`Loading from local path: ${source}`);
78
+ const content = await Bun.file(source).arrayBuffer();
79
+ return { content, filePath: source };
80
+ } catch (error) {
81
+ return { error: `Error loading from local path ${source}: ${error}` };
82
+ }
83
+ }
84
+ }
85
+ static async downloadToPath(source, targetPath) {
86
+ const isUrl = source.startsWith("http://") || source.startsWith("https://");
87
+ await mkdir(path.dirname(targetPath), { recursive: true });
88
+ if (isUrl) {
89
+ try {
90
+ console.log(`Downloading from URL: ${source}`);
91
+ const response = await fetch(source);
92
+ if (!response.ok) {
93
+ return { error: `Failed to fetch from ${source}: ${response.statusText}` };
94
+ }
95
+ const content = await response.arrayBuffer();
96
+ await writeFile(targetPath, Buffer.from(content));
97
+ console.log(`Downloaded: ${source} -> ${targetPath}`);
98
+ return { content, filePath: targetPath };
99
+ } catch (error) {
100
+ return { error: `Error downloading from ${source}: ${error}` };
101
+ }
102
+ } else {
103
+ try {
104
+ console.log(`Copying from local path: ${source}`);
105
+ const content = await Bun.file(source).arrayBuffer();
106
+ await writeFile(targetPath, Buffer.from(content));
107
+ return { content, filePath: targetPath };
108
+ } catch (error) {
109
+ return { error: `Error copying from local path ${source}: ${error}` };
110
+ }
111
+ }
112
+ }
113
+ static async fetchHighlightQueries(sources, cacheDir, filetype) {
114
+ const queryPromises = sources.map((source) => this.fetchHighlightQuery(source, cacheDir, filetype));
115
+ const queryResults = await Promise.all(queryPromises);
116
+ const validQueries = queryResults.filter((query) => query.trim().length > 0);
117
+ return validQueries.join(`
118
+ `);
119
+ }
120
+ static async fetchHighlightQuery(source, cacheDir, filetype) {
121
+ const result = await this.downloadOrLoad(source, cacheDir, "queries", ".scm", true, filetype);
122
+ if (result.error) {
123
+ console.error(`Error fetching highlight query from ${source}:`, result.error);
124
+ return "";
125
+ }
126
+ if (result.content) {
127
+ return new TextDecoder().decode(result.content);
128
+ }
129
+ return "";
130
+ }
131
+ }
132
+
133
+ // src/lib/tree-sitter/parser.worker.ts
134
+ import { isMainThread } from "worker_threads";
135
+
136
+ // src/lib/bunfs.ts
137
+ import { basename as basename2, join as join2 } from "path";
138
+ function isBunfsPath(path2) {
139
+ return path2.includes("$bunfs") || /^B:[\\/]~BUN/i.test(path2);
140
+ }
141
+ function getBunfsRootPath() {
142
+ return process.platform === "win32" ? "B:\\~BUN\\root" : "/$bunfs/root";
143
+ }
144
+ function normalizeBunfsPath(fileName) {
145
+ return join2(getBunfsRootPath(), basename2(fileName));
146
+ }
147
+
148
+ // src/lib/tree-sitter/parser.worker.ts
149
+ var self = globalThis;
150
+
151
+ class ParserWorker {
152
+ bufferParsers = new Map;
153
+ filetypeParserOptions = new Map;
154
+ filetypeParsers = new Map;
155
+ filetypeParserPromises = new Map;
156
+ reusableParsers = new Map;
157
+ reusableParserPromises = new Map;
158
+ initializePromise;
159
+ performance;
160
+ dataPath;
161
+ tsDataPath;
162
+ initialized = false;
163
+ constructor() {
164
+ this.performance = {
165
+ averageParseTime: 0,
166
+ parseTimes: [],
167
+ averageQueryTime: 0,
168
+ queryTimes: []
169
+ };
170
+ }
171
+ async fetchQueries(sources, filetype) {
172
+ if (!this.tsDataPath) {
173
+ return "";
174
+ }
175
+ return DownloadUtils.fetchHighlightQueries(sources, this.tsDataPath, filetype);
176
+ }
177
+ async initialize({ dataPath }) {
178
+ if (this.initializePromise) {
179
+ return this.initializePromise;
180
+ }
181
+ this.initializePromise = new Promise(async (resolve, reject) => {
182
+ this.dataPath = dataPath;
183
+ this.tsDataPath = path2.join(dataPath, "tree-sitter");
184
+ try {
185
+ await mkdir2(path2.join(this.tsDataPath, "languages"), { recursive: true });
186
+ await mkdir2(path2.join(this.tsDataPath, "queries"), { recursive: true });
187
+ let { default: treeWasm } = await import("web-tree-sitter/tree-sitter.wasm", {
188
+ with: { type: "wasm" }
189
+ });
190
+ if (isBunfsPath(treeWasm)) {
191
+ treeWasm = normalizeBunfsPath(path2.parse(treeWasm).base);
192
+ }
193
+ await Parser.init({
194
+ locateFile() {
195
+ return treeWasm;
196
+ }
197
+ });
198
+ this.initialized = true;
199
+ resolve();
200
+ } catch (error) {
201
+ reject(error);
202
+ }
203
+ });
204
+ return this.initializePromise;
205
+ }
206
+ addFiletypeParser(filetypeParser) {
207
+ this.filetypeParserOptions.set(filetypeParser.filetype, filetypeParser);
208
+ }
209
+ async createQueries(filetypeParser, language) {
210
+ try {
211
+ const highlightQueryContent = await this.fetchQueries(filetypeParser.queries.highlights, filetypeParser.filetype);
212
+ if (!highlightQueryContent) {
213
+ console.error("Failed to fetch highlight queries for:", filetypeParser.filetype);
214
+ return;
215
+ }
216
+ const highlightsQuery = new Query(language, highlightQueryContent);
217
+ const result = {
218
+ highlights: highlightsQuery
219
+ };
220
+ if (filetypeParser.queries.injections && filetypeParser.queries.injections.length > 0) {
221
+ const injectionQueryContent = await this.fetchQueries(filetypeParser.queries.injections, filetypeParser.filetype);
222
+ if (injectionQueryContent) {
223
+ result.injections = new Query(language, injectionQueryContent);
224
+ }
225
+ }
226
+ return result;
227
+ } catch (error) {
228
+ console.error("Error creating queries for", filetypeParser.filetype, filetypeParser.queries);
229
+ console.error(error);
230
+ return;
231
+ }
232
+ }
233
+ async loadLanguage(languageSource) {
234
+ if (!this.initialized || !this.tsDataPath) {
235
+ return;
236
+ }
237
+ const result = await DownloadUtils.downloadOrLoad(languageSource, this.tsDataPath, "languages", ".wasm", false);
238
+ if (result.error) {
239
+ console.error(`Error loading language ${languageSource}:`, result.error);
240
+ return;
241
+ }
242
+ if (!result.filePath) {
243
+ return;
244
+ }
245
+ const normalizedPath = result.filePath.replaceAll("\\", "/");
246
+ try {
247
+ const language = await Language.load(normalizedPath);
248
+ return language;
249
+ } catch (error) {
250
+ console.error(`Error loading language from ${normalizedPath}:`, error);
251
+ return;
252
+ }
253
+ }
254
+ async resolveFiletypeParser(filetype) {
255
+ if (this.filetypeParsers.has(filetype)) {
256
+ return this.filetypeParsers.get(filetype);
257
+ }
258
+ if (this.filetypeParserPromises.has(filetype)) {
259
+ return this.filetypeParserPromises.get(filetype);
260
+ }
261
+ const loadingPromise = this.loadFiletypeParser(filetype);
262
+ this.filetypeParserPromises.set(filetype, loadingPromise);
263
+ try {
264
+ const result = await loadingPromise;
265
+ if (result) {
266
+ this.filetypeParsers.set(filetype, result);
267
+ }
268
+ return result;
269
+ } finally {
270
+ this.filetypeParserPromises.delete(filetype);
271
+ }
272
+ }
273
+ async loadFiletypeParser(filetype) {
274
+ const filetypeParserOptions = this.filetypeParserOptions.get(filetype);
275
+ if (!filetypeParserOptions) {
276
+ return;
277
+ }
278
+ const language = await this.loadLanguage(filetypeParserOptions.wasm);
279
+ if (!language) {
280
+ return;
281
+ }
282
+ const queries = await this.createQueries(filetypeParserOptions, language);
283
+ if (!queries) {
284
+ console.error("Failed to create queries for:", filetype);
285
+ return;
286
+ }
287
+ const filetypeParser = {
288
+ ...filetypeParserOptions,
289
+ queries,
290
+ language
291
+ };
292
+ return filetypeParser;
293
+ }
294
+ async preloadParser(filetype) {
295
+ return this.resolveFiletypeParser(filetype);
296
+ }
297
+ async getReusableParser(filetype) {
298
+ if (this.reusableParsers.has(filetype)) {
299
+ return this.reusableParsers.get(filetype);
300
+ }
301
+ if (this.reusableParserPromises.has(filetype)) {
302
+ return this.reusableParserPromises.get(filetype);
303
+ }
304
+ const creationPromise = this.createReusableParser(filetype);
305
+ this.reusableParserPromises.set(filetype, creationPromise);
306
+ try {
307
+ const result = await creationPromise;
308
+ if (result) {
309
+ this.reusableParsers.set(filetype, result);
310
+ }
311
+ return result;
312
+ } finally {
313
+ this.reusableParserPromises.delete(filetype);
314
+ }
315
+ }
316
+ async createReusableParser(filetype) {
317
+ const filetypeParser = await this.resolveFiletypeParser(filetype);
318
+ if (!filetypeParser) {
319
+ return;
320
+ }
321
+ const parser = new Parser;
322
+ parser.setLanguage(filetypeParser.language);
323
+ const reusableState = {
324
+ parser,
325
+ filetypeParser,
326
+ queries: filetypeParser.queries
327
+ };
328
+ return reusableState;
329
+ }
330
+ async handleInitializeParser(bufferId, version, content, filetype, messageId) {
331
+ const filetypeParser = await this.resolveFiletypeParser(filetype);
332
+ if (!filetypeParser) {
333
+ self.postMessage({
334
+ type: "PARSER_INIT_RESPONSE",
335
+ bufferId,
336
+ messageId,
337
+ hasParser: false,
338
+ warning: `No parser available for filetype ${filetype}`
339
+ });
340
+ return;
341
+ }
342
+ const parser = new Parser;
343
+ parser.setLanguage(filetypeParser.language);
344
+ const tree = parser.parse(content);
345
+ if (!tree) {
346
+ self.postMessage({
347
+ type: "PARSER_INIT_RESPONSE",
348
+ bufferId,
349
+ messageId,
350
+ hasParser: false,
351
+ error: "Failed to parse buffer"
352
+ });
353
+ return;
354
+ }
355
+ const parserState = {
356
+ parser,
357
+ tree,
358
+ queries: filetypeParser.queries,
359
+ filetype,
360
+ content,
361
+ injectionMapping: filetypeParser.injectionMapping
362
+ };
363
+ this.bufferParsers.set(bufferId, parserState);
364
+ self.postMessage({
365
+ type: "PARSER_INIT_RESPONSE",
366
+ bufferId,
367
+ messageId,
368
+ hasParser: true
369
+ });
370
+ const highlights = await this.initialQuery(parserState);
371
+ self.postMessage({
372
+ type: "HIGHLIGHT_RESPONSE",
373
+ bufferId,
374
+ version,
375
+ ...highlights
376
+ });
377
+ }
378
+ async initialQuery(parserState) {
379
+ const query = parserState.queries.highlights;
380
+ const matches = query.captures(parserState.tree.rootNode);
381
+ let injectionRanges = new Map;
382
+ if (parserState.queries.injections) {
383
+ const injectionResult = await this.processInjections(parserState);
384
+ matches.push(...injectionResult.captures);
385
+ injectionRanges = injectionResult.injectionRanges;
386
+ }
387
+ return this.getHighlights(parserState, matches, injectionRanges);
388
+ }
389
+ getNodeText(node, content) {
390
+ return content.substring(node.startIndex, node.endIndex);
391
+ }
392
+ async processInjections(parserState) {
393
+ const injectionMatches = [];
394
+ const injectionRanges = new Map;
395
+ if (!parserState.queries.injections) {
396
+ return { captures: injectionMatches, injectionRanges };
397
+ }
398
+ const content = parserState.content;
399
+ const injectionCaptures = parserState.queries.injections.captures(parserState.tree.rootNode);
400
+ const languageGroups = new Map;
401
+ const injectionMapping = parserState.injectionMapping;
402
+ for (const capture of injectionCaptures) {
403
+ const captureName = capture.name;
404
+ if (captureName === "injection.content" || captureName.includes("injection")) {
405
+ const nodeType = capture.node.type;
406
+ let targetLanguage;
407
+ if (injectionMapping?.nodeTypes && injectionMapping.nodeTypes[nodeType]) {
408
+ targetLanguage = injectionMapping.nodeTypes[nodeType];
409
+ } else if (nodeType === "code_fence_content") {
410
+ const parent = capture.node.parent;
411
+ if (parent) {
412
+ const infoString = parent.children.find((child) => child.type === "info_string");
413
+ if (infoString) {
414
+ const languageNode = infoString.children.find((child) => child.type === "language");
415
+ if (languageNode) {
416
+ const languageName = this.getNodeText(languageNode, content);
417
+ if (injectionMapping?.infoStringMap && injectionMapping.infoStringMap[languageName]) {
418
+ targetLanguage = injectionMapping.infoStringMap[languageName];
419
+ } else {
420
+ targetLanguage = languageName;
421
+ }
422
+ }
423
+ }
424
+ }
425
+ }
426
+ if (targetLanguage) {
427
+ if (!languageGroups.has(targetLanguage)) {
428
+ languageGroups.set(targetLanguage, []);
429
+ }
430
+ languageGroups.get(targetLanguage).push({ node: capture.node, name: capture.name });
431
+ }
432
+ }
433
+ }
434
+ for (const [language, captures] of languageGroups.entries()) {
435
+ const injectedParser = await this.getReusableParser(language);
436
+ if (!injectedParser) {
437
+ console.warn(`No parser found for injection language: ${language}`);
438
+ continue;
439
+ }
440
+ if (!injectionRanges.has(language)) {
441
+ injectionRanges.set(language, []);
442
+ }
443
+ const parser = injectedParser.parser;
444
+ for (const { node: injectionNode } of captures) {
445
+ try {
446
+ injectionRanges.get(language).push({
447
+ start: injectionNode.startIndex,
448
+ end: injectionNode.endIndex
449
+ });
450
+ const injectionContent = this.getNodeText(injectionNode, content);
451
+ const tree = parser.parse(injectionContent);
452
+ if (tree) {
453
+ const matches = injectedParser.queries.highlights.captures(tree.rootNode);
454
+ for (const match of matches) {
455
+ const offsetCapture = {
456
+ name: match.name,
457
+ patternIndex: match.patternIndex,
458
+ _injectedQuery: injectedParser.queries.highlights,
459
+ node: {
460
+ ...match.node,
461
+ startPosition: {
462
+ row: match.node.startPosition.row + injectionNode.startPosition.row,
463
+ column: match.node.startPosition.row === 0 ? match.node.startPosition.column + injectionNode.startPosition.column : match.node.startPosition.column
464
+ },
465
+ endPosition: {
466
+ row: match.node.endPosition.row + injectionNode.startPosition.row,
467
+ column: match.node.endPosition.row === 0 ? match.node.endPosition.column + injectionNode.startPosition.column : match.node.endPosition.column
468
+ },
469
+ startIndex: match.node.startIndex + injectionNode.startIndex,
470
+ endIndex: match.node.endIndex + injectionNode.startIndex
471
+ }
472
+ };
473
+ injectionMatches.push(offsetCapture);
474
+ }
475
+ tree.delete();
476
+ }
477
+ } catch (error) {
478
+ console.error(`Error processing injection for language ${language}:`, error);
479
+ }
480
+ }
481
+ }
482
+ return { captures: injectionMatches, injectionRanges };
483
+ }
484
+ editToRange(edit) {
485
+ return {
486
+ startPosition: {
487
+ column: edit.startPosition.column,
488
+ row: edit.startPosition.row
489
+ },
490
+ endPosition: {
491
+ column: edit.newEndPosition.column,
492
+ row: edit.newEndPosition.row
493
+ },
494
+ startIndex: edit.startIndex,
495
+ endIndex: edit.newEndIndex
496
+ };
497
+ }
498
+ async handleEdits(bufferId, content, edits) {
499
+ const parserState = this.bufferParsers.get(bufferId);
500
+ if (!parserState) {
501
+ return { warning: "No parser state found for buffer" };
502
+ }
503
+ parserState.content = content;
504
+ for (const edit of edits) {
505
+ parserState.tree.edit(edit);
506
+ }
507
+ const startParse = performance.now();
508
+ const newTree = parserState.parser.parse(content, parserState.tree);
509
+ const endParse = performance.now();
510
+ const parseTime = endParse - startParse;
511
+ this.performance.parseTimes.push(parseTime);
512
+ if (this.performance.parseTimes.length > 10) {
513
+ this.performance.parseTimes.shift();
514
+ }
515
+ this.performance.averageParseTime = this.performance.parseTimes.reduce((acc, time) => acc + time, 0) / this.performance.parseTimes.length;
516
+ if (!newTree) {
517
+ return { error: "Failed to parse buffer" };
518
+ }
519
+ const changedRanges = parserState.tree.getChangedRanges(newTree);
520
+ parserState.tree = newTree;
521
+ const startQuery = performance.now();
522
+ const matches = [];
523
+ if (changedRanges.length === 0) {
524
+ edits.forEach((edit) => {
525
+ const range = this.editToRange(edit);
526
+ changedRanges.push(range);
527
+ });
528
+ }
529
+ for (const range of changedRanges) {
530
+ let node = parserState.tree.rootNode.descendantForPosition(range.startPosition, range.endPosition);
531
+ if (!node) {
532
+ continue;
533
+ }
534
+ if (node.equals(parserState.tree.rootNode)) {
535
+ const rangeCaptures = parserState.queries.highlights.captures(node, {
536
+ startIndex: range.startIndex - 100,
537
+ endIndex: range.endIndex + 1000
538
+ });
539
+ matches.push(...rangeCaptures);
540
+ continue;
541
+ }
542
+ while (node && !this.nodeContainsRange(node, range)) {
543
+ node = node.parent;
544
+ }
545
+ if (!node) {
546
+ node = parserState.tree.rootNode;
547
+ }
548
+ const nodeCaptures = parserState.queries.highlights.captures(node);
549
+ matches.push(...nodeCaptures);
550
+ }
551
+ let injectionRanges = new Map;
552
+ if (parserState.queries.injections) {
553
+ const injectionResult = await this.processInjections(parserState);
554
+ matches.push(...injectionResult.captures);
555
+ injectionRanges = injectionResult.injectionRanges;
556
+ }
557
+ const endQuery = performance.now();
558
+ const queryTime = endQuery - startQuery;
559
+ this.performance.queryTimes.push(queryTime);
560
+ if (this.performance.queryTimes.length > 10) {
561
+ this.performance.queryTimes.shift();
562
+ }
563
+ this.performance.averageQueryTime = this.performance.queryTimes.reduce((acc, time) => acc + time, 0) / this.performance.queryTimes.length;
564
+ return this.getHighlights(parserState, matches, injectionRanges);
565
+ }
566
+ nodeContainsRange(node, range) {
567
+ return node.startPosition.row <= range.startPosition.row && node.endPosition.row >= range.endPosition.row && (node.startPosition.row < range.startPosition.row || node.startPosition.column <= range.startPosition.column) && (node.endPosition.row > range.endPosition.row || node.endPosition.column >= range.endPosition.column);
568
+ }
569
+ getHighlights(parserState, matches, injectionRanges) {
570
+ const lineHighlights = new Map;
571
+ const droppedHighlights = new Map;
572
+ for (const match of matches) {
573
+ const node = match.node;
574
+ const startLine = node.startPosition.row;
575
+ const endLine = node.endPosition.row;
576
+ const highlight = {
577
+ startCol: node.startPosition.column,
578
+ endCol: node.endPosition.column,
579
+ group: match.name
580
+ };
581
+ if (!lineHighlights.has(startLine)) {
582
+ lineHighlights.set(startLine, new Map);
583
+ droppedHighlights.set(startLine, new Map);
584
+ }
585
+ if (lineHighlights.get(startLine)?.has(node.id)) {
586
+ droppedHighlights.get(startLine)?.set(node.id, lineHighlights.get(startLine)?.get(node.id));
587
+ }
588
+ lineHighlights.get(startLine)?.set(node.id, highlight);
589
+ if (startLine !== endLine) {
590
+ for (let line = startLine + 1;line <= endLine; line++) {
591
+ if (!lineHighlights.has(line)) {
592
+ lineHighlights.set(line, new Map);
593
+ }
594
+ const hl = {
595
+ startCol: 0,
596
+ endCol: node.endPosition.column,
597
+ group: match.name
598
+ };
599
+ lineHighlights.get(line)?.set(node.id, hl);
600
+ }
601
+ }
602
+ }
603
+ return {
604
+ highlights: Array.from(lineHighlights.entries()).map(([line, lineHighlights2]) => ({
605
+ line,
606
+ highlights: Array.from(lineHighlights2.values()),
607
+ droppedHighlights: droppedHighlights.get(line) ? Array.from(droppedHighlights.get(line).values()) : []
608
+ }))
609
+ };
610
+ }
611
+ getSimpleHighlights(matches, injectionRanges) {
612
+ const highlights = [];
613
+ const flatInjectionRanges = [];
614
+ for (const [lang, ranges] of injectionRanges.entries()) {
615
+ for (const range of ranges) {
616
+ flatInjectionRanges.push({ ...range, lang });
617
+ }
618
+ }
619
+ for (const match of matches) {
620
+ const node = match.node;
621
+ let isInjection = false;
622
+ let injectionLang;
623
+ let containsInjection = false;
624
+ for (const injRange of flatInjectionRanges) {
625
+ if (node.startIndex >= injRange.start && node.endIndex <= injRange.end) {
626
+ isInjection = true;
627
+ injectionLang = injRange.lang;
628
+ break;
629
+ } else if (node.startIndex <= injRange.start && node.endIndex >= injRange.end) {
630
+ containsInjection = true;
631
+ break;
632
+ }
633
+ }
634
+ const matchQuery = match._injectedQuery;
635
+ const patternProperties = matchQuery?.setProperties?.[match.patternIndex];
636
+ const concealValue = patternProperties?.conceal ?? match.setProperties?.conceal;
637
+ const concealLines = patternProperties?.conceal_lines ?? match.setProperties?.conceal_lines;
638
+ const meta = {};
639
+ if (isInjection && injectionLang) {
640
+ meta.isInjection = true;
641
+ meta.injectionLang = injectionLang;
642
+ }
643
+ if (containsInjection) {
644
+ meta.containsInjection = true;
645
+ }
646
+ if (concealValue !== undefined) {
647
+ meta.conceal = concealValue;
648
+ }
649
+ if (concealLines !== undefined) {
650
+ meta.concealLines = concealLines;
651
+ }
652
+ if (Object.keys(meta).length > 0) {
653
+ highlights.push([node.startIndex, node.endIndex, match.name, meta]);
654
+ } else {
655
+ highlights.push([node.startIndex, node.endIndex, match.name]);
656
+ }
657
+ }
658
+ highlights.sort((a, b) => a[0] - b[0]);
659
+ return highlights;
660
+ }
661
+ async handleResetBuffer(bufferId, version, content) {
662
+ const parserState = this.bufferParsers.get(bufferId);
663
+ if (!parserState) {
664
+ return { warning: "No parser state found for buffer" };
665
+ }
666
+ parserState.content = content;
667
+ const newTree = parserState.parser.parse(content);
668
+ if (!newTree) {
669
+ return { error: "Failed to parse buffer during reset" };
670
+ }
671
+ parserState.tree = newTree;
672
+ const matches = parserState.queries.highlights.captures(parserState.tree.rootNode);
673
+ let injectionRanges = new Map;
674
+ if (parserState.queries.injections) {
675
+ const injectionResult = await this.processInjections(parserState);
676
+ matches.push(...injectionResult.captures);
677
+ injectionRanges = injectionResult.injectionRanges;
678
+ }
679
+ return this.getHighlights(parserState, matches, injectionRanges);
680
+ }
681
+ disposeBuffer(bufferId) {
682
+ const parserState = this.bufferParsers.get(bufferId);
683
+ if (!parserState) {
684
+ return;
685
+ }
686
+ parserState.tree.delete();
687
+ parserState.parser.delete();
688
+ this.bufferParsers.delete(bufferId);
689
+ }
690
+ async handleOneShotHighlight(content, filetype, messageId) {
691
+ const reusableState = await this.getReusableParser(filetype);
692
+ if (!reusableState) {
693
+ self.postMessage({
694
+ type: "ONESHOT_HIGHLIGHT_RESPONSE",
695
+ messageId,
696
+ hasParser: false,
697
+ warning: `No parser available for filetype ${filetype}`
698
+ });
699
+ return;
700
+ }
701
+ const parseContent = filetype === "markdown" && content.endsWith("```") ? content + `
702
+ ` : content;
703
+ const tree = reusableState.parser.parse(parseContent);
704
+ if (!tree) {
705
+ self.postMessage({
706
+ type: "ONESHOT_HIGHLIGHT_RESPONSE",
707
+ messageId,
708
+ hasParser: false,
709
+ error: "Failed to parse content"
710
+ });
711
+ return;
712
+ }
713
+ try {
714
+ const matches = reusableState.filetypeParser.queries.highlights.captures(tree.rootNode);
715
+ let injectionRanges = new Map;
716
+ if (reusableState.filetypeParser.queries.injections) {
717
+ const parserState = {
718
+ parser: reusableState.parser,
719
+ tree,
720
+ queries: reusableState.filetypeParser.queries,
721
+ filetype,
722
+ content,
723
+ injectionMapping: reusableState.filetypeParser.injectionMapping
724
+ };
725
+ const injectionResult = await this.processInjections(parserState);
726
+ matches.push(...injectionResult.captures);
727
+ injectionRanges = injectionResult.injectionRanges;
728
+ }
729
+ const highlights = this.getSimpleHighlights(matches, injectionRanges);
730
+ self.postMessage({
731
+ type: "ONESHOT_HIGHLIGHT_RESPONSE",
732
+ messageId,
733
+ hasParser: true,
734
+ highlights
735
+ });
736
+ } finally {
737
+ tree.delete();
738
+ }
739
+ }
740
+ async updateDataPath(dataPath) {
741
+ this.dataPath = dataPath;
742
+ this.tsDataPath = path2.join(dataPath, "tree-sitter");
743
+ try {
744
+ await mkdir2(path2.join(this.tsDataPath, "languages"), { recursive: true });
745
+ await mkdir2(path2.join(this.tsDataPath, "queries"), { recursive: true });
746
+ } catch (error) {
747
+ throw new Error(`Failed to update data path: ${error}`);
748
+ }
749
+ }
750
+ async clearCache() {
751
+ if (!this.dataPath || !this.tsDataPath) {
752
+ throw new Error("No data path configured");
753
+ }
754
+ const { rm } = await import("fs/promises");
755
+ try {
756
+ const treeSitterPath = path2.join(this.dataPath, "tree-sitter");
757
+ await rm(treeSitterPath, { recursive: true, force: true });
758
+ await mkdir2(path2.join(treeSitterPath, "languages"), { recursive: true });
759
+ await mkdir2(path2.join(treeSitterPath, "queries"), { recursive: true });
760
+ this.filetypeParsers.clear();
761
+ this.filetypeParserPromises.clear();
762
+ this.reusableParsers.clear();
763
+ this.reusableParserPromises.clear();
764
+ } catch (error) {
765
+ throw new Error(`Failed to clear cache: ${error}`);
766
+ }
767
+ }
768
+ }
769
+ if (!isMainThread) {
770
+ let logMessage = function(type, ...args) {
771
+ self.postMessage({
772
+ type: "WORKER_LOG",
773
+ logType: type,
774
+ data: args
775
+ });
776
+ };
777
+ const worker = new ParserWorker;
778
+ console.log = (...args) => logMessage("log", ...args);
779
+ console.error = (...args) => logMessage("error", ...args);
780
+ console.warn = (...args) => logMessage("warn", ...args);
781
+ self.onmessage = async (e) => {
782
+ const { type, bufferId, version, content, filetype, edits, filetypeParser, messageId, dataPath } = e.data;
783
+ try {
784
+ switch (type) {
785
+ case "INIT":
786
+ try {
787
+ await worker.initialize({ dataPath });
788
+ self.postMessage({ type: "INIT_RESPONSE" });
789
+ } catch (error) {
790
+ self.postMessage({
791
+ type: "INIT_RESPONSE",
792
+ error: error instanceof Error ? error.stack || error.message : String(error)
793
+ });
794
+ }
795
+ break;
796
+ case "ADD_FILETYPE_PARSER":
797
+ worker.addFiletypeParser(filetypeParser);
798
+ break;
799
+ case "PRELOAD_PARSER":
800
+ const maybeParser = await worker.preloadParser(filetype);
801
+ self.postMessage({ type: "PRELOAD_PARSER_RESPONSE", messageId, hasParser: !!maybeParser });
802
+ break;
803
+ case "INITIALIZE_PARSER":
804
+ await worker.handleInitializeParser(bufferId, version, content, filetype, messageId);
805
+ break;
806
+ case "HANDLE_EDITS":
807
+ const response = await worker.handleEdits(bufferId, content, edits);
808
+ if (response.highlights && response.highlights.length > 0) {
809
+ self.postMessage({ type: "HIGHLIGHT_RESPONSE", bufferId, version, ...response });
810
+ } else if (response.warning) {
811
+ self.postMessage({ type: "WARNING", bufferId, warning: response.warning });
812
+ } else if (response.error) {
813
+ self.postMessage({ type: "ERROR", bufferId, error: response.error });
814
+ }
815
+ break;
816
+ case "GET_PERFORMANCE":
817
+ self.postMessage({ type: "PERFORMANCE_RESPONSE", performance: worker.performance, messageId });
818
+ break;
819
+ case "RESET_BUFFER":
820
+ const resetResponse = await worker.handleResetBuffer(bufferId, version, content);
821
+ if (resetResponse.highlights && resetResponse.highlights.length > 0) {
822
+ self.postMessage({ type: "HIGHLIGHT_RESPONSE", bufferId, version, ...resetResponse });
823
+ } else if (resetResponse.warning) {
824
+ self.postMessage({ type: "WARNING", bufferId, warning: resetResponse.warning });
825
+ } else if (resetResponse.error) {
826
+ self.postMessage({ type: "ERROR", bufferId, error: resetResponse.error });
827
+ }
828
+ break;
829
+ case "DISPOSE_BUFFER":
830
+ worker.disposeBuffer(bufferId);
831
+ self.postMessage({ type: "BUFFER_DISPOSED", bufferId });
832
+ break;
833
+ case "ONESHOT_HIGHLIGHT":
834
+ await worker.handleOneShotHighlight(content, filetype, messageId);
835
+ break;
836
+ case "UPDATE_DATA_PATH":
837
+ try {
838
+ await worker.updateDataPath(dataPath);
839
+ self.postMessage({ type: "UPDATE_DATA_PATH_RESPONSE", messageId });
840
+ } catch (error) {
841
+ self.postMessage({
842
+ type: "UPDATE_DATA_PATH_RESPONSE",
843
+ messageId,
844
+ error: error instanceof Error ? error.message : String(error)
845
+ });
846
+ }
847
+ break;
848
+ case "CLEAR_CACHE":
849
+ try {
850
+ await worker.clearCache();
851
+ self.postMessage({ type: "CLEAR_CACHE_RESPONSE", messageId });
852
+ } catch (error) {
853
+ self.postMessage({
854
+ type: "CLEAR_CACHE_RESPONSE",
855
+ messageId,
856
+ error: error instanceof Error ? error.message : String(error)
857
+ });
858
+ }
859
+ break;
860
+ default:
861
+ self.postMessage({
862
+ type: "ERROR",
863
+ bufferId,
864
+ error: `Unknown message type: ${type}`
865
+ });
866
+ }
867
+ } catch (error) {
868
+ self.postMessage({
869
+ type: "ERROR",
870
+ bufferId,
871
+ error: error instanceof Error ? error.stack || error.message : String(error)
872
+ });
873
+ }
874
+ };
875
+ }
876
+
877
+ //# debugId=F5C8191D269AAAF964756E2164756E21
878
+ //# sourceMappingURL=parser.worker.js.map