zidane-gui 8.2.4 → 9.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.
Files changed (42) hide show
  1. package/README.md +3 -2
  2. package/out/main/chunks/{history-pager-Bd5PUapJ.js → history-pager-DUFgTrih.js} +5 -56
  3. package/out/main/chunks/session-search-sql-BrNTuwjH.js +196 -0
  4. package/out/main/chunks/tool-results-sql-C0MqWcQc.js +41 -0
  5. package/out/main/chunks/transcript-sql-DbZ-a5wb.js +43 -0
  6. package/out/main/chunks/usage-sql-DiITGx8Q.js +67 -0
  7. package/out/main/history-worker.js +2 -4
  8. package/out/main/index.js +2275 -3375
  9. package/out/main/lsp-host.js +17 -4
  10. package/out/main/session-search-worker.js +20 -0
  11. package/out/main/tool-results-worker.js +17 -0
  12. package/out/main/usage-worker.js +5 -19
  13. package/out/preload/index.mjs +69 -5
  14. package/out/renderer/assets/CodeEditor-in2F3Rz-.js +12771 -0
  15. package/out/renderer/assets/ComposerEditor-DzKoxH6Z.js +68 -0
  16. package/out/renderer/assets/DiffsTab-Ceh4E5wW.js +540 -0
  17. package/out/renderer/assets/EditorWorkers-Bhv2OJRb.js +67 -0
  18. package/out/renderer/assets/FileIcon-CYgGSQ59.js +781 -0
  19. package/out/renderer/assets/FilesTab-DESQMqGK.js +11763 -0
  20. package/out/renderer/assets/core-xOIU6ifr.js +9977 -0
  21. package/out/renderer/assets/file-tabs-Cozt9Sho.js +105 -0
  22. package/out/renderer/assets/{ghostty-web-BTRdAlae.js → ghostty-web-BTHoKwMc.js} +1 -1
  23. package/out/renderer/assets/index-DkE-xvCG.js +9525 -0
  24. package/out/renderer/assets/index-DogoEzwx.js +10868 -0
  25. package/out/renderer/assets/{index-BI29HKE2.css → index-DrLLItLS.css} +2481 -2639
  26. package/out/renderer/assets/kit-BUt8oFlT.js +64699 -0
  27. package/out/renderer/assets/pierre-theme-Bj5EAt1L.js +4312 -0
  28. package/out/renderer/assets/useDetachCleanup-Bb7k1ePf.js +3138 -0
  29. package/out/renderer/assets/useFolderChanges-B4X4n6NV.js +7896 -0
  30. package/out/renderer/assets/vendor-BvslLX9q.js +20410 -0
  31. package/out/renderer/assets/vendor-D_E2rLzO.css +388 -0
  32. package/out/renderer/assets/vendor-editor-Bx3dRdBD.js +26391 -0
  33. package/out/renderer/assets/vendor-motion-BLeNAEjH.js +9376 -0
  34. package/out/renderer/assets/vendor-react-DltKc0Ts.js +14275 -0
  35. package/out/renderer/assets/vendor-shiki-ba8IDo5s.js +459 -0
  36. package/out/renderer/index.html +11 -3
  37. package/package.json +10 -4
  38. package/scripts/postinstall.mjs +2 -1
  39. package/out/main/chunks/context-77_UZfgL.js +0 -61
  40. package/out/main/chunks/usage-sql-C2Tg1u44.js +0 -81
  41. package/out/renderer/assets/index-D0Yl489p.js +0 -191283
  42. /package/out/renderer/assets/{working-tree-parse.worker-BAW1QWyk.js → patch-parse.worker-BAW1QWyk.js} +0 -0
@@ -0,0 +1,4312 @@
1
+ import { _ as __vitePreload } from "./vendor-shiki-ba8IDo5s.js";
2
+ import { b as bundledLanguages, n as normalizeTheme, c as createHighlighter, a as createOnigurumaEngine, d as createJavaScriptRegexEngine } from "./index-DogoEzwx.js";
3
+ import { g as getDefaultExportFromCjs, r as reactExports, j as jsxRuntimeExports } from "./vendor-react-DltKc0Ts.js";
4
+ const DIFFS_TAG_NAME = "diffs-container";
5
+ (() => {
6
+ try {
7
+ return false;
8
+ } catch {
9
+ return false;
10
+ }
11
+ })();
12
+ const COMMIT_METADATA_SPLIT = /(?=^From [a-f0-9]+ .+$)/m;
13
+ const GIT_DIFF_FILE_BREAK_REGEX = /(?=^diff --git)/gm;
14
+ const SPLIT_WITH_NEWLINES = /(?<=\n)/;
15
+ const FILENAME_HEADER_REGEX = /^(---|\+\+\+)\s+([^\t\r\n]+)/;
16
+ const INDEX_LINE_METADATA = /^index ([0-9a-f]+)\.\.([0-9a-f]+)(?: (\d+))?$/i;
17
+ const HEADER_PREFIX_SLOT_ID = "header-prefix";
18
+ const HEADER_FILENAME_SUFFIX_SLOT_ID = "header-filename-suffix";
19
+ const HEADER_METADATA_SLOT_ID = "header-metadata";
20
+ const CUSTOM_HEADER_SLOT_ID = "header-custom";
21
+ const DEFAULT_THEMES = {
22
+ dark: "pierre-dark",
23
+ light: "pierre-light"
24
+ };
25
+ const THEME_CSS_ATTRIBUTE = "data-theme-css";
26
+ const UNSAFE_CSS_ATTRIBUTE = "data-unsafe-css";
27
+ const DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE = "data-diffs-scrollbar-measure";
28
+ const DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY = "--diffs-scrollbar-gutter-measured";
29
+ const DEFAULT_TOKENIZE_MAX_LENGTH = 1e5;
30
+ const DEFAULT_VIRTUAL_FILE_METRICS = {
31
+ hunkLineCount: 50,
32
+ lineHeight: 20,
33
+ diffHeaderHeight: 44,
34
+ spacing: 8
35
+ };
36
+ ({
37
+ ...DEFAULT_VIRTUAL_FILE_METRICS
38
+ });
39
+ const DEFAULT_EXPANDED_REGION = Object.freeze({
40
+ fromStart: 0,
41
+ fromEnd: 0
42
+ });
43
+ const DEFAULT_RENDER_RANGE = {
44
+ startingLine: 0,
45
+ totalLines: Infinity,
46
+ bufferBefore: 0,
47
+ bufferAfter: 0
48
+ };
49
+ const EMPTY_RENDER_RANGE = {
50
+ startingLine: 0,
51
+ totalLines: 0,
52
+ bufferBefore: 0,
53
+ bufferAfter: 0
54
+ };
55
+ const ResolvedLanguages = /* @__PURE__ */ new Map();
56
+ const ResolvingLanguages = /* @__PURE__ */ new Map();
57
+ const RegisteredCustomLanguages = /* @__PURE__ */ new Map();
58
+ const AttachedLanguages = /* @__PURE__ */ new Set();
59
+ function areLanguagesAttached(languages) {
60
+ for (const language of Array.isArray(languages) ? languages : [languages]) {
61
+ if (language === "text" || language === "ansi") continue;
62
+ if (!AttachedLanguages.has(language)) return false;
63
+ }
64
+ return true;
65
+ }
66
+ function attachResolvedLanguages(resolvedLanguages, highlighter2) {
67
+ resolvedLanguages = Array.isArray(resolvedLanguages) ? resolvedLanguages : [resolvedLanguages];
68
+ for (const resolvedLang of resolvedLanguages) {
69
+ if (AttachedLanguages.has(resolvedLang.name)) continue;
70
+ let lang = ResolvedLanguages.get(resolvedLang.name);
71
+ if (lang == null) {
72
+ lang = resolvedLang;
73
+ ResolvedLanguages.set(resolvedLang.name, lang);
74
+ }
75
+ const grammar = lang.data.find((grammar2) => grammar2.name === lang.name || grammar2.aliases?.includes(lang.name) === true);
76
+ if (grammar == null) throw new Error(`attachResolvedLanguages: No returned grammar declares "${lang.name}" as its name or an alias.`);
77
+ highlighter2.loadLanguageSync(lang.data);
78
+ try {
79
+ highlighter2.getLanguage(lang.name);
80
+ } catch {
81
+ throw new Error(`attachResolvedLanguages: "${grammar.name}" is already loaded without alias "${lang.name}". Load the alias first or give the grammar a unique name.`);
82
+ }
83
+ AttachedLanguages.add(lang.name);
84
+ }
85
+ }
86
+ function isWorkerContext() {
87
+ return typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && self instanceof WorkerGlobalScope;
88
+ }
89
+ async function resolveLanguage(lang) {
90
+ if (isWorkerContext()) throw new Error(`resolveLanguage("${lang}") cannot be called from a worker context. Languages must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);
91
+ const resolver = ResolvingLanguages.get(lang);
92
+ if (resolver != null) return resolver;
93
+ try {
94
+ let loader = RegisteredCustomLanguages.get(lang);
95
+ if (loader == null && Object.prototype.hasOwnProperty.call(bundledLanguages, lang)) loader = bundledLanguages[lang];
96
+ if (loader == null) throw new Error(`resolveLanguage: "${lang}" not found in bundled or custom languages`);
97
+ const resolver2 = loader().then(({ default: data }) => {
98
+ const resolvedLang = {
99
+ name: lang,
100
+ data
101
+ };
102
+ if (!ResolvedLanguages.has(lang)) ResolvedLanguages.set(lang, resolvedLang);
103
+ return resolvedLang;
104
+ });
105
+ ResolvingLanguages.set(lang, resolver2);
106
+ return await resolver2;
107
+ } finally {
108
+ ResolvingLanguages.delete(lang);
109
+ }
110
+ }
111
+ function getResolvedOrResolveLanguage(language) {
112
+ return ResolvedLanguages.get(language) ?? resolveLanguage(language);
113
+ }
114
+ function getThemes(theme = DEFAULT_THEMES) {
115
+ const themesArr = [];
116
+ if (typeof theme === "string") themesArr.push(theme);
117
+ else {
118
+ themesArr.push(theme.dark);
119
+ themesArr.push(theme.light);
120
+ }
121
+ return themesArr;
122
+ }
123
+ const AttachedThemes = /* @__PURE__ */ new Set();
124
+ function areThemesAttached(themes) {
125
+ for (const theme of getThemes(themes)) if (!AttachedThemes.has(theme)) return false;
126
+ return true;
127
+ }
128
+ function createThemeCollection(options) {
129
+ const descriptors = [];
130
+ const seen = /* @__PURE__ */ new Set();
131
+ for (const entry of getCollectionEntries(options.themes)) {
132
+ const themes = isThemeCollectionSource(entry) ? entry.getThemes() : [entry];
133
+ for (const descriptor of themes) {
134
+ if (seen.has(descriptor.name)) throw new Error(`Theme collection already contains theme "${descriptor.name}"`);
135
+ seen.add(descriptor.name);
136
+ descriptors.push(descriptor);
137
+ }
138
+ }
139
+ const allThemes = Object.freeze([...descriptors]);
140
+ const lightThemes = Object.freeze(allThemes.filter((descriptor) => descriptor.colorScheme === "light"));
141
+ const darkThemes = Object.freeze(allThemes.filter((descriptor) => descriptor.colorScheme === "dark"));
142
+ const themesByName = new Map(allThemes.map((descriptor) => [descriptor.name, descriptor]));
143
+ const allNames = Object.freeze(allThemes.map((descriptor) => descriptor.name));
144
+ const lightNames = Object.freeze(lightThemes.map((descriptor) => descriptor.name));
145
+ const darkNames = Object.freeze(darkThemes.map((descriptor) => descriptor.name));
146
+ function filteredThemes(filterOptions) {
147
+ if (filterOptions == null) return allThemes;
148
+ const { colorScheme, collection } = filterOptions;
149
+ if (collection == null) {
150
+ if (colorScheme === "light") return lightThemes;
151
+ if (colorScheme === "dark") return darkThemes;
152
+ return allThemes;
153
+ }
154
+ return allThemes.filter((descriptor) => {
155
+ if (descriptor.collection !== collection) return false;
156
+ return colorScheme == null || descriptor.colorScheme === colorScheme;
157
+ });
158
+ }
159
+ return {
160
+ getTheme(name) {
161
+ return themesByName.get(name);
162
+ },
163
+ getThemes(themeOptions) {
164
+ return filteredThemes(themeOptions);
165
+ },
166
+ getThemeNames(namesOptions) {
167
+ if (namesOptions?.collection == null) {
168
+ if (namesOptions?.colorScheme === "light") return lightNames;
169
+ if (namesOptions?.colorScheme === "dark") return darkNames;
170
+ return allNames;
171
+ }
172
+ return filteredThemes(namesOptions).map((descriptor) => descriptor.name);
173
+ },
174
+ hasTheme(name) {
175
+ return themesByName.has(name);
176
+ },
177
+ orderBy(compare) {
178
+ return createThemeCollection({ themes: allThemes.map((descriptor, index) => ({
179
+ descriptor,
180
+ index
181
+ })).sort((a, b) => {
182
+ const result = compare(a.descriptor, b.descriptor);
183
+ if (result !== 0) return result;
184
+ return a.index - b.index;
185
+ }).map((entry) => entry.descriptor) });
186
+ },
187
+ pick(names) {
188
+ const picked = [];
189
+ const pickedNames = /* @__PURE__ */ new Set();
190
+ for (const name of names) {
191
+ if (pickedNames.has(name)) throw new Error(`Theme collection pick already includes theme "${name}"`);
192
+ pickedNames.add(name);
193
+ const descriptor = themesByName.get(name);
194
+ if (descriptor == null) throw new Error(`Theme collection does not contain theme "${name}"`);
195
+ picked.push(descriptor);
196
+ }
197
+ return createThemeCollection({ themes: picked });
198
+ },
199
+ registerInto(resolver) {
200
+ for (const descriptor of allThemes) resolver.registerThemeIfAbsent(descriptor.name, descriptor.load);
201
+ }
202
+ };
203
+ }
204
+ function getCollectionEntries(input) {
205
+ if (isThemeCollectionEntry(input)) return [input];
206
+ return input;
207
+ }
208
+ function isThemeCollectionEntry(input) {
209
+ return isThemeCollectionSource(input) || isThemeDescriptor(input);
210
+ }
211
+ function isThemeDescriptor(input) {
212
+ return typeof input.name === "string" && typeof input.load === "function";
213
+ }
214
+ function isThemeCollectionSource(entry) {
215
+ return typeof entry.getThemes === "function";
216
+ }
217
+ function unwrapDefault(value) {
218
+ return value !== null && typeof value === "object" && "default" in value ? value.default : value;
219
+ }
220
+ var DuplicateThemeError = class extends Error {
221
+ constructor(name) {
222
+ super(`Theme "${name}" is already registered`);
223
+ this.name = "DuplicateThemeError";
224
+ }
225
+ };
226
+ var UnregisteredThemeError = class extends Error {
227
+ constructor(name) {
228
+ super(`No loader registered for theme "${name}"`);
229
+ this.name = "UnregisteredThemeError";
230
+ }
231
+ };
232
+ var UnresolvedThemeError = class extends Error {
233
+ constructor(name) {
234
+ super(`Theme "${name}" has not been resolved`);
235
+ this.name = "UnresolvedThemeError";
236
+ }
237
+ };
238
+ function createThemeResolver() {
239
+ const loaders = /* @__PURE__ */ new Map();
240
+ const resolved = /* @__PURE__ */ new Map();
241
+ const inflight = /* @__PURE__ */ new Map();
242
+ let cacheGeneration = 0;
243
+ function registerTheme(name, loader) {
244
+ if (loaders.has(name)) throw new DuplicateThemeError(name);
245
+ loaders.set(name, loader);
246
+ }
247
+ function registerThemeIfAbsent(name, loader) {
248
+ if (loaders.has(name)) return false;
249
+ loaders.set(name, loader);
250
+ return true;
251
+ }
252
+ function hasRegisteredTheme(name) {
253
+ return loaders.has(name);
254
+ }
255
+ function resolveTheme2(name) {
256
+ const cached = resolved.get(name);
257
+ if (cached !== void 0) return Promise.resolve(cached);
258
+ const existing = inflight.get(name);
259
+ if (existing !== void 0) return existing;
260
+ const loader = loaders.get(name);
261
+ if (loader === void 0) return Promise.reject(new UnregisteredThemeError(name));
262
+ const generation = cacheGeneration;
263
+ const promise = loader().then((result) => {
264
+ const theme = unwrapDefault(result);
265
+ if (generation === cacheGeneration) resolved.set(name, theme);
266
+ if (inflight.get(name) === promise) inflight.delete(name);
267
+ return theme;
268
+ }).catch((err) => {
269
+ if (inflight.get(name) === promise) inflight.delete(name);
270
+ throw err;
271
+ });
272
+ inflight.set(name, promise);
273
+ return promise;
274
+ }
275
+ function resolveThemes2(names) {
276
+ return Promise.all(names.map((name) => resolveTheme2(name)));
277
+ }
278
+ function seedResolvedTheme(name, theme) {
279
+ resolved.set(name, theme);
280
+ }
281
+ function seedResolvedThemes(entries) {
282
+ for (const [name, theme] of entries) seedResolvedTheme(name, theme);
283
+ }
284
+ function getResolvedTheme(name) {
285
+ return resolved.get(name);
286
+ }
287
+ function getResolvedThemes2(names) {
288
+ const themes = [];
289
+ for (const name of names) {
290
+ const theme = resolved.get(name);
291
+ if (theme === void 0) throw new UnresolvedThemeError(name);
292
+ themes.push(theme);
293
+ }
294
+ return themes;
295
+ }
296
+ function hasResolvedTheme(name) {
297
+ return resolved.has(name);
298
+ }
299
+ function hasResolvedThemes2(names) {
300
+ for (const name of names) if (!resolved.has(name)) return false;
301
+ return true;
302
+ }
303
+ function getResolvedOrResolveTheme2(name) {
304
+ const cached = resolved.get(name);
305
+ if (cached !== void 0) return cached;
306
+ return resolveTheme2(name);
307
+ }
308
+ function clearResolvedThemes() {
309
+ cacheGeneration++;
310
+ resolved.clear();
311
+ inflight.clear();
312
+ }
313
+ return {
314
+ clearResolvedThemes,
315
+ getResolvedOrResolveTheme: getResolvedOrResolveTheme2,
316
+ getResolvedTheme,
317
+ getResolvedThemes: getResolvedThemes2,
318
+ hasRegisteredTheme,
319
+ hasResolvedTheme,
320
+ hasResolvedThemes: hasResolvedThemes2,
321
+ registerTheme,
322
+ registerThemeIfAbsent,
323
+ resolveTheme: resolveTheme2,
324
+ resolveThemes: resolveThemes2,
325
+ seedResolvedTheme,
326
+ seedResolvedThemes
327
+ };
328
+ }
329
+ const themeResolver = createThemeResolver();
330
+ function attachResolvedThemes(themes, highlighter2) {
331
+ themes = Array.isArray(themes) ? themes : [themes];
332
+ for (let themeRef of themes) {
333
+ let resolvedTheme;
334
+ if (typeof themeRef === "string") {
335
+ resolvedTheme = themeResolver.getResolvedTheme(themeRef);
336
+ if (resolvedTheme == null) throw new Error(`loadResolvedThemes: ${themeRef} is not resolved, you must resolve it before calling loadResolvedThemes`);
337
+ } else {
338
+ resolvedTheme = themeRef;
339
+ themeRef = themeRef.name;
340
+ if (themeResolver.getResolvedTheme(themeRef) == null) themeResolver.seedResolvedTheme(themeRef, resolvedTheme);
341
+ }
342
+ if (AttachedThemes.has(themeRef)) continue;
343
+ AttachedThemes.add(themeRef);
344
+ highlighter2.loadThemeSync(resolvedTheme);
345
+ }
346
+ }
347
+ function createTheme({ name, load, colorScheme, collection, displayName }) {
348
+ return {
349
+ name,
350
+ colorScheme,
351
+ collection,
352
+ displayName,
353
+ load: normalizingLoader(load)
354
+ };
355
+ }
356
+ function normalizingLoader(loader) {
357
+ return async () => {
358
+ return normalizeTheme(unwrapDefault(await loader()));
359
+ };
360
+ }
361
+ const PIERRE_COLLECTION = "pierre";
362
+ const DARK_PIERRE_THEMES = [
363
+ "pierre-dark",
364
+ "pierre-dark-soft",
365
+ "pierre-dark-vibrant",
366
+ "pierre-dark-protanopia-deuteranopia",
367
+ "pierre-dark-tritanopia"
368
+ ];
369
+ const LIGHT_PIERRE_THEMES = [
370
+ "pierre-light",
371
+ "pierre-light-soft",
372
+ "pierre-light-vibrant",
373
+ "pierre-light-protanopia-deuteranopia",
374
+ "pierre-light-tritanopia"
375
+ ];
376
+ const PIERRE_THEMES = [...LIGHT_PIERRE_THEMES, ...DARK_PIERRE_THEMES];
377
+ const LIGHT_PIERRE_THEME_NAMES = new Set(LIGHT_PIERRE_THEMES);
378
+ function pierreColorScheme(name) {
379
+ if (LIGHT_PIERRE_THEME_NAMES.has(name)) return "light";
380
+ return "dark";
381
+ }
382
+ const PIERRE_THEME_DISPLAY_NAMES = {
383
+ "pierre-dark": "Pierre Dark",
384
+ "pierre-dark-soft": "Pierre Dark Soft",
385
+ "pierre-dark-vibrant": "Pierre Dark Vibrant",
386
+ "pierre-dark-protanopia-deuteranopia": "Pierre Dark Protanopia & Deuteranopia",
387
+ "pierre-dark-tritanopia": "Pierre Dark Tritanopia",
388
+ "pierre-light": "Pierre Light",
389
+ "pierre-light-soft": "Pierre Light Soft",
390
+ "pierre-light-vibrant": "Pierre Light Vibrant",
391
+ "pierre-light-protanopia-deuteranopia": "Pierre Light Protanopia & Deuteranopia",
392
+ "pierre-light-tritanopia": "Pierre Light Tritanopia"
393
+ };
394
+ const PIERRE_THEME_IMPORTS = {
395
+ "pierre-dark": () => __vitePreload(() => import("./pierre-dark-BL-l9r39.js"), true ? [] : void 0, import.meta.url),
396
+ "pierre-dark-soft": () => __vitePreload(() => import("./pierre-dark-soft-B6TBhICr.js"), true ? [] : void 0, import.meta.url),
397
+ "pierre-dark-vibrant": () => __vitePreload(() => import("./pierre-dark-vibrant-yElMGqZN.js"), true ? [] : void 0, import.meta.url),
398
+ "pierre-dark-protanopia-deuteranopia": () => __vitePreload(() => import("./pierre-dark-protanopia-deuteranopia-BBjGuJQU.js"), true ? [] : void 0, import.meta.url),
399
+ "pierre-dark-tritanopia": () => __vitePreload(() => import("./pierre-dark-tritanopia-f-j_EX9A.js"), true ? [] : void 0, import.meta.url),
400
+ "pierre-light": () => __vitePreload(() => import("./pierre-light-BUzWTcjO.js"), true ? [] : void 0, import.meta.url),
401
+ "pierre-light-soft": () => __vitePreload(() => import("./pierre-light-soft-CCMU-Zh0.js"), true ? [] : void 0, import.meta.url),
402
+ "pierre-light-vibrant": () => __vitePreload(() => import("./pierre-light-vibrant-BRUbQnMc.js"), true ? [] : void 0, import.meta.url),
403
+ "pierre-light-protanopia-deuteranopia": () => __vitePreload(() => import("./pierre-light-protanopia-deuteranopia-DlvVSCaI.js"), true ? [] : void 0, import.meta.url),
404
+ "pierre-light-tritanopia": () => __vitePreload(() => import("./pierre-light-tritanopia-v4xacE1C.js"), true ? [] : void 0, import.meta.url)
405
+ };
406
+ function createPierreTheme(name) {
407
+ return createTheme({
408
+ name,
409
+ collection: PIERRE_COLLECTION,
410
+ colorScheme: pierreColorScheme(name),
411
+ displayName: PIERRE_THEME_DISPLAY_NAMES[name],
412
+ load: PIERRE_THEME_IMPORTS[name]
413
+ });
414
+ }
415
+ const pierreThemes = createThemeCollection({ themes: PIERRE_THEMES.map((name) => createPierreTheme(name)) });
416
+ const SHIKI_COLLECTION = "shiki";
417
+ const LIGHT_SHIKI_THEMES = [
418
+ "ayu-light",
419
+ "catppuccin-latte",
420
+ "everforest-light",
421
+ "github-light",
422
+ "github-light-default",
423
+ "github-light-high-contrast",
424
+ "gruvbox-light-hard",
425
+ "gruvbox-light-medium",
426
+ "gruvbox-light-soft",
427
+ "horizon-bright",
428
+ "kanagawa-lotus",
429
+ "light-plus",
430
+ "material-theme-lighter",
431
+ "min-light",
432
+ "night-owl-light",
433
+ "one-light",
434
+ "rose-pine-dawn",
435
+ "slack-ochin",
436
+ "snazzy-light",
437
+ "solarized-light",
438
+ "vitesse-light"
439
+ ];
440
+ const DARK_SHIKI_THEMES = [
441
+ "andromeeda",
442
+ "aurora-x",
443
+ "ayu-dark",
444
+ "ayu-mirage",
445
+ "catppuccin-frappe",
446
+ "catppuccin-macchiato",
447
+ "catppuccin-mocha",
448
+ "dark-plus",
449
+ "dracula",
450
+ "dracula-soft",
451
+ "everforest-dark",
452
+ "github-dark",
453
+ "github-dark-default",
454
+ "github-dark-dimmed",
455
+ "github-dark-high-contrast",
456
+ "gruvbox-dark-hard",
457
+ "gruvbox-dark-medium",
458
+ "gruvbox-dark-soft",
459
+ "horizon",
460
+ "houston",
461
+ "kanagawa-dragon",
462
+ "kanagawa-wave",
463
+ "laserwave",
464
+ "material-theme",
465
+ "material-theme-darker",
466
+ "material-theme-ocean",
467
+ "material-theme-palenight",
468
+ "min-dark",
469
+ "monokai",
470
+ "night-owl",
471
+ "nord",
472
+ "one-dark-pro",
473
+ "plastic",
474
+ "poimandres",
475
+ "red",
476
+ "rose-pine",
477
+ "rose-pine-moon",
478
+ "slack-dark",
479
+ "solarized-dark",
480
+ "synthwave-84",
481
+ "tokyo-night",
482
+ "vesper",
483
+ "vitesse-black",
484
+ "vitesse-dark"
485
+ ];
486
+ const LIGHT_SHIKI_THEME_NAMES = new Set(LIGHT_SHIKI_THEMES);
487
+ function shikiColorScheme(name) {
488
+ if (LIGHT_SHIKI_THEME_NAMES.has(name)) return "light";
489
+ return "dark";
490
+ }
491
+ const SHIKI_THEME_IMPORTS = {
492
+ andromeeda: () => __vitePreload(() => import("./andromeeda-C847lm7Z.js"), true ? [] : void 0, import.meta.url),
493
+ "aurora-x": () => __vitePreload(() => import("./aurora-x-wJ4-eM2h.js"), true ? [] : void 0, import.meta.url),
494
+ "ayu-dark": () => __vitePreload(() => import("./ayu-dark-rtpbXCNg.js"), true ? [] : void 0, import.meta.url),
495
+ "ayu-light": () => __vitePreload(() => import("./ayu-light-BCZDSyV8.js"), true ? [] : void 0, import.meta.url),
496
+ "ayu-mirage": () => __vitePreload(() => import("./ayu-mirage-BVoH71sA.js"), true ? [] : void 0, import.meta.url),
497
+ "catppuccin-frappe": () => __vitePreload(() => import("./catppuccin-frappe-CsW6iLIR.js"), true ? [] : void 0, import.meta.url),
498
+ "catppuccin-latte": () => __vitePreload(() => import("./catppuccin-latte-reHbSDAH.js"), true ? [] : void 0, import.meta.url),
499
+ "catppuccin-macchiato": () => __vitePreload(() => import("./catppuccin-macchiato-rSGd47q5.js"), true ? [] : void 0, import.meta.url),
500
+ "catppuccin-mocha": () => __vitePreload(() => import("./catppuccin-mocha-C6c0_b-7.js"), true ? [] : void 0, import.meta.url),
501
+ "dark-plus": () => __vitePreload(() => import("./dark-plus-DmZ1Dzd4.js"), true ? [] : void 0, import.meta.url),
502
+ dracula: () => __vitePreload(() => import("./dracula-B8-AVrwI.js"), true ? [] : void 0, import.meta.url),
503
+ "dracula-soft": () => __vitePreload(() => import("./dracula-soft-BHeefow7.js"), true ? [] : void 0, import.meta.url),
504
+ "everforest-dark": () => __vitePreload(() => import("./everforest-dark-Cg1xdODP.js"), true ? [] : void 0, import.meta.url),
505
+ "everforest-light": () => __vitePreload(() => import("./everforest-light-BmTD3bxe.js"), true ? [] : void 0, import.meta.url),
506
+ "github-dark": () => __vitePreload(() => import("./github-dark-O22yVQaY.js"), true ? [] : void 0, import.meta.url),
507
+ "github-dark-default": () => __vitePreload(() => import("./github-dark-default-DB2Hkvqn.js"), true ? [] : void 0, import.meta.url),
508
+ "github-dark-dimmed": () => __vitePreload(() => import("./github-dark-dimmed-CMZ_OfqC.js"), true ? [] : void 0, import.meta.url),
509
+ "github-dark-high-contrast": () => __vitePreload(() => import("./github-dark-high-contrast-DmxWVmCU.js"), true ? [] : void 0, import.meta.url),
510
+ "github-light": () => __vitePreload(() => import("./github-light-BTbR9xVK.js"), true ? [] : void 0, import.meta.url),
511
+ "github-light-default": () => __vitePreload(() => import("./github-light-default-DWEonwFe.js"), true ? [] : void 0, import.meta.url),
512
+ "github-light-high-contrast": () => __vitePreload(() => import("./github-light-high-contrast-WJ_cPDts.js"), true ? [] : void 0, import.meta.url),
513
+ "gruvbox-dark-hard": () => __vitePreload(() => import("./gruvbox-dark-hard-DVsRsETr.js"), true ? [] : void 0, import.meta.url),
514
+ "gruvbox-dark-medium": () => __vitePreload(() => import("./gruvbox-dark-medium-B5JBrQdg.js"), true ? [] : void 0, import.meta.url),
515
+ "gruvbox-dark-soft": () => __vitePreload(() => import("./gruvbox-dark-soft-Db-YOqRx.js"), true ? [] : void 0, import.meta.url),
516
+ "gruvbox-light-hard": () => __vitePreload(() => import("./gruvbox-light-hard-CXzJt7DI.js"), true ? [] : void 0, import.meta.url),
517
+ "gruvbox-light-medium": () => __vitePreload(() => import("./gruvbox-light-medium-B89RAI1Y.js"), true ? [] : void 0, import.meta.url),
518
+ "gruvbox-light-soft": () => __vitePreload(() => import("./gruvbox-light-soft-Cs0hTZYv.js"), true ? [] : void 0, import.meta.url),
519
+ horizon: () => __vitePreload(() => import("./horizon-DWzh3z5C.js"), true ? [] : void 0, import.meta.url),
520
+ "horizon-bright": () => __vitePreload(() => import("./horizon-bright-BJQsV5UY.js"), true ? [] : void 0, import.meta.url),
521
+ houston: () => __vitePreload(() => import("./houston-CF_ws8Cq.js"), true ? [] : void 0, import.meta.url),
522
+ "kanagawa-dragon": () => __vitePreload(() => import("./kanagawa-dragon-BzrndB3G.js"), true ? [] : void 0, import.meta.url),
523
+ "kanagawa-lotus": () => __vitePreload(() => import("./kanagawa-lotus-BMbWLXSu.js"), true ? [] : void 0, import.meta.url),
524
+ "kanagawa-wave": () => __vitePreload(() => import("./kanagawa-wave-OC_VodQx.js"), true ? [] : void 0, import.meta.url),
525
+ laserwave: () => __vitePreload(() => import("./laserwave-DF03wMlf.js"), true ? [] : void 0, import.meta.url),
526
+ "light-plus": () => __vitePreload(() => import("./light-plus-DS08Xg5J.js"), true ? [] : void 0, import.meta.url),
527
+ "material-theme": () => __vitePreload(() => import("./material-theme-B8B2U48Q.js"), true ? [] : void 0, import.meta.url),
528
+ "material-theme-darker": () => __vitePreload(() => import("./material-theme-darker-BV0iY_T3.js"), true ? [] : void 0, import.meta.url),
529
+ "material-theme-lighter": () => __vitePreload(() => import("./material-theme-lighter-DrzybSTF.js"), true ? [] : void 0, import.meta.url),
530
+ "material-theme-ocean": () => __vitePreload(() => import("./material-theme-ocean-BRPLVReX.js"), true ? [] : void 0, import.meta.url),
531
+ "material-theme-palenight": () => __vitePreload(() => import("./material-theme-palenight-DSJwsR_D.js"), true ? [] : void 0, import.meta.url),
532
+ "min-dark": () => __vitePreload(() => import("./min-dark-BNaN9fWk.js"), true ? [] : void 0, import.meta.url),
533
+ "min-light": () => __vitePreload(() => import("./min-light-CMrjentn.js"), true ? [] : void 0, import.meta.url),
534
+ monokai: () => __vitePreload(() => import("./monokai-BL-7sM2b.js"), true ? [] : void 0, import.meta.url),
535
+ "night-owl": () => __vitePreload(() => import("./night-owl-DSS199ra.js"), true ? [] : void 0, import.meta.url),
536
+ "night-owl-light": () => __vitePreload(() => import("./night-owl-light-gC6E-Eh2.js"), true ? [] : void 0, import.meta.url),
537
+ nord: () => __vitePreload(() => import("./nord-CvDbBq5M.js"), true ? [] : void 0, import.meta.url),
538
+ "one-dark-pro": () => __vitePreload(() => import("./one-dark-pro-DfmyFT_9.js"), true ? [] : void 0, import.meta.url),
539
+ "one-light": () => __vitePreload(() => import("./one-light-B0cTzZyr.js"), true ? [] : void 0, import.meta.url),
540
+ plastic: () => __vitePreload(() => import("./plastic-BjwMpBc0.js"), true ? [] : void 0, import.meta.url),
541
+ poimandres: () => __vitePreload(() => import("./poimandres-ChWyhPrn.js"), true ? [] : void 0, import.meta.url),
542
+ red: () => __vitePreload(() => import("./red-BcXR4G_B.js"), true ? [] : void 0, import.meta.url),
543
+ "rose-pine": () => __vitePreload(() => import("./rose-pine-DsUfEP3G.js"), true ? [] : void 0, import.meta.url),
544
+ "rose-pine-dawn": () => __vitePreload(() => import("./rose-pine-dawn-BvRaiqBN.js"), true ? [] : void 0, import.meta.url),
545
+ "rose-pine-moon": () => __vitePreload(() => import("./rose-pine-moon-B51k6Eh0.js"), true ? [] : void 0, import.meta.url),
546
+ "slack-dark": () => __vitePreload(() => import("./slack-dark-BEe10hxO.js"), true ? [] : void 0, import.meta.url),
547
+ "slack-ochin": () => __vitePreload(() => import("./slack-ochin-BKmu9pBc.js"), true ? [] : void 0, import.meta.url),
548
+ "snazzy-light": () => __vitePreload(() => import("./snazzy-light-Dcvd-ZyI.js"), true ? [] : void 0, import.meta.url),
549
+ "solarized-dark": () => __vitePreload(() => import("./solarized-dark-9CqJc6gu.js"), true ? [] : void 0, import.meta.url),
550
+ "solarized-light": () => __vitePreload(() => import("./solarized-light-CahvOdlg.js"), true ? [] : void 0, import.meta.url),
551
+ "synthwave-84": () => __vitePreload(() => import("./synthwave-84-CoUef9sh.js"), true ? [] : void 0, import.meta.url),
552
+ "tokyo-night": () => __vitePreload(() => import("./tokyo-night-DjtLpAEY.js"), true ? [] : void 0, import.meta.url),
553
+ vesper: () => __vitePreload(() => import("./vesper-D0zf0Dl2.js"), true ? [] : void 0, import.meta.url),
554
+ "vitesse-black": () => __vitePreload(() => import("./vitesse-black-BqNLki8b.js"), true ? [] : void 0, import.meta.url),
555
+ "vitesse-dark": () => __vitePreload(() => import("./vitesse-dark-jJ32WhwH.js"), true ? [] : void 0, import.meta.url),
556
+ "vitesse-light": () => __vitePreload(() => import("./vitesse-light-476zM4e6.js"), true ? [] : void 0, import.meta.url)
557
+ };
558
+ function createShikiTheme(name) {
559
+ return createTheme({
560
+ name,
561
+ collection: SHIKI_COLLECTION,
562
+ colorScheme: shikiColorScheme(name),
563
+ load: SHIKI_THEME_IMPORTS[name]
564
+ });
565
+ }
566
+ const shikiThemes = createThemeCollection({ themes: Object.freeze([...LIGHT_SHIKI_THEMES.map((name) => createShikiTheme(name)), ...DARK_SHIKI_THEMES.map((name) => createShikiTheme(name))]) });
567
+ createThemeCollection({ themes: [pierreThemes, shikiThemes] });
568
+ function prepareThemeResolution(themeName) {
569
+ if (isWorkerContext()) throw new Error(`Theme "${themeName}" cannot be resolved from a worker context. Themes must be pre-resolved on the main thread and passed to the worker via the resolvedLanguages parameter.`);
570
+ if (themeResolver.hasRegisteredTheme(themeName)) return;
571
+ const descriptor = shikiThemes.getTheme(themeName);
572
+ if (descriptor != null) {
573
+ themeResolver.registerThemeIfAbsent(descriptor.name, descriptor.load);
574
+ return;
575
+ }
576
+ throw new Error(`No valid theme loader registered for "${themeName}"`);
577
+ }
578
+ function validateResolvedThemeName(themeName, theme) {
579
+ if (theme.name !== themeName) throw new Error(`resolvedTheme: themeName: ${themeName} does not match theme.name: ${theme.name}`);
580
+ }
581
+ async function resolveTheme(themeName) {
582
+ prepareThemeResolution(themeName);
583
+ const theme = await themeResolver.resolveTheme(themeName);
584
+ validateResolvedThemeName(themeName, theme);
585
+ return theme;
586
+ }
587
+ function getResolvedOrResolveTheme(themeName) {
588
+ return themeResolver.getResolvedTheme(themeName) ?? resolveTheme(themeName);
589
+ }
590
+ let highlighter;
591
+ async function getSharedHighlighter({ themes, langs, preferredHighlighter = "shiki-js" }) {
592
+ highlighter ??= createHighlighter({
593
+ themes: [],
594
+ langs: ["text"],
595
+ engine: preferredHighlighter === "shiki-wasm" ? createOnigurumaEngine(__vitePreload(() => import("./wasm-DDgzZJey.js"), true ? [] : void 0, import.meta.url)) : createJavaScriptRegexEngine()
596
+ });
597
+ const instance = isHighlighterLoading(highlighter) ? await highlighter : highlighter;
598
+ highlighter = instance;
599
+ const languageLoaders = [];
600
+ for (const language of Array.from(new Set(langs))) {
601
+ if (language === "text" || language === "ansi") continue;
602
+ const maybeResolvedLanguage = getResolvedOrResolveLanguage(language);
603
+ if ("then" in maybeResolvedLanguage) languageLoaders.push(maybeResolvedLanguage);
604
+ else attachResolvedLanguages(maybeResolvedLanguage, instance);
605
+ }
606
+ const themeLoaders = [];
607
+ for (const themeName of themes) {
608
+ const maybeResolvedTheme = getResolvedOrResolveTheme(themeName);
609
+ if ("then" in maybeResolvedTheme) themeLoaders.push(maybeResolvedTheme);
610
+ else attachResolvedThemes(maybeResolvedTheme, highlighter);
611
+ }
612
+ if (languageLoaders.length > 0 || themeLoaders.length > 0) await Promise.all([Promise.all(languageLoaders).then((languages) => {
613
+ attachResolvedLanguages(languages, instance);
614
+ }), Promise.all(themeLoaders).then((themes2) => {
615
+ attachResolvedThemes(themes2, instance);
616
+ })]);
617
+ return instance;
618
+ }
619
+ function getHighlighterIfLoaded(withSettings) {
620
+ if (highlighter == null || "then" in highlighter) return;
621
+ if (withSettings != null && (!areThemesAttached(withSettings.theme) || !areLanguagesAttached(withSettings.lang))) return;
622
+ return highlighter;
623
+ }
624
+ function isHighlighterLoading(h = highlighter) {
625
+ return h != null && "then" in h;
626
+ }
627
+ for (const descriptor of pierreThemes.getThemes()) themeResolver.registerThemeIfAbsent(descriptor.name, descriptor.load);
628
+ function areThemesEqual(themeA, themeB) {
629
+ if (themeA == null || themeB == null || typeof themeA === "string" || typeof themeB === "string") return themeA === themeB;
630
+ return themeA.dark === themeB.dark && themeA.light === themeB.light;
631
+ }
632
+ function createTextNodeElement(value) {
633
+ return {
634
+ type: "text",
635
+ value
636
+ };
637
+ }
638
+ function createHastElement({ tagName, children = [], properties = {} }) {
639
+ return {
640
+ type: "element",
641
+ tagName,
642
+ properties,
643
+ children
644
+ };
645
+ }
646
+ function createIconElement({ name, width = 16, height = 16, properties }) {
647
+ return createHastElement({
648
+ tagName: "svg",
649
+ properties: {
650
+ width,
651
+ height,
652
+ viewBox: "0 0 16 16",
653
+ ...properties
654
+ },
655
+ children: [createHastElement({
656
+ tagName: "use",
657
+ properties: { href: `#${name.replace(/^#/, "")}` }
658
+ })]
659
+ });
660
+ }
661
+ function findCodeElement(nodes) {
662
+ let firstChild = nodes.children[0];
663
+ while (firstChild != null) {
664
+ if (firstChild.type === "element" && firstChild.tagName === "code") return firstChild;
665
+ if ("children" in firstChild) firstChild = firstChild.children[0];
666
+ else firstChild = null;
667
+ }
668
+ }
669
+ function createGutterWrapper(children) {
670
+ return createHastElement({
671
+ tagName: "div",
672
+ properties: { "data-gutter": "" },
673
+ children
674
+ });
675
+ }
676
+ function createGutterItem(lineType, lineNumber, lineIndex, properties = {}) {
677
+ return createHastElement({
678
+ tagName: "div",
679
+ properties: {
680
+ "data-line-type": lineType,
681
+ "data-column-number": lineNumber,
682
+ "data-line-index": lineIndex,
683
+ ...properties
684
+ },
685
+ children: lineNumber != null ? [createHastElement({
686
+ tagName: "span",
687
+ properties: { "data-line-number-content": "" },
688
+ children: [createTextNodeElement(`${lineNumber}`)]
689
+ })] : void 0
690
+ });
691
+ }
692
+ function createGutterGap(type, bufferType, size) {
693
+ return createHastElement({
694
+ tagName: "div",
695
+ properties: {
696
+ "data-gutter-buffer": bufferType,
697
+ "data-buffer-size": size,
698
+ "data-line-type": bufferType === "annotation" ? void 0 : type,
699
+ style: bufferType === "annotation" ? `grid-row: span ${size};` : `grid-row: span ${size};min-height:calc(${size} * 1lh);`
700
+ }
701
+ });
702
+ }
703
+ function hasResolvedThemes(themeNames) {
704
+ return themeResolver.hasResolvedThemes(themeNames);
705
+ }
706
+ function areFileRenderOptionsEqual(optionsA, optionsB) {
707
+ return areThemesEqual(optionsA.theme, optionsB.theme) && optionsA.useTokenTransformer === optionsB.useTokenTransformer && optionsA.tokenizeMaxLineLength === optionsB.tokenizeMaxLineLength;
708
+ }
709
+ const CUSTOM_EXTENSION_TO_FILE_FORMAT = /* @__PURE__ */ new Map();
710
+ let customExtensionsVersion = 0;
711
+ const EXTENSION_TO_FILE_FORMAT = {
712
+ "1c": "1c",
713
+ abap: "abap",
714
+ as: "actionscript-3",
715
+ ada: "ada",
716
+ adb: "ada",
717
+ ads: "ada",
718
+ adoc: "asciidoc",
719
+ asciidoc: "asciidoc",
720
+ "component.html": "angular-html",
721
+ "component.ts": "angular-ts",
722
+ conf: "nginx",
723
+ htaccess: "apache",
724
+ cls: "tex",
725
+ trigger: "apex",
726
+ apl: "apl",
727
+ applescript: "applescript",
728
+ scpt: "applescript",
729
+ ara: "ara",
730
+ asm: "asm",
731
+ s: "riscv",
732
+ astro: "astro",
733
+ awk: "awk",
734
+ bal: "ballerina",
735
+ sh: "zsh",
736
+ bash: "zsh",
737
+ bat: "cmd",
738
+ cmd: "cmd",
739
+ be: "berry",
740
+ beancount: "beancount",
741
+ bib: "bibtex",
742
+ bicep: "bicep",
743
+ "blade.php": "blade",
744
+ bsl: "bsl",
745
+ c: "c",
746
+ h: "objective-cpp",
747
+ cs: "csharp",
748
+ cpp: "cpp",
749
+ hpp: "cpp",
750
+ cc: "cpp",
751
+ cxx: "cpp",
752
+ hh: "cpp",
753
+ cdc: "cdc",
754
+ cairo: "cairo",
755
+ clar: "clarity",
756
+ clj: "clojure",
757
+ cljs: "clojure",
758
+ cljc: "clojure",
759
+ soy: "soy",
760
+ cmake: "cmake",
761
+ "CMakeLists.txt": "cmake",
762
+ cob: "cobol",
763
+ cbl: "cobol",
764
+ cobol: "cobol",
765
+ CODEOWNERS: "codeowners",
766
+ ql: "ql",
767
+ coffee: "coffeescript",
768
+ lisp: "lisp",
769
+ cl: "lisp",
770
+ lsp: "lisp",
771
+ log: "log",
772
+ v: "verilog",
773
+ cql: "cql",
774
+ cr: "crystal",
775
+ css: "css",
776
+ csv: "csv",
777
+ cue: "cue",
778
+ cypher: "cypher",
779
+ cyp: "cypher",
780
+ d: "d",
781
+ dart: "dart",
782
+ dax: "dax",
783
+ desktop: "desktop",
784
+ diff: "diff",
785
+ patch: "diff",
786
+ Dockerfile: "dockerfile",
787
+ dockerfile: "dockerfile",
788
+ env: "dotenv",
789
+ dm: "dream-maker",
790
+ edge: "edge",
791
+ el: "emacs-lisp",
792
+ ex: "elixir",
793
+ exs: "elixir",
794
+ elm: "elm",
795
+ erb: "erb",
796
+ erl: "erlang",
797
+ hrl: "erlang",
798
+ f: "fortran-fixed-form",
799
+ for: "fortran-fixed-form",
800
+ fs: "fsharp",
801
+ fsi: "fsharp",
802
+ fsx: "fsharp",
803
+ f03: "f03",
804
+ f08: "f08",
805
+ f18: "f18",
806
+ f77: "f77",
807
+ f90: "fortran-free-form",
808
+ f95: "fortran-free-form",
809
+ fnl: "fennel",
810
+ fish: "fish",
811
+ ftl: "ftl",
812
+ tres: "gdresource",
813
+ res: "gdresource",
814
+ gd: "gdscript",
815
+ gdshader: "gdshader",
816
+ gs: "genie",
817
+ feature: "gherkin",
818
+ COMMIT_EDITMSG: "git-commit",
819
+ "git-rebase-todo": "git-rebase",
820
+ gjs: "glimmer-js",
821
+ gleam: "gleam",
822
+ gts: "glimmer-ts",
823
+ glsl: "glsl",
824
+ vert: "glsl",
825
+ frag: "glsl",
826
+ shader: "shaderlab",
827
+ gp: "gnuplot",
828
+ plt: "gnuplot",
829
+ gnuplot: "gnuplot",
830
+ go: "go",
831
+ graphql: "graphql",
832
+ gql: "graphql",
833
+ groovy: "groovy",
834
+ gvy: "groovy",
835
+ hack: "hack",
836
+ haml: "haml",
837
+ hbs: "handlebars",
838
+ handlebars: "handlebars",
839
+ hs: "haskell",
840
+ lhs: "haskell",
841
+ hx: "haxe",
842
+ hcl: "hcl",
843
+ hjson: "hjson",
844
+ hlsl: "hlsl",
845
+ fx: "hlsl",
846
+ html: "html",
847
+ htm: "html",
848
+ http: "http",
849
+ rest: "http",
850
+ hxml: "hxml",
851
+ hy: "hy",
852
+ imba: "imba",
853
+ ini: "ini",
854
+ cfg: "ini",
855
+ jade: "pug",
856
+ pug: "pug",
857
+ java: "java",
858
+ js: "javascript",
859
+ mjs: "javascript",
860
+ cjs: "javascript",
861
+ jinja: "jinja",
862
+ jinja2: "jinja",
863
+ j2: "jinja",
864
+ jison: "jison",
865
+ jl: "julia",
866
+ json: "json",
867
+ json5: "json5",
868
+ jsonc: "jsonc",
869
+ jsonl: "jsonl",
870
+ jsonnet: "jsonnet",
871
+ libsonnet: "jsonnet",
872
+ jssm: "jssm",
873
+ jsx: "jsx",
874
+ kt: "kotlin",
875
+ kts: "kts",
876
+ kql: "kusto",
877
+ tex: "tex",
878
+ ltx: "tex",
879
+ lean: "lean4",
880
+ less: "less",
881
+ liquid: "liquid",
882
+ lit: "lit",
883
+ ll: "llvm",
884
+ logo: "logo",
885
+ lua: "lua",
886
+ luau: "luau",
887
+ Makefile: "makefile",
888
+ mk: "makefile",
889
+ makefile: "makefile",
890
+ md: "markdown",
891
+ markdown: "markdown",
892
+ marko: "marko",
893
+ m: "wolfram",
894
+ mat: "matlab",
895
+ mdc: "mdc",
896
+ mdx: "mdx",
897
+ wiki: "wikitext",
898
+ mediawiki: "wikitext",
899
+ mmd: "mermaid",
900
+ mermaid: "mermaid",
901
+ mips: "mipsasm",
902
+ mojo: "mojo",
903
+ "🔥": "mojo",
904
+ move: "move",
905
+ nar: "narrat",
906
+ nf: "nextflow",
907
+ nim: "nim",
908
+ nims: "nim",
909
+ nimble: "nim",
910
+ nix: "nix",
911
+ nu: "nushell",
912
+ mm: "objective-cpp",
913
+ ml: "ocaml",
914
+ mli: "ocaml",
915
+ mll: "ocaml",
916
+ mly: "ocaml",
917
+ odin: "odin",
918
+ pas: "pascal",
919
+ p: "pascal",
920
+ pl: "prolog",
921
+ pm: "perl",
922
+ t: "perl",
923
+ raku: "raku",
924
+ p6: "raku",
925
+ pl6: "raku",
926
+ php: "php",
927
+ phtml: "php",
928
+ pls: "plsql",
929
+ sql: "sql",
930
+ po: "po",
931
+ polar: "polar",
932
+ pcss: "postcss",
933
+ pot: "pot",
934
+ potx: "potx",
935
+ pq: "powerquery",
936
+ pqm: "powerquery",
937
+ ps1: "powershell",
938
+ psm1: "powershell",
939
+ psd1: "powershell",
940
+ prisma: "prisma",
941
+ pro: "prolog",
942
+ P: "prolog",
943
+ properties: "properties",
944
+ proto: "protobuf",
945
+ pp: "puppet",
946
+ purs: "purescript",
947
+ py: "python",
948
+ pyw: "python",
949
+ pyi: "python",
950
+ BUCK: "python",
951
+ BUILD: "python",
952
+ PACKAGE: "python",
953
+ WORKSPACE: "python",
954
+ Tiltfile: "python",
955
+ bazel: "python",
956
+ bxl: "python",
957
+ bzl: "python",
958
+ bzlmod: "python",
959
+ star: "python",
960
+ sky: "python",
961
+ qml: "qml",
962
+ qmldir: "qmldir",
963
+ qss: "qss",
964
+ r: "r",
965
+ R: "r",
966
+ rkt: "racket",
967
+ rktl: "racket",
968
+ razor: "razor",
969
+ cshtml: "razor",
970
+ rb: "ruby",
971
+ rbw: "ruby",
972
+ reg: "reg",
973
+ regex: "regexp",
974
+ rel: "rel",
975
+ rs: "rust",
976
+ rst: "rst",
977
+ rake: "ruby",
978
+ gemspec: "ruby",
979
+ jbuilder: "ruby",
980
+ builder: "ruby",
981
+ rabl: "ruby",
982
+ arb: "ruby",
983
+ ru: "ruby",
984
+ podspec: "ruby",
985
+ Gemfile: "ruby",
986
+ Rakefile: "ruby",
987
+ Guardfile: "ruby",
988
+ Capfile: "ruby",
989
+ Berksfile: "ruby",
990
+ Brewfile: "ruby",
991
+ Vagrantfile: "ruby",
992
+ Thorfile: "ruby",
993
+ Appraisals: "ruby",
994
+ Dangerfile: "ruby",
995
+ sas: "sas",
996
+ sass: "sass",
997
+ scala: "scala",
998
+ sc: "scala",
999
+ scm: "scheme",
1000
+ ss: "scheme",
1001
+ sld: "scheme",
1002
+ scss: "scss",
1003
+ sdbl: "sdbl",
1004
+ shadergraph: "shader",
1005
+ st: "smalltalk",
1006
+ sol: "solidity",
1007
+ sparql: "sparql",
1008
+ rq: "sparql",
1009
+ spl: "splunk",
1010
+ config: "ssh-config",
1011
+ do: "stata",
1012
+ ado: "stata",
1013
+ dta: "stata",
1014
+ styl: "stylus",
1015
+ stylus: "stylus",
1016
+ svelte: "svelte",
1017
+ swift: "swift",
1018
+ sv: "system-verilog",
1019
+ svh: "system-verilog",
1020
+ service: "systemd",
1021
+ socket: "systemd",
1022
+ device: "systemd",
1023
+ timer: "systemd",
1024
+ talon: "talonscript",
1025
+ tasl: "tasl",
1026
+ tcl: "tcl",
1027
+ templ: "templ",
1028
+ tf: "tf",
1029
+ tfvars: "tfvars",
1030
+ toml: "toml",
1031
+ ts: "typescript",
1032
+ mts: "typescript",
1033
+ cts: "typescript",
1034
+ tsp: "typespec",
1035
+ tsv: "tsv",
1036
+ tsx: "tsx",
1037
+ ttl: "turtle",
1038
+ twig: "twig",
1039
+ typ: "typst",
1040
+ vv: "v",
1041
+ vala: "vala",
1042
+ vapi: "vala",
1043
+ vb: "vb",
1044
+ vbs: "vb",
1045
+ bas: "vb",
1046
+ vh: "verilog",
1047
+ vhd: "vhdl",
1048
+ vhdl: "vhdl",
1049
+ vim: "vimscript",
1050
+ vue: "vue",
1051
+ "vine.ts": "vue-vine",
1052
+ vy: "vyper",
1053
+ wasm: "wasm",
1054
+ wat: "wasm",
1055
+ wy: "文言",
1056
+ wgsl: "wgsl",
1057
+ wit: "wit",
1058
+ wl: "wolfram",
1059
+ nb: "wolfram",
1060
+ xml: "xml",
1061
+ xsl: "xsl",
1062
+ xslt: "xsl",
1063
+ yaml: "yaml",
1064
+ yml: "yml",
1065
+ zs: "zenscript",
1066
+ zig: "zig",
1067
+ zsh: "zsh",
1068
+ sty: "tex"
1069
+ };
1070
+ function getFiletypeFromFileName(fileName) {
1071
+ const format = matchFiletypeFromName(fileName);
1072
+ if (format != null) return format;
1073
+ const baseName = fileName.split(/[/\\]/).pop() ?? fileName;
1074
+ return baseName === fileName ? "text" : matchFiletypeFromName(baseName) ?? "text";
1075
+ }
1076
+ function matchFiletypeFromName(fileName) {
1077
+ if (CUSTOM_EXTENSION_TO_FILE_FORMAT.has(fileName)) return CUSTOM_EXTENSION_TO_FILE_FORMAT.get(fileName) ?? "text";
1078
+ if (Object.hasOwn(EXTENSION_TO_FILE_FORMAT, fileName)) return EXTENSION_TO_FILE_FORMAT[fileName] ?? null;
1079
+ const compoundMatch = fileName.match(/\.([^/\\]+\.[^/\\]+)$/);
1080
+ if (compoundMatch != null) {
1081
+ if (CUSTOM_EXTENSION_TO_FILE_FORMAT.has(compoundMatch[1])) return CUSTOM_EXTENSION_TO_FILE_FORMAT.get(compoundMatch[1]) ?? "text";
1082
+ if (Object.hasOwn(EXTENSION_TO_FILE_FORMAT, compoundMatch[1])) return EXTENSION_TO_FILE_FORMAT[compoundMatch[1]] ?? "text";
1083
+ }
1084
+ const simpleMatch = fileName.match(/\.([^.]+)$/)?.[1] ?? "";
1085
+ if (CUSTOM_EXTENSION_TO_FILE_FORMAT.has(simpleMatch)) return CUSTOM_EXTENSION_TO_FILE_FORMAT.get(simpleMatch) ?? "text";
1086
+ return Object.hasOwn(EXTENSION_TO_FILE_FORMAT, simpleMatch) ? EXTENSION_TO_FILE_FORMAT[simpleMatch] ?? "text" : null;
1087
+ }
1088
+ function getCustomExtensionsVersion() {
1089
+ return customExtensionsVersion;
1090
+ }
1091
+ function getCustomExtensionsMap() {
1092
+ return Object.fromEntries(CUSTOM_EXTENSION_TO_FILE_FORMAT);
1093
+ }
1094
+ function processLine(node, line, state) {
1095
+ const lineInfo = typeof state.lineInfo === "function" ? state.lineInfo(line) : state.lineInfo[line - 1];
1096
+ if (lineInfo == null) {
1097
+ const errorMessage = `processLine: line ${line}, contains no state.lineInfo`;
1098
+ console.error(errorMessage, {
1099
+ node,
1100
+ line,
1101
+ state
1102
+ });
1103
+ throw new Error(errorMessage);
1104
+ }
1105
+ node.tagName = "div";
1106
+ node.properties["data-line"] = lineInfo.lineNumber;
1107
+ node.properties["data-alt-line"] = lineInfo.altLineNumber;
1108
+ node.properties["data-line-type"] = lineInfo.type;
1109
+ node.properties["data-line-index"] = lineInfo.lineIndex;
1110
+ if (node.children.length === 0) node.children.push(createTextNodeElement("\n"));
1111
+ return node;
1112
+ }
1113
+ const NO_TOKEN = /* @__PURE__ */ Symbol("no-token");
1114
+ const MULTIPLE_TOKENS = /* @__PURE__ */ Symbol("multiple-tokens");
1115
+ function wrapTokenFragments(container) {
1116
+ const ownTokenChar = getTokenChar(container);
1117
+ if (ownTokenChar != null) return ownTokenChar;
1118
+ let containerTokenState = NO_TOKEN;
1119
+ const wrappedChildren = [];
1120
+ let currentTokenChildren = [];
1121
+ let currentTokenChar;
1122
+ const flushTokenChildren = () => {
1123
+ if (currentTokenChildren.length === 0 || currentTokenChar == null) {
1124
+ currentTokenChildren = [];
1125
+ currentTokenChar = void 0;
1126
+ return;
1127
+ }
1128
+ if (currentTokenChildren.length === 1) {
1129
+ const child = currentTokenChildren[0];
1130
+ if (child?.type === "element") {
1131
+ setTokenChar(child, currentTokenChar);
1132
+ for (const grandChild of child.children) stripTokenChar(grandChild);
1133
+ } else stripTokenChar(child);
1134
+ wrappedChildren.push(child);
1135
+ currentTokenChildren = [];
1136
+ currentTokenChar = void 0;
1137
+ return;
1138
+ }
1139
+ for (const child of currentTokenChildren) stripTokenChar(child);
1140
+ wrappedChildren.push(createHastElement({
1141
+ tagName: "span",
1142
+ properties: { "data-char": currentTokenChar },
1143
+ children: currentTokenChildren
1144
+ }));
1145
+ currentTokenChildren = [];
1146
+ currentTokenChar = void 0;
1147
+ };
1148
+ const mergeContainerTokenState = (childTokenState) => {
1149
+ if (childTokenState === NO_TOKEN) return;
1150
+ if (childTokenState === MULTIPLE_TOKENS) {
1151
+ containerTokenState = MULTIPLE_TOKENS;
1152
+ return;
1153
+ }
1154
+ if (containerTokenState === NO_TOKEN) {
1155
+ containerTokenState = childTokenState;
1156
+ return;
1157
+ }
1158
+ if (containerTokenState !== childTokenState) containerTokenState = MULTIPLE_TOKENS;
1159
+ };
1160
+ for (const child of container.children) {
1161
+ const childTokenState = child.type === "element" ? wrapTokenFragments(child) : NO_TOKEN;
1162
+ mergeContainerTokenState(childTokenState);
1163
+ if (typeof childTokenState !== "number") {
1164
+ flushTokenChildren();
1165
+ wrappedChildren.push(child);
1166
+ continue;
1167
+ }
1168
+ if (currentTokenChar != null && currentTokenChar !== childTokenState) flushTokenChildren();
1169
+ currentTokenChar ??= childTokenState;
1170
+ currentTokenChildren.push(child);
1171
+ }
1172
+ flushTokenChildren();
1173
+ container.children = wrappedChildren;
1174
+ return containerTokenState;
1175
+ }
1176
+ function getTokenChar(node) {
1177
+ const value = node.properties["data-char"];
1178
+ if (typeof value === "number") return value;
1179
+ }
1180
+ function stripTokenChar(node) {
1181
+ if (node.type !== "element") return;
1182
+ node.properties["data-char"] = void 0;
1183
+ for (const child of node.children) stripTokenChar(child);
1184
+ }
1185
+ function setTokenChar(node, char) {
1186
+ node.properties["data-char"] = char;
1187
+ }
1188
+ function transformerStyleToClass(options = {}) {
1189
+ const { classPrefix = "__shiki_", classSuffix = "", classReplacer = (className) => className } = options;
1190
+ const classToStyle = /* @__PURE__ */ new Map();
1191
+ function stringifyStyle(style) {
1192
+ return Object.entries(style).map(([key, value]) => `${key}:${value}`).join(";");
1193
+ }
1194
+ function registerStyle(style) {
1195
+ const str = typeof style === "string" ? style : stringifyStyle(style);
1196
+ let className = classPrefix + cyrb53(str) + classSuffix;
1197
+ className = classReplacer(className);
1198
+ if (!classToStyle.has(className)) classToStyle.set(className, typeof style === "string" ? style : { ...style });
1199
+ return className;
1200
+ }
1201
+ return {
1202
+ name: "@shikijs/transformers:style-to-class",
1203
+ pre(t) {
1204
+ if (!t.properties.style) return;
1205
+ const className = registerStyle(t.properties.style);
1206
+ delete t.properties.style;
1207
+ this.addClassToHast(t, className);
1208
+ },
1209
+ tokens(lines) {
1210
+ for (const line of lines) for (const token of line) {
1211
+ if (!token.htmlStyle) continue;
1212
+ const className = registerStyle(token.htmlStyle);
1213
+ token.htmlStyle = {};
1214
+ token.htmlAttrs ||= {};
1215
+ if (!token.htmlAttrs.class) token.htmlAttrs.class = className;
1216
+ else token.htmlAttrs.class += ` ${className}`;
1217
+ }
1218
+ },
1219
+ getClassRegistry() {
1220
+ return classToStyle;
1221
+ },
1222
+ getCSS() {
1223
+ let css = "";
1224
+ for (const [className, style] of classToStyle.entries()) css += `.${className}{${typeof style === "string" ? style : stringifyStyle(style)}}`;
1225
+ return css;
1226
+ },
1227
+ clearRegistry() {
1228
+ classToStyle.clear();
1229
+ }
1230
+ };
1231
+ }
1232
+ function cyrb53(str, seed = 0) {
1233
+ let h1 = 3735928559 ^ seed;
1234
+ let h2 = 1103547991 ^ seed;
1235
+ for (let i = 0, ch; i < str.length; i++) {
1236
+ ch = str.charCodeAt(i);
1237
+ h1 = Math.imul(h1 ^ ch, 2654435761);
1238
+ h2 = Math.imul(h2 ^ ch, 1597334677);
1239
+ }
1240
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
1241
+ h1 ^= Math.imul(h2 ^ h2 >>> 13, 3266489909);
1242
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
1243
+ h2 ^= Math.imul(h1 ^ h1 >>> 13, 3266489909);
1244
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36).slice(0, 6);
1245
+ }
1246
+ function createTransformerWithState(useTokenTransformer = false, useCSSClasses = false) {
1247
+ const state = { lineInfo: [] };
1248
+ const transformers = [{
1249
+ line(node) {
1250
+ delete node.properties.class;
1251
+ return node;
1252
+ },
1253
+ pre(pre) {
1254
+ const code = findCodeElement(pre);
1255
+ const children = [];
1256
+ if (code != null) {
1257
+ let index = 1;
1258
+ for (const node of code.children) {
1259
+ if (node.type !== "element") continue;
1260
+ if (useTokenTransformer) wrapTokenFragments(node);
1261
+ children.push(processLine(node, index, state));
1262
+ index++;
1263
+ }
1264
+ code.children = children;
1265
+ }
1266
+ return pre;
1267
+ },
1268
+ ...useTokenTransformer ? {
1269
+ tokens(lines) {
1270
+ for (const line of lines) {
1271
+ let col = 0;
1272
+ for (const token of line) {
1273
+ const tokenWithOriginalRange = token;
1274
+ tokenWithOriginalRange.__lineChar ??= col;
1275
+ col += token.content.length;
1276
+ }
1277
+ }
1278
+ },
1279
+ preprocess(_code, options) {
1280
+ options.mergeWhitespaces = "never";
1281
+ },
1282
+ span(hast, _line, _char, _lineElement, token) {
1283
+ if (token?.offset != null && token.content != null) {
1284
+ const tokenChar = token.__lineChar;
1285
+ if (tokenChar != null) hast.properties["data-char"] = tokenChar;
1286
+ return hast;
1287
+ }
1288
+ return hast;
1289
+ }
1290
+ } : null
1291
+ }];
1292
+ if (useCSSClasses) transformers.push(tokenStyleNormalizer, toClass);
1293
+ if (useTokenTransformer) transformers.push({ line: (node) => {
1294
+ if (node.type === "element" && node.children.length === 0) node.children.push({
1295
+ type: "element",
1296
+ tagName: "br",
1297
+ properties: {},
1298
+ children: []
1299
+ });
1300
+ return node;
1301
+ } });
1302
+ return {
1303
+ state,
1304
+ transformers,
1305
+ toClass
1306
+ };
1307
+ }
1308
+ const toClass = transformerStyleToClass({ classPrefix: "hl-" });
1309
+ const tokenStyleNormalizer = {
1310
+ name: "token-style-normalizer",
1311
+ tokens(lines) {
1312
+ for (const line of lines) for (const token of line) {
1313
+ if (token.htmlStyle != null) continue;
1314
+ const style = {};
1315
+ if (token.color != null) style.color = token.color;
1316
+ if (token.bgColor != null) style["background-color"] = token.bgColor;
1317
+ if (token.fontStyle != null && token.fontStyle !== 0) {
1318
+ if ((token.fontStyle & 1) !== 0) style["font-style"] = "italic";
1319
+ if ((token.fontStyle & 2) !== 0) style["font-weight"] = "bold";
1320
+ if ((token.fontStyle & 4) !== 0) style["text-decoration"] = "underline";
1321
+ }
1322
+ if (Object.keys(style).length > 0) token.htmlStyle = style;
1323
+ }
1324
+ }
1325
+ };
1326
+ function formatCSSVariablePrefix(type) {
1327
+ return `--${type === "token" ? "diffs-token" : "diffs"}-`;
1328
+ }
1329
+ const HEX_TRANSPARENT_RE = /^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/i;
1330
+ const ALPHA_ZERO_RE = /^0(?:\.0+)?%?$/;
1331
+ function getFunctionalAlpha(color) {
1332
+ const openParen = color.indexOf("(");
1333
+ if (openParen <= 0 || !color.endsWith(")")) return;
1334
+ const fn = color.slice(0, openParen).trim();
1335
+ if (!/^(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color)$/i.test(fn)) return;
1336
+ const inner = color.slice(openParen + 1, -1).trim();
1337
+ if (inner.length === 0) return;
1338
+ const slashIndex = inner.lastIndexOf("/");
1339
+ if (slashIndex !== -1) return inner.slice(slashIndex + 1).trim();
1340
+ if (/^(?:rgba|hsla)$/i.test(fn)) {
1341
+ const parts = inner.split(",");
1342
+ if (parts.length === 4) return parts[3]?.trim();
1343
+ }
1344
+ }
1345
+ function parseHexRgba(color) {
1346
+ const match = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})\b/i.exec(color.trim());
1347
+ if (match == null) return null;
1348
+ const hex = match[1];
1349
+ let expanded;
1350
+ let alpha = 1;
1351
+ if (hex.length === 3) expanded = hex.split("").map((c) => c + c).join("");
1352
+ else if (hex.length === 6) expanded = hex;
1353
+ else {
1354
+ expanded = hex.slice(0, 6);
1355
+ alpha = parseInt(hex.slice(6, 8), 16) / 255;
1356
+ }
1357
+ return [
1358
+ parseInt(expanded.slice(0, 2), 16),
1359
+ parseInt(expanded.slice(2, 4), 16),
1360
+ parseInt(expanded.slice(4, 6), 16),
1361
+ alpha
1362
+ ];
1363
+ }
1364
+ function relativeLuminance(color) {
1365
+ if (color == null) return null;
1366
+ const rgba = parseHexRgba(color);
1367
+ if (rgba == null) return null;
1368
+ const r = rgba[0] / 255;
1369
+ const g = rgba[1] / 255;
1370
+ const b = rgba[2] / 255;
1371
+ const channel = (v) => v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
1372
+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
1373
+ }
1374
+ function contrastRatio(a, b) {
1375
+ const [hi, lo] = a > b ? [a, b] : [b, a];
1376
+ return (hi + 0.05) / (lo + 0.05);
1377
+ }
1378
+ function compositeOverBg(fgColor, bgColor) {
1379
+ if (bgColor == null) return void 0;
1380
+ const fgParts = parseHexRgba(fgColor);
1381
+ const bgParts = parseHexRgba(bgColor);
1382
+ if (fgParts == null || bgParts == null) return void 0;
1383
+ const [fr, fg, fb, fa] = fgParts;
1384
+ const [br, bg, bb] = bgParts;
1385
+ return "#" + [
1386
+ Math.round(fr * fa + br * (1 - fa)),
1387
+ Math.round(fg * fa + bg * (1 - fa)),
1388
+ Math.round(fb * fa + bb * (1 - fa))
1389
+ ].map((v) => v.toString(16).padStart(2, "0")).join("");
1390
+ }
1391
+ function isFullyTransparent(color) {
1392
+ if (color == null) return false;
1393
+ const normalized = color.trim().toLowerCase();
1394
+ if (normalized === "transparent") return true;
1395
+ if (HEX_TRANSPARENT_RE.test(normalized)) return true;
1396
+ const alpha = getFunctionalAlpha(normalized);
1397
+ return alpha != null && ALPHA_ZERO_RE.test(alpha);
1398
+ }
1399
+ function isDarkSurface(bg, fgHint) {
1400
+ const fromBg = relativeLuminance(bg);
1401
+ if (fromBg != null) return fromBg < 0.4;
1402
+ const fromFg = relativeLuminance(fgHint);
1403
+ return fromFg != null ? fromFg > 0.6 : false;
1404
+ }
1405
+ function surfacesMatch(a, b) {
1406
+ if (a == null || b == null) return false;
1407
+ if (a.trim().toLowerCase() === b.trim().toLowerCase()) return true;
1408
+ const la = relativeLuminance(a);
1409
+ const lb = relativeLuminance(b);
1410
+ if (la == null || lb == null) return false;
1411
+ return Math.abs(la - lb) < 0.06;
1412
+ }
1413
+ function hoverWouldEraseText(hover, bg, fg) {
1414
+ if (bg == null || fg == null) return false;
1415
+ const hoverL = relativeLuminance(hover);
1416
+ const bgL = relativeLuminance(bg);
1417
+ const fgL = relativeLuminance(fg);
1418
+ if (hoverL == null || bgL == null || fgL == null) return false;
1419
+ return Math.abs(hoverL - fgL) < Math.abs(hoverL - bgL);
1420
+ }
1421
+ function pickReadableForeground(bg, candidates) {
1422
+ const bgL = relativeLuminance(bg);
1423
+ const firstDefined = candidates.find((candidate) => candidate != null && candidate !== "");
1424
+ if (bgL == null) return firstDefined;
1425
+ let best;
1426
+ let bestRatio = -1;
1427
+ for (const candidate of candidates) {
1428
+ if (candidate == null || candidate === "") continue;
1429
+ const candidateL = relativeLuminance(candidate);
1430
+ if (candidateL == null) continue;
1431
+ const ratio = contrastRatio(bgL, candidateL);
1432
+ if (ratio >= 3) return candidate;
1433
+ if (ratio > bestRatio) {
1434
+ best = candidate;
1435
+ bestRatio = ratio;
1436
+ }
1437
+ }
1438
+ return best ?? firstDefined;
1439
+ }
1440
+ function deriveMutedFg(primaryFg, bg) {
1441
+ if (bg == null) return primaryFg;
1442
+ const fgParts = parseHexRgba(primaryFg);
1443
+ const bgParts = parseHexRgba(bg);
1444
+ const bgL = relativeLuminance(bg);
1445
+ if (fgParts == null || bgParts == null || bgL == null) return `color-mix(in srgb, ${primaryFg} 70%, ${bg})`;
1446
+ const [fr, fg2, fb] = fgParts;
1447
+ const [br, bg3, bb] = bgParts;
1448
+ for (const weight of [
1449
+ 0.6,
1450
+ 0.7,
1451
+ 0.8,
1452
+ 0.9
1453
+ ]) {
1454
+ const hex = "#" + [
1455
+ Math.round(fr * weight + br * (1 - weight)),
1456
+ Math.round(fg2 * weight + bg3 * (1 - weight)),
1457
+ Math.round(fb * weight + bb * (1 - weight))
1458
+ ].map((v) => v.toString(16).padStart(2, "0")).join("");
1459
+ const L = relativeLuminance(hex);
1460
+ if (L != null && contrastRatio(bgL, L) >= 4.5) return hex;
1461
+ }
1462
+ return primaryFg;
1463
+ }
1464
+ const cache = /* @__PURE__ */ new WeakMap();
1465
+ function normalizeThemeColors(theme) {
1466
+ const cached = cache.get(theme);
1467
+ if (cached != null) return cached;
1468
+ const originalColors = theme.colors ?? {};
1469
+ const colors = { ...originalColors };
1470
+ const editorBackground = originalColors["editor.background"] ?? theme.bg;
1471
+ const editorForeground = originalColors["editor.foreground"] ?? theme.fg;
1472
+ const sidebarBackground = originalColors["sideBar.background"] ?? editorBackground;
1473
+ const sidebarForeground = originalColors["sideBar.foreground"] ?? editorForeground;
1474
+ fill(colors, "editor.background", editorBackground);
1475
+ fill(colors, "editor.foreground", editorForeground);
1476
+ fill(colors, "sideBar.background", sidebarBackground);
1477
+ fill(colors, "sideBar.foreground", sidebarForeground);
1478
+ fill(colors, "input.background", originalColors["input.background"] ?? sidebarBackground);
1479
+ fill(colors, "sideBarSectionHeader.foreground", originalColors["sideBarSectionHeader.foreground"] ?? sidebarForeground);
1480
+ fill(colors, "list.activeSelectionForeground", originalColors["list.activeSelectionForeground"] ?? sidebarForeground);
1481
+ fill(colors, "gitDecoration.addedResourceForeground", firstColor(originalColors["gitDecoration.addedResourceForeground"], originalColors["terminal.ansiGreen"], originalColors["editorGutter.addedBackground"]));
1482
+ fill(colors, "gitDecoration.modifiedResourceForeground", firstColor(originalColors["gitDecoration.modifiedResourceForeground"], originalColors["terminal.ansiBlue"], originalColors["editorGutter.modifiedBackground"]));
1483
+ fill(colors, "gitDecoration.deletedResourceForeground", firstColor(originalColors["gitDecoration.deletedResourceForeground"], originalColors["terminal.ansiRed"], originalColors["editorGutter.deletedBackground"]));
1484
+ const focusRing = (isFullyTransparent(originalColors["list.focusOutline"]) ? void 0 : originalColors["list.focusOutline"]) ?? (isFullyTransparent(originalColors["focusBorder"]) ? void 0 : originalColors["focusBorder"]);
1485
+ if (focusRing != null) colors["list.focusOutline"] = focusRing;
1486
+ else delete colors["list.focusOutline"];
1487
+ const hover = originalColors["list.hoverBackground"];
1488
+ if (hover != null && (matchesSurface(hover, sidebarBackground) || hoverWouldEraseText(hover, sidebarBackground, sidebarForeground))) delete colors["list.hoverBackground"];
1489
+ const result = Object.freeze({
1490
+ ...theme,
1491
+ colors: Object.freeze(colors)
1492
+ });
1493
+ cache.set(theme, result);
1494
+ return result;
1495
+ }
1496
+ function fill(colors, key, value) {
1497
+ if (value != null && value !== "") colors[key] = value;
1498
+ }
1499
+ function firstColor(...candidates) {
1500
+ for (const candidate of candidates) if (candidate != null && candidate !== "") return candidate;
1501
+ }
1502
+ function matchesSurface(color, surface) {
1503
+ return surface != null && color.toLowerCase() === surface.toLowerCase();
1504
+ }
1505
+ function getHighlighterThemeStyles({ theme = DEFAULT_THEMES, highlighter: highlighter2, prefix }) {
1506
+ let styles = "";
1507
+ if (typeof theme === "string") {
1508
+ const themeData = highlighter2.getTheme(theme);
1509
+ const normalized = normalizeThemeColors(themeData);
1510
+ styles += `color:${normalized.fg};`;
1511
+ styles += `background-color:${normalized.bg};`;
1512
+ styles += `${formatCSSVariablePrefix("global")}fg:${normalized.fg};`;
1513
+ styles += `${formatCSSVariablePrefix("global")}bg:${normalized.bg};`;
1514
+ styles += getGitVariables(themeData, prefix);
1515
+ } else {
1516
+ let themeData = highlighter2.getTheme(theme.dark);
1517
+ let normalized = normalizeThemeColors(themeData);
1518
+ styles += `${formatCSSVariablePrefix("global")}dark:${normalized.fg};`;
1519
+ styles += `${formatCSSVariablePrefix("global")}dark-bg:${normalized.bg};`;
1520
+ styles += getGitVariables(themeData, "dark");
1521
+ themeData = highlighter2.getTheme(theme.light);
1522
+ normalized = normalizeThemeColors(themeData);
1523
+ styles += `${formatCSSVariablePrefix("global")}light:${normalized.fg};`;
1524
+ styles += `${formatCSSVariablePrefix("global")}light-bg:${normalized.bg};`;
1525
+ styles += getGitVariables(themeData, "light");
1526
+ }
1527
+ return styles;
1528
+ }
1529
+ function getGitVariables(themeData, modePrefix) {
1530
+ modePrefix = modePrefix != null ? `${modePrefix}-` : "";
1531
+ let styles = "";
1532
+ const additionGreen = themeData.colors?.["gitDecoration.addedResourceForeground"] ?? themeData.colors?.["terminal.ansiGreen"];
1533
+ if (additionGreen != null) styles += `${formatCSSVariablePrefix("global")}${modePrefix}addition-color:${additionGreen};`;
1534
+ const deletionRed = themeData.colors?.["gitDecoration.deletedResourceForeground"] ?? themeData.colors?.["terminal.ansiRed"];
1535
+ if (deletionRed != null) styles += `${formatCSSVariablePrefix("global")}${modePrefix}deletion-color:${deletionRed};`;
1536
+ const modifiedBlue = themeData.colors?.["gitDecoration.modifiedResourceForeground"] ?? themeData.colors?.["terminal.ansiBlue"];
1537
+ if (modifiedBlue != null) styles += `${formatCSSVariablePrefix("global")}${modePrefix}modified-color:${modifiedBlue};`;
1538
+ return styles;
1539
+ }
1540
+ function getLineNodes(nodes) {
1541
+ let firstChild = nodes.children[0];
1542
+ while (firstChild != null) {
1543
+ if (firstChild.type === "element" && firstChild.tagName === "code") return firstChild.children;
1544
+ if ("children" in firstChild) firstChild = firstChild.children[0];
1545
+ else firstChild = null;
1546
+ }
1547
+ console.error(nodes);
1548
+ throw new Error("getLineNodes: Unable to find children");
1549
+ }
1550
+ const LINE_FEED = 10;
1551
+ const CARRIAGE_RETURN = 13;
1552
+ const DENSE_LINE_BREAK_BLOCK_SIZE = 4;
1553
+ const DENSE_LINE_BREAK_BLOCK_SPAN = 40;
1554
+ function computeLineOffsets(contents) {
1555
+ const offsets = [0];
1556
+ let carriageReturn = contents.indexOf("\r");
1557
+ let lineFeed = contents.indexOf("\n");
1558
+ let blockStart = 0;
1559
+ let blockBreaks = 0;
1560
+ while (carriageReturn !== -1 || lineFeed !== -1) {
1561
+ let nextOffset;
1562
+ if (carriageReturn !== -1 && (lineFeed === -1 || carriageReturn < lineFeed)) {
1563
+ if (lineFeed === carriageReturn + 1) {
1564
+ nextOffset = lineFeed + 1;
1565
+ carriageReturn = contents.indexOf("\r", nextOffset);
1566
+ lineFeed = contents.indexOf("\n", nextOffset);
1567
+ } else {
1568
+ nextOffset = carriageReturn + 1;
1569
+ carriageReturn = contents.indexOf("\r", nextOffset);
1570
+ }
1571
+ } else {
1572
+ nextOffset = lineFeed + 1;
1573
+ lineFeed = contents.indexOf("\n", nextOffset);
1574
+ }
1575
+ offsets.push(nextOffset);
1576
+ if (++blockBreaks === DENSE_LINE_BREAK_BLOCK_SIZE) {
1577
+ if (nextOffset - blockStart <= DENSE_LINE_BREAK_BLOCK_SPAN) {
1578
+ for (let i = nextOffset; i < contents.length; i++) {
1579
+ const char = contents.charCodeAt(i);
1580
+ if (char === LINE_FEED || char === CARRIAGE_RETURN) {
1581
+ if (char === CARRIAGE_RETURN && i + 1 < contents.length && contents.charCodeAt(i + 1) === LINE_FEED) i++;
1582
+ offsets.push(i + 1);
1583
+ }
1584
+ }
1585
+ return offsets;
1586
+ }
1587
+ blockStart = nextOffset;
1588
+ blockBreaks = 0;
1589
+ }
1590
+ }
1591
+ return offsets;
1592
+ }
1593
+ function countLineBreaks(contents) {
1594
+ let count = 0;
1595
+ for (let i = 0; i < contents.length; i++) {
1596
+ const char = contents.charCodeAt(i);
1597
+ if (char === LINE_FEED || char === CARRIAGE_RETURN) {
1598
+ if (char === CARRIAGE_RETURN && i + 1 < contents.length && contents.charCodeAt(i + 1) === LINE_FEED) i++;
1599
+ count++;
1600
+ }
1601
+ }
1602
+ return count;
1603
+ }
1604
+ function linesFromFileContents(contents) {
1605
+ const offsets = computeLineOffsets(contents);
1606
+ return Array.from({ length: offsets.length }, (_, i) => {
1607
+ const start = offsets[i];
1608
+ const end = offsets[i + 1] ?? contents.length;
1609
+ return contents.slice(start, end);
1610
+ });
1611
+ }
1612
+ function appendItems(target, items) {
1613
+ for (const item of items) target.push(item);
1614
+ }
1615
+ const DEFAULT_PLAIN_TEXT_OPTIONS$1 = { forcePlainText: false };
1616
+ function renderFileWithHighlighter(file, highlighter2, { theme, tokenizeMaxLineLength, useTokenTransformer }, { forcePlainText, startingLine, totalLines, lines } = DEFAULT_PLAIN_TEXT_OPTIONS$1) {
1617
+ if (forcePlainText) {
1618
+ startingLine ??= 0;
1619
+ totalLines ??= Infinity;
1620
+ } else {
1621
+ startingLine = 0;
1622
+ totalLines = Infinity;
1623
+ }
1624
+ const isWindowedHighlight = startingLine > 0 || totalLines < Infinity;
1625
+ const { state, transformers } = createTransformerWithState(useTokenTransformer);
1626
+ const lang = forcePlainText ? "text" : file.lang ?? getFiletypeFromFileName(file.name);
1627
+ const baseThemeType = typeof theme === "string" ? highlighter2.getTheme(theme).type : void 0;
1628
+ const themeStyles = getHighlighterThemeStyles({
1629
+ theme,
1630
+ highlighter: highlighter2
1631
+ });
1632
+ state.lineInfo = (shikiLineNumber) => ({
1633
+ type: "context",
1634
+ lineIndex: shikiLineNumber - 1 + startingLine,
1635
+ lineNumber: shikiLineNumber + startingLine
1636
+ });
1637
+ const hastConfig = (() => {
1638
+ if (typeof theme === "string") return {
1639
+ lang,
1640
+ theme,
1641
+ transformers,
1642
+ defaultColor: false,
1643
+ cssVariablePrefix: formatCSSVariablePrefix("token"),
1644
+ tokenizeMaxLineLength,
1645
+ tokenizeTimeLimit: 0
1646
+ };
1647
+ return {
1648
+ lang,
1649
+ themes: theme,
1650
+ transformers,
1651
+ defaultColor: false,
1652
+ cssVariablePrefix: formatCSSVariablePrefix("token"),
1653
+ tokenizeMaxLineLength,
1654
+ tokenizeTimeLimit: 0
1655
+ };
1656
+ })();
1657
+ const highlightedLines = getLineNodes(highlighter2.codeToHast(normalizeHighlightLineEndings(isWindowedHighlight ? extractWindowedFileContent(lines ?? linesFromFileContents(file.contents), startingLine, totalLines) : file.contents), hastConfig));
1658
+ const code = isWindowedHighlight ? new Array(startingLine) : highlightedLines;
1659
+ if (isWindowedHighlight) appendItems(code, highlightedLines);
1660
+ return {
1661
+ code,
1662
+ themeStyles,
1663
+ baseThemeType
1664
+ };
1665
+ }
1666
+ function normalizeHighlightLineEndings(contents) {
1667
+ return contents.replace(/\r(?!\n)/g, "\n");
1668
+ }
1669
+ function extractWindowedFileContent(lines, startingLine, totalLines) {
1670
+ if (lines.length === 0) return "";
1671
+ const endLine = Math.min(startingLine + totalLines, lines.length);
1672
+ return lines.slice(startingLine, endLine).join("");
1673
+ }
1674
+ function isFilePlainText(file) {
1675
+ return (file.lang ?? getFiletypeFromFileName(file.name)) === "text";
1676
+ }
1677
+ var WorkerPoolTerminatedError = class extends Error {
1678
+ constructor() {
1679
+ super("WorkerPoolManager: operation canceled because the pool terminated");
1680
+ this.name = "WorkerPoolTerminatedError";
1681
+ }
1682
+ };
1683
+ var WorkerPoolTaskCanceledError = class extends Error {
1684
+ constructor() {
1685
+ super("WorkerPoolManager: operation canceled before the task completed");
1686
+ this.name = "WorkerPoolTaskCanceledError";
1687
+ }
1688
+ };
1689
+ var WorkerPoolWorkerError = class extends Error {
1690
+ constructor(message, options) {
1691
+ super(message, options);
1692
+ this.name = "WorkerPoolWorkerError";
1693
+ }
1694
+ };
1695
+ const reportedWorkerErrors = /* @__PURE__ */ new WeakSet();
1696
+ function markWorkerErrorReported(error) {
1697
+ reportedWorkerErrors.add(error);
1698
+ }
1699
+ function isWorkerPoolCancellation(error) {
1700
+ return error instanceof WorkerPoolTerminatedError || error instanceof WorkerPoolTaskCanceledError;
1701
+ }
1702
+ function isHandledWorkerPoolError(error) {
1703
+ return isWorkerPoolCancellation(error) || error instanceof WorkerPoolWorkerError && reportedWorkerErrors.has(error);
1704
+ }
1705
+ function computeVirtualFileMetrics(metrics) {
1706
+ return {
1707
+ ...DEFAULT_VIRTUAL_FILE_METRICS,
1708
+ ...metrics
1709
+ };
1710
+ }
1711
+ function getVirtualFileHeaderRegion(metrics, disableFileHeader) {
1712
+ return getVirtualFileHeaderHeight(metrics, disableFileHeader) + getVirtualFilePaddingTop(metrics, disableFileHeader);
1713
+ }
1714
+ function getVirtualFileHeaderHeight(metrics, disableFileHeader) {
1715
+ return disableFileHeader ? 0 : metrics.diffHeaderHeight;
1716
+ }
1717
+ function getVirtualFilePaddingTop(metrics, disableFileHeader) {
1718
+ return metrics.paddingTop ?? (disableFileHeader ? metrics.spacing : 0);
1719
+ }
1720
+ function getVirtualFilePaddingBottom(metrics) {
1721
+ return metrics.paddingBottom ?? metrics.spacing;
1722
+ }
1723
+ function getDefaultHunkSeparatorHeight(type) {
1724
+ switch (type) {
1725
+ case "simple":
1726
+ return 4;
1727
+ case "metadata":
1728
+ case "line-info":
1729
+ case "line-info-basic":
1730
+ case "custom":
1731
+ return 32;
1732
+ }
1733
+ }
1734
+ function areDiffTargetsEqual(diffA, diffB) {
1735
+ return diffA?.cacheKey != null || diffB?.cacheKey != null ? diffA?.cacheKey === diffB?.cacheKey : diffA === diffB;
1736
+ }
1737
+ function areFilesEqual(fileA, fileB) {
1738
+ return fileA?.cacheKey === fileB?.cacheKey && fileA?.contents === fileB?.contents && fileA?.name === fileB?.name && fileA?.lang === fileB?.lang;
1739
+ }
1740
+ function getHunkSideStartBoundary(start, count) {
1741
+ return start - (count === 0 ? 0 : 1);
1742
+ }
1743
+ function getHunkSideEndBoundary(start, count) {
1744
+ return getHunkSideStartBoundary(start, count) + count;
1745
+ }
1746
+ function cleanLastNewline(contents) {
1747
+ let end = contents.length;
1748
+ if (contents.charCodeAt(end - 1) === 10) {
1749
+ end--;
1750
+ if (contents.charCodeAt(end - 1) === 13) end--;
1751
+ }
1752
+ return contents.slice(0, end);
1753
+ }
1754
+ class Diff {
1755
+ diff(oldStr, newStr, options = {}) {
1756
+ let callback;
1757
+ if (typeof options === "function") {
1758
+ callback = options;
1759
+ options = {};
1760
+ } else if ("callback" in options) {
1761
+ callback = options.callback;
1762
+ }
1763
+ const oldString = this.castInput(oldStr, options);
1764
+ const newString = this.castInput(newStr, options);
1765
+ const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
1766
+ const newTokens = this.removeEmpty(this.tokenize(newString, options));
1767
+ return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
1768
+ }
1769
+ diffWithOptionsObj(oldTokens, newTokens, options, callback) {
1770
+ var _a;
1771
+ const done = (value) => {
1772
+ value = this.postProcess(value, options);
1773
+ if (callback) {
1774
+ setTimeout(function() {
1775
+ callback(value);
1776
+ }, 0);
1777
+ return void 0;
1778
+ } else {
1779
+ return value;
1780
+ }
1781
+ };
1782
+ const newLen = newTokens.length, oldLen = oldTokens.length;
1783
+ let editLength = 1;
1784
+ let maxEditLength = newLen + oldLen;
1785
+ if (options.maxEditLength != null) {
1786
+ maxEditLength = Math.min(maxEditLength, options.maxEditLength);
1787
+ }
1788
+ const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity;
1789
+ const abortAfterTimestamp = Date.now() + maxExecutionTime;
1790
+ const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
1791
+ let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
1792
+ if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
1793
+ return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
1794
+ }
1795
+ let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
1796
+ const execEditLength = () => {
1797
+ for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
1798
+ let basePath;
1799
+ const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
1800
+ if (removePath) {
1801
+ bestPath[diagonalPath - 1] = void 0;
1802
+ }
1803
+ let canAdd = false;
1804
+ if (addPath) {
1805
+ const addPathNewPos = addPath.oldPos - diagonalPath;
1806
+ canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
1807
+ }
1808
+ const canRemove = removePath && removePath.oldPos + 1 < oldLen;
1809
+ if (!canAdd && !canRemove) {
1810
+ bestPath[diagonalPath] = void 0;
1811
+ continue;
1812
+ }
1813
+ if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
1814
+ basePath = this.addToPath(addPath, true, false, 0, options);
1815
+ } else {
1816
+ basePath = this.addToPath(removePath, false, true, 1, options);
1817
+ }
1818
+ newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
1819
+ if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
1820
+ return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
1821
+ } else {
1822
+ bestPath[diagonalPath] = basePath;
1823
+ if (basePath.oldPos + 1 >= oldLen) {
1824
+ maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
1825
+ }
1826
+ if (newPos + 1 >= newLen) {
1827
+ minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
1828
+ }
1829
+ }
1830
+ }
1831
+ editLength++;
1832
+ };
1833
+ if (callback) {
1834
+ (function exec() {
1835
+ setTimeout(function() {
1836
+ if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
1837
+ return callback(void 0);
1838
+ }
1839
+ if (!execEditLength()) {
1840
+ exec();
1841
+ }
1842
+ }, 0);
1843
+ })();
1844
+ } else {
1845
+ while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
1846
+ const ret = execEditLength();
1847
+ if (ret) {
1848
+ return ret;
1849
+ }
1850
+ }
1851
+ }
1852
+ }
1853
+ addToPath(path, added, removed, oldPosInc, options) {
1854
+ const last = path.lastComponent;
1855
+ if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
1856
+ return {
1857
+ oldPos: path.oldPos + oldPosInc,
1858
+ lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
1859
+ };
1860
+ } else {
1861
+ return {
1862
+ oldPos: path.oldPos + oldPosInc,
1863
+ lastComponent: { count: 1, added, removed, previousComponent: last }
1864
+ };
1865
+ }
1866
+ }
1867
+ extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
1868
+ const newLen = newTokens.length, oldLen = oldTokens.length;
1869
+ let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
1870
+ while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
1871
+ newPos++;
1872
+ oldPos++;
1873
+ commonCount++;
1874
+ if (options.oneChangePerToken) {
1875
+ basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
1876
+ }
1877
+ }
1878
+ if (commonCount && !options.oneChangePerToken) {
1879
+ basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
1880
+ }
1881
+ basePath.oldPos = oldPos;
1882
+ return newPos;
1883
+ }
1884
+ equals(left, right, options) {
1885
+ if (options.comparator) {
1886
+ return options.comparator(left, right);
1887
+ } else {
1888
+ return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
1889
+ }
1890
+ }
1891
+ removeEmpty(array) {
1892
+ const ret = [];
1893
+ for (let i = 0; i < array.length; i++) {
1894
+ if (array[i]) {
1895
+ ret.push(array[i]);
1896
+ }
1897
+ }
1898
+ return ret;
1899
+ }
1900
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1901
+ castInput(value, options) {
1902
+ return value;
1903
+ }
1904
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1905
+ tokenize(value, options) {
1906
+ return Array.from(value);
1907
+ }
1908
+ join(chars) {
1909
+ return chars.join("");
1910
+ }
1911
+ postProcess(changeObjects, options) {
1912
+ return changeObjects;
1913
+ }
1914
+ get useLongestToken() {
1915
+ return false;
1916
+ }
1917
+ buildValues(lastComponent, newTokens, oldTokens) {
1918
+ const components = [];
1919
+ let nextComponent;
1920
+ while (lastComponent) {
1921
+ components.push(lastComponent);
1922
+ nextComponent = lastComponent.previousComponent;
1923
+ delete lastComponent.previousComponent;
1924
+ lastComponent = nextComponent;
1925
+ }
1926
+ components.reverse();
1927
+ const componentLen = components.length;
1928
+ let componentPos = 0, newPos = 0, oldPos = 0;
1929
+ for (; componentPos < componentLen; componentPos++) {
1930
+ const component = components[componentPos];
1931
+ if (!component.removed) {
1932
+ if (!component.added && this.useLongestToken) {
1933
+ let value = newTokens.slice(newPos, newPos + component.count);
1934
+ value = value.map(function(value2, i) {
1935
+ const oldValue = oldTokens[oldPos + i];
1936
+ return oldValue.length > value2.length ? oldValue : value2;
1937
+ });
1938
+ component.value = this.join(value);
1939
+ } else {
1940
+ component.value = this.join(newTokens.slice(newPos, newPos + component.count));
1941
+ }
1942
+ newPos += component.count;
1943
+ if (!component.added) {
1944
+ oldPos += component.count;
1945
+ }
1946
+ } else {
1947
+ component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
1948
+ oldPos += component.count;
1949
+ }
1950
+ }
1951
+ return components;
1952
+ }
1953
+ }
1954
+ class CharacterDiff extends Diff {
1955
+ }
1956
+ const characterDiff = new CharacterDiff();
1957
+ function diffChars(oldStr, newStr, options) {
1958
+ return characterDiff.diff(oldStr, newStr, options);
1959
+ }
1960
+ const extendedWordChars = "a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}";
1961
+ class WordsWithSpaceDiff extends Diff {
1962
+ tokenize(value) {
1963
+ const regex = new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`, "ug");
1964
+ return value.match(regex) || [];
1965
+ }
1966
+ }
1967
+ const wordsWithSpaceDiff = new WordsWithSpaceDiff();
1968
+ function diffWordsWithSpace(oldStr, newStr, options) {
1969
+ return wordsWithSpaceDiff.diff(oldStr, newStr, options);
1970
+ }
1971
+ function areDiffRenderOptionsEqual(optionsA, optionsB) {
1972
+ return areThemesEqual(optionsA.theme, optionsB.theme) && optionsA.useTokenTransformer === optionsB.useTokenTransformer && optionsA.tokenizeMaxLineLength === optionsB.tokenizeMaxLineLength && optionsA.lineDiffType === optionsB.lineDiffType && optionsA.maxLineDiffLength === optionsB.maxLineDiffLength;
1973
+ }
1974
+ function createDiffSpanDecoration({ line, spanStart, spanLength }) {
1975
+ return {
1976
+ start: {
1977
+ line,
1978
+ character: spanStart
1979
+ },
1980
+ end: {
1981
+ line,
1982
+ character: spanStart + spanLength
1983
+ },
1984
+ properties: { "data-diff-span": "" },
1985
+ alwaysWrap: true
1986
+ };
1987
+ }
1988
+ function pushOrJoinSpan({ item, arr, enableJoin, isNeutral = false, isLastItem = false }) {
1989
+ const lastItem = arr[arr.length - 1];
1990
+ if (lastItem == null || isLastItem || !enableJoin) {
1991
+ arr.push([isNeutral ? 0 : 1, item.value]);
1992
+ return;
1993
+ }
1994
+ const isLastItemNeutral = lastItem[0] === 0;
1995
+ if (isNeutral === isLastItemNeutral || isNeutral && item.value.length === 1 && !isLastItemNeutral) {
1996
+ lastItem[1] += item.value;
1997
+ return;
1998
+ }
1999
+ arr.push([isNeutral ? 0 : 1, item.value]);
2000
+ }
2001
+ function getHunkAdditionLineRange(hunk) {
2002
+ return [getHunkSideStartBoundary(hunk.additionStart, hunk.additionCount) + 1, getHunkSideEndBoundary(hunk.additionStart, hunk.additionCount) + 1];
2003
+ }
2004
+ function getExpandedRegion({ isPartial, rangeSize, expandedHunks, hunkIndex, collapsedContextThreshold }) {
2005
+ const normalizedRangeSize = Math.max(rangeSize, 0);
2006
+ if (normalizedRangeSize === 0 || isPartial) return {
2007
+ fromStart: 0,
2008
+ fromEnd: 0,
2009
+ rangeSize: normalizedRangeSize,
2010
+ collapsedLines: normalizedRangeSize,
2011
+ renderAll: false
2012
+ };
2013
+ if (expandedHunks === true || normalizedRangeSize <= collapsedContextThreshold) return {
2014
+ fromStart: normalizedRangeSize,
2015
+ fromEnd: 0,
2016
+ rangeSize: normalizedRangeSize,
2017
+ collapsedLines: 0,
2018
+ renderAll: true
2019
+ };
2020
+ const region = expandedHunks?.get(hunkIndex);
2021
+ const fromStart = Math.min(Math.max(region?.fromStart ?? 0, 0), normalizedRangeSize);
2022
+ const fromEnd = Math.min(Math.max(region?.fromEnd ?? 0, 0), normalizedRangeSize);
2023
+ const expandedCount = fromStart + fromEnd;
2024
+ const renderAll = expandedCount >= normalizedRangeSize;
2025
+ return {
2026
+ fromStart: renderAll ? normalizedRangeSize : fromStart,
2027
+ fromEnd: renderAll ? 0 : fromEnd,
2028
+ rangeSize: normalizedRangeSize,
2029
+ collapsedLines: Math.max(normalizedRangeSize - expandedCount, 0),
2030
+ renderAll
2031
+ };
2032
+ }
2033
+ function hasTrailingContextMismatch(fileDiff) {
2034
+ const lastHunk = fileDiff.hunks[fileDiff.hunks.length - 1];
2035
+ if (lastHunk == null || fileDiff.isPartial || fileDiff.additionLines.length === 0 || fileDiff.deletionLines.length === 0) return false;
2036
+ const additionRemaining = fileDiff.additionLines.length - getHunkSideEndBoundary(lastHunk.additionStart, lastHunk.additionCount);
2037
+ const deletionRemaining = fileDiff.deletionLines.length - getHunkSideEndBoundary(lastHunk.deletionStart, lastHunk.deletionCount);
2038
+ if (additionRemaining <= 0 && deletionRemaining <= 0) return false;
2039
+ return additionRemaining !== deletionRemaining;
2040
+ }
2041
+ function getTrailingContextRangeSize({ fileDiff, errorPrefix }) {
2042
+ const lastHunk = fileDiff.hunks[fileDiff.hunks.length - 1];
2043
+ if (lastHunk == null || fileDiff.isPartial || fileDiff.additionLines.length === 0 || fileDiff.deletionLines.length === 0) return 0;
2044
+ const additionRemaining = fileDiff.additionLines.length - getHunkSideEndBoundary(lastHunk.additionStart, lastHunk.additionCount);
2045
+ const deletionRemaining = fileDiff.deletionLines.length - getHunkSideEndBoundary(lastHunk.deletionStart, lastHunk.deletionCount);
2046
+ if (additionRemaining <= 0 && deletionRemaining <= 0) return 0;
2047
+ if (additionRemaining !== deletionRemaining) throw new Error(`${errorPrefix}: trailing context mismatch (additions=${additionRemaining}, deletions=${deletionRemaining}) for ${fileDiff.name}`);
2048
+ return Math.min(additionRemaining, deletionRemaining);
2049
+ }
2050
+ function getTrailingExpandedRegion({ fileDiff, hunkIndex, expandedHunks, collapsedContextThreshold, errorPrefix }) {
2051
+ if (hunkIndex !== fileDiff.hunks.length - 1) return;
2052
+ const trailingRangeSize = getTrailingContextRangeSize({
2053
+ fileDiff,
2054
+ errorPrefix
2055
+ });
2056
+ if (trailingRangeSize <= 0) return;
2057
+ if (expandedHunks === true || trailingRangeSize <= collapsedContextThreshold) return {
2058
+ fromStart: trailingRangeSize,
2059
+ fromEnd: 0,
2060
+ rangeSize: trailingRangeSize,
2061
+ collapsedLines: 0,
2062
+ renderAll: true
2063
+ };
2064
+ const region = expandedHunks?.get(fileDiff.hunks.length);
2065
+ const fromStart = Math.min(Math.max(region?.fromStart ?? 0, 0), trailingRangeSize);
2066
+ return {
2067
+ fromStart,
2068
+ fromEnd: 0,
2069
+ rangeSize: trailingRangeSize,
2070
+ collapsedLines: trailingRangeSize - fromStart,
2071
+ renderAll: fromStart >= trailingRangeSize
2072
+ };
2073
+ }
2074
+ function isAdditionLineRenderable({ fileDiff, lineNumber, expandedHunks, collapsedContextThreshold }) {
2075
+ if (expandedHunks === true || fileDiff.isPartial) return true;
2076
+ for (const [hunkIndex, hunk] of fileDiff.hunks.entries()) {
2077
+ const [hunkStart, hunkEnd] = getHunkAdditionLineRange(hunk);
2078
+ if (lineNumber < hunkStart) {
2079
+ const region = getExpandedRegion({
2080
+ isPartial: fileDiff.isPartial,
2081
+ rangeSize: hunk.collapsedBefore,
2082
+ expandedHunks,
2083
+ hunkIndex,
2084
+ collapsedContextThreshold
2085
+ });
2086
+ const gapStart = hunkStart - region.rangeSize;
2087
+ return region.renderAll || lineNumber < gapStart + region.fromStart || lineNumber >= hunkStart - region.fromEnd;
2088
+ }
2089
+ if (lineNumber < hunkEnd) return true;
2090
+ }
2091
+ const trailingRegion = getTrailingExpandedRegion({
2092
+ fileDiff,
2093
+ hunkIndex: fileDiff.hunks.length - 1,
2094
+ expandedHunks,
2095
+ collapsedContextThreshold,
2096
+ errorPrefix: "isAdditionLineRenderable"
2097
+ });
2098
+ if (trailingRegion == null || trailingRegion.renderAll) return true;
2099
+ const lastHunk = fileDiff.hunks[fileDiff.hunks.length - 1];
2100
+ const [, trailingStart] = getHunkAdditionLineRange(lastHunk);
2101
+ return lineNumber < trailingStart + trailingRegion.fromStart || lineNumber >= trailingStart + trailingRegion.rangeSize;
2102
+ }
2103
+ function getNearestRenderableAdditionLine({ fileDiff, lineNumber, direction, expandedHunks, collapsedContextThreshold }) {
2104
+ if (expandedHunks === true || fileDiff.isPartial) return lineNumber;
2105
+ const ranges = [];
2106
+ let modeledEnd = 1;
2107
+ for (const [hunkIndex, hunk] of fileDiff.hunks.entries()) {
2108
+ const [hunkStart, hunkEnd] = getHunkAdditionLineRange(hunk);
2109
+ const region = getExpandedRegion({
2110
+ isPartial: fileDiff.isPartial,
2111
+ rangeSize: hunk.collapsedBefore,
2112
+ expandedHunks,
2113
+ hunkIndex,
2114
+ collapsedContextThreshold
2115
+ });
2116
+ const gapStart = hunkStart - region.rangeSize;
2117
+ if (region.renderAll) ranges.push([gapStart, hunkStart]);
2118
+ else {
2119
+ if (region.fromStart > 0) ranges.push([gapStart, gapStart + region.fromStart]);
2120
+ if (region.fromEnd > 0) ranges.push([hunkStart - region.fromEnd, hunkStart]);
2121
+ }
2122
+ ranges.push([hunkStart, hunkEnd]);
2123
+ modeledEnd = hunkEnd;
2124
+ }
2125
+ const trailingRegion = getTrailingExpandedRegion({
2126
+ fileDiff,
2127
+ hunkIndex: fileDiff.hunks.length - 1,
2128
+ expandedHunks,
2129
+ collapsedContextThreshold,
2130
+ errorPrefix: "getNearestRenderableAdditionLine"
2131
+ });
2132
+ if (trailingRegion != null) {
2133
+ const trailingStart = modeledEnd;
2134
+ modeledEnd = trailingStart + trailingRegion.rangeSize;
2135
+ if (trailingRegion.renderAll) ranges.push([trailingStart, modeledEnd]);
2136
+ else if (trailingRegion.fromStart > 0) ranges.push([trailingStart, trailingStart + trailingRegion.fromStart]);
2137
+ }
2138
+ if (lineNumber >= modeledEnd) return lineNumber;
2139
+ if (direction === "down") {
2140
+ for (const [start, end] of ranges) if (end > lineNumber) return Math.max(start, lineNumber);
2141
+ return;
2142
+ }
2143
+ for (let index = ranges.length - 1; index >= 0; index--) {
2144
+ const [start, end] = ranges[index];
2145
+ if (start <= lineNumber) return Math.min(end - 1, lineNumber);
2146
+ }
2147
+ }
2148
+ function getHunkSeparatorHeight({ type, metrics }) {
2149
+ return metrics.hunkSeparatorHeight ?? getDefaultHunkSeparatorHeight(type);
2150
+ }
2151
+ function getHunkSeparatorGap({ type, metrics }) {
2152
+ return type === "simple" || type === "metadata" || type === "line-info-basic" ? 0 : metrics.spacing;
2153
+ }
2154
+ function hasLeadingHunkSeparator({ type, hunkIndex, hunkSpecs }) {
2155
+ switch (type) {
2156
+ case "simple":
2157
+ return hunkIndex > 0;
2158
+ case "metadata":
2159
+ return hunkSpecs != null;
2160
+ case "line-info":
2161
+ case "line-info-basic":
2162
+ case "custom":
2163
+ return true;
2164
+ }
2165
+ }
2166
+ function hasTrailingHunkSeparator(type) {
2167
+ return type !== "simple" && type !== "metadata";
2168
+ }
2169
+ function getLeadingHunkSeparatorLayout({ type, metrics, hunkIndex, hunkSpecs }) {
2170
+ if (!hasLeadingHunkSeparator({
2171
+ type,
2172
+ hunkIndex,
2173
+ hunkSpecs
2174
+ })) return;
2175
+ const height = getHunkSeparatorHeight({
2176
+ type,
2177
+ metrics
2178
+ });
2179
+ const gap = getHunkSeparatorGap({
2180
+ type,
2181
+ metrics
2182
+ });
2183
+ const gapBefore = hunkIndex > 0 ? gap : 0;
2184
+ const gapAfter = gap;
2185
+ return {
2186
+ height,
2187
+ gapBefore,
2188
+ gapAfter,
2189
+ totalHeight: gapBefore + height + gapAfter
2190
+ };
2191
+ }
2192
+ function getTrailingHunkSeparatorLayout({ type, metrics }) {
2193
+ if (!hasTrailingHunkSeparator(type)) return;
2194
+ const height = getHunkSeparatorHeight({
2195
+ type,
2196
+ metrics
2197
+ });
2198
+ const gapBefore = getHunkSeparatorGap({
2199
+ type,
2200
+ metrics
2201
+ });
2202
+ return {
2203
+ height,
2204
+ gapBefore,
2205
+ gapAfter: 0,
2206
+ totalHeight: gapBefore + height
2207
+ };
2208
+ }
2209
+ function iterateOverDiff({ diff, diffStyle, startingLine = 0, totalLines = Infinity, expandedHunks, collapsedContextThreshold = 1, callback }) {
2210
+ const iterationStart = getIterationStartState({
2211
+ diff,
2212
+ diffStyle,
2213
+ startingLine,
2214
+ expandedHunks,
2215
+ collapsedContextThreshold
2216
+ });
2217
+ const state = {
2218
+ viewportStart: startingLine,
2219
+ viewportEnd: startingLine + totalLines,
2220
+ isWindowedHighlight: startingLine > 0 || totalLines < Infinity,
2221
+ splitCount: iterationStart.splitCount,
2222
+ unifiedCount: iterationStart.unifiedCount,
2223
+ finalHunkIndex: diff.hunks.length - 1,
2224
+ shouldBreak() {
2225
+ if (!state.isWindowedHighlight) return false;
2226
+ const breakUnified = state.unifiedCount >= startingLine + totalLines;
2227
+ const breakSplit = state.splitCount >= startingLine + totalLines;
2228
+ if (diffStyle === "unified") return breakUnified;
2229
+ else if (diffStyle === "split") return breakSplit;
2230
+ else return breakUnified && breakSplit;
2231
+ },
2232
+ shouldSkip(unifiedCount, splitCount) {
2233
+ if (!state.isWindowedHighlight) return false;
2234
+ const skipUnified = unifiedCount > 0 && state.unifiedCount + unifiedCount <= startingLine;
2235
+ const skipSplit = splitCount > 0 && state.splitCount + splitCount <= startingLine;
2236
+ if (diffStyle === "unified") return skipUnified;
2237
+ else if (diffStyle === "split") return skipSplit;
2238
+ else return skipUnified && skipSplit;
2239
+ },
2240
+ incrementCounts(unifiedValue, splitValue) {
2241
+ if (diffStyle === "unified" || diffStyle === "both") state.unifiedCount += unifiedValue;
2242
+ if (diffStyle === "split" || diffStyle === "both") state.splitCount += splitValue;
2243
+ },
2244
+ isInWindow(unifiedHeight, splitHeight) {
2245
+ if (!state.isWindowedHighlight) return true;
2246
+ const unifiedInWindow = state.isInUnifiedWindow(unifiedHeight);
2247
+ const splitInWindow = state.isInSplitWindow(splitHeight);
2248
+ if (diffStyle === "unified") return unifiedInWindow;
2249
+ else if (diffStyle === "split") return splitInWindow;
2250
+ else return unifiedInWindow || splitInWindow;
2251
+ },
2252
+ isInUnifiedWindow(unifiedHeight) {
2253
+ return !state.isWindowedHighlight || state.unifiedCount >= startingLine - unifiedHeight && state.unifiedCount < startingLine + totalLines;
2254
+ },
2255
+ isInSplitWindow(splitHeight) {
2256
+ return !state.isWindowedHighlight || state.splitCount >= startingLine - splitHeight && state.splitCount < startingLine + totalLines;
2257
+ },
2258
+ emit(props, silent = false) {
2259
+ if (!silent) {
2260
+ if (diffStyle === "unified") state.incrementCounts(1, 0);
2261
+ else if (diffStyle === "split") state.incrementCounts(0, 1);
2262
+ else state.incrementCounts(1, 1);
2263
+ }
2264
+ return callback(props) ?? false;
2265
+ }
2266
+ };
2267
+ hunkIterator: for (let hunkIndex = iterationStart.hunkIndex; hunkIndex < diff.hunks.length; hunkIndex++) {
2268
+ let getTrailingCollapsedAfter = function(unifiedLineIndex2, splitLineIndex2) {
2269
+ if (trailingRegion == null || trailingRegion.collapsedLines <= 0 || trailingRegion.fromStart + trailingRegion.fromEnd > 0) return 0;
2270
+ if (diffStyle === "unified") return unifiedLineIndex2 === hunk.unifiedLineStart + hunk.unifiedLineCount - 1 ? trailingRegion.collapsedLines : 0;
2271
+ return splitLineIndex2 === hunk.splitLineStart + hunk.splitLineCount - 1 ? trailingRegion.collapsedLines : 0;
2272
+ }, consumePendingCollapsed = function() {
2273
+ if (consumedCollapsed) return 0;
2274
+ consumedCollapsed = true;
2275
+ return leadingRegion.collapsedLines;
2276
+ };
2277
+ const hunk = diff.hunks[hunkIndex];
2278
+ if (hunk == null) throw new Error("iterateOverDiff: invalid hunk index");
2279
+ if (state.shouldBreak()) break;
2280
+ const deletionBoundary = getHunkSideStartBoundary(hunk.deletionStart, hunk.deletionCount);
2281
+ const additionBoundary = getHunkSideStartBoundary(hunk.additionStart, hunk.additionCount);
2282
+ const deletionStartIndex = !diff.isPartial && hunk.deletionCount === 0 ? deletionBoundary : hunk.deletionLineIndex;
2283
+ const additionStartIndex = !diff.isPartial && hunk.additionCount === 0 ? additionBoundary : hunk.additionLineIndex;
2284
+ const leadingRegion = getExpandedRegion({
2285
+ isPartial: diff.isPartial,
2286
+ rangeSize: hunk.collapsedBefore,
2287
+ expandedHunks,
2288
+ hunkIndex,
2289
+ collapsedContextThreshold
2290
+ });
2291
+ const trailingRegion = hunkIndex === state.finalHunkIndex ? getTrailingExpandedRegion({
2292
+ fileDiff: diff,
2293
+ hunkIndex,
2294
+ expandedHunks,
2295
+ collapsedContextThreshold,
2296
+ errorPrefix: "iterateOverDiff"
2297
+ }) : void 0;
2298
+ const expandedLineCount = leadingRegion.fromStart + leadingRegion.fromEnd;
2299
+ let consumedCollapsed = leadingRegion.collapsedLines === 0;
2300
+ if (!state.shouldSkip(expandedLineCount, expandedLineCount)) {
2301
+ let unifiedLineIndex2 = hunk.unifiedLineStart - leadingRegion.rangeSize;
2302
+ let splitLineIndex2 = hunk.splitLineStart - leadingRegion.rangeSize;
2303
+ let deletionLineIndex2 = deletionStartIndex - leadingRegion.rangeSize;
2304
+ let additionLineIndex2 = additionStartIndex - leadingRegion.rangeSize;
2305
+ let deletionLineNumber2 = deletionBoundary + 1 - leadingRegion.rangeSize;
2306
+ let additionLineNumber2 = additionBoundary + 1 - leadingRegion.rangeSize;
2307
+ if (walkContextLines(state, leadingRegion.fromStart, diffStyle, (index) => {
2308
+ return state.emit({
2309
+ hunkIndex,
2310
+ hunk,
2311
+ collapsedBefore: 0,
2312
+ collapsedAfter: 0,
2313
+ type: "context-expanded",
2314
+ deletionLine: {
2315
+ lineNumber: deletionLineNumber2 + index,
2316
+ lineIndex: deletionLineIndex2 + index,
2317
+ noEOFCR: false,
2318
+ unifiedLineIndex: unifiedLineIndex2 + index,
2319
+ splitLineIndex: splitLineIndex2 + index
2320
+ },
2321
+ additionLine: {
2322
+ unifiedLineIndex: unifiedLineIndex2 + index,
2323
+ splitLineIndex: splitLineIndex2 + index,
2324
+ lineIndex: additionLineIndex2 + index,
2325
+ lineNumber: additionLineNumber2 + index,
2326
+ noEOFCR: false
2327
+ }
2328
+ });
2329
+ })) break hunkIterator;
2330
+ unifiedLineIndex2 = hunk.unifiedLineStart - leadingRegion.fromEnd;
2331
+ splitLineIndex2 = hunk.splitLineStart - leadingRegion.fromEnd;
2332
+ deletionLineIndex2 = deletionStartIndex - leadingRegion.fromEnd;
2333
+ additionLineIndex2 = additionStartIndex - leadingRegion.fromEnd;
2334
+ deletionLineNumber2 = deletionBoundary + 1 - leadingRegion.fromEnd;
2335
+ additionLineNumber2 = additionBoundary + 1 - leadingRegion.fromEnd;
2336
+ if (walkContextLines(state, leadingRegion.fromEnd, diffStyle, (index) => {
2337
+ return state.emit({
2338
+ hunkIndex,
2339
+ hunk,
2340
+ collapsedBefore: consumePendingCollapsed(),
2341
+ collapsedAfter: 0,
2342
+ type: "context-expanded",
2343
+ deletionLine: {
2344
+ lineNumber: deletionLineNumber2 + index,
2345
+ lineIndex: deletionLineIndex2 + index,
2346
+ noEOFCR: false,
2347
+ unifiedLineIndex: unifiedLineIndex2 + index,
2348
+ splitLineIndex: splitLineIndex2 + index
2349
+ },
2350
+ additionLine: {
2351
+ unifiedLineIndex: unifiedLineIndex2 + index,
2352
+ splitLineIndex: splitLineIndex2 + index,
2353
+ lineIndex: additionLineIndex2 + index,
2354
+ lineNumber: additionLineNumber2 + index,
2355
+ noEOFCR: false
2356
+ }
2357
+ });
2358
+ }, () => {
2359
+ consumePendingCollapsed();
2360
+ })) break hunkIterator;
2361
+ } else {
2362
+ state.incrementCounts(expandedLineCount, expandedLineCount);
2363
+ consumePendingCollapsed();
2364
+ }
2365
+ let unifiedLineIndex = hunk.unifiedLineStart;
2366
+ let splitLineIndex = hunk.splitLineStart;
2367
+ let deletionLineIndex = deletionStartIndex;
2368
+ let additionLineIndex = additionStartIndex;
2369
+ let deletionLineNumber = deletionBoundary + 1;
2370
+ let additionLineNumber = additionBoundary + 1;
2371
+ const lastContent = hunk.hunkContent.at(-1);
2372
+ for (const content of hunk.hunkContent) {
2373
+ if (state.shouldBreak()) break hunkIterator;
2374
+ const isLastContent = content === lastContent;
2375
+ if (content.type === "context") {
2376
+ if (!state.shouldSkip(content.lines, content.lines)) {
2377
+ if (walkContextLines(state, content.lines, diffStyle, (index) => {
2378
+ const isLastLine = isLastContent && index === content.lines - 1;
2379
+ const unifiedRowIndex = unifiedLineIndex + index;
2380
+ const splitRowIndex = splitLineIndex + index;
2381
+ return state.emit({
2382
+ hunkIndex,
2383
+ hunk,
2384
+ collapsedBefore: consumePendingCollapsed(),
2385
+ collapsedAfter: getTrailingCollapsedAfter(unifiedRowIndex, splitRowIndex),
2386
+ type: "context",
2387
+ deletionLine: {
2388
+ lineNumber: deletionLineNumber + index,
2389
+ lineIndex: deletionLineIndex + index,
2390
+ noEOFCR: isLastLine && hunk.noEOFCRDeletions,
2391
+ unifiedLineIndex: unifiedRowIndex,
2392
+ splitLineIndex: splitRowIndex
2393
+ },
2394
+ additionLine: {
2395
+ unifiedLineIndex: unifiedRowIndex,
2396
+ splitLineIndex: splitRowIndex,
2397
+ lineIndex: additionLineIndex + index,
2398
+ lineNumber: additionLineNumber + index,
2399
+ noEOFCR: isLastLine && hunk.noEOFCRAdditions
2400
+ }
2401
+ });
2402
+ }, () => {
2403
+ consumePendingCollapsed();
2404
+ })) break hunkIterator;
2405
+ } else {
2406
+ state.incrementCounts(content.lines, content.lines);
2407
+ consumePendingCollapsed();
2408
+ }
2409
+ unifiedLineIndex += content.lines;
2410
+ splitLineIndex += content.lines;
2411
+ deletionLineIndex += content.lines;
2412
+ additionLineIndex += content.lines;
2413
+ deletionLineNumber += content.lines;
2414
+ additionLineNumber += content.lines;
2415
+ } else {
2416
+ const splitCount = Math.max(content.deletions, content.additions);
2417
+ const unifiedCount = content.deletions + content.additions;
2418
+ if (!state.shouldSkip(unifiedCount, splitCount)) {
2419
+ const iterationRanges = getChangeIterationRanges(state, content, diffStyle);
2420
+ if ((iterationRanges[0]?.[0] ?? 0) > 0) consumePendingCollapsed();
2421
+ for (const [rangeStart, rangeEnd] of iterationRanges) for (let index = rangeStart; index < rangeEnd; index++) {
2422
+ const collapsedAfter = getTrailingCollapsedAfter(unifiedLineIndex + index, diffStyle === "unified" ? splitLineIndex + (index < content.deletions ? index : index - content.deletions) : splitLineIndex + index);
2423
+ if (state.emit(getChangeLineData({
2424
+ hunkIndex,
2425
+ hunk,
2426
+ collapsedBefore: consumePendingCollapsed(),
2427
+ collapsedAfter,
2428
+ diffStyle,
2429
+ index,
2430
+ unifiedLineIndex,
2431
+ splitLineIndex,
2432
+ additionLineIndex,
2433
+ deletionLineIndex,
2434
+ additionLineNumber,
2435
+ deletionLineNumber,
2436
+ content,
2437
+ isLastContent,
2438
+ unifiedCount,
2439
+ splitCount
2440
+ }), true)) break hunkIterator;
2441
+ }
2442
+ }
2443
+ consumePendingCollapsed();
2444
+ state.incrementCounts(unifiedCount, splitCount);
2445
+ unifiedLineIndex += unifiedCount;
2446
+ splitLineIndex += splitCount;
2447
+ deletionLineIndex += content.deletions;
2448
+ additionLineIndex += content.additions;
2449
+ deletionLineNumber += content.deletions;
2450
+ additionLineNumber += content.additions;
2451
+ }
2452
+ }
2453
+ if (trailingRegion != null) {
2454
+ const { collapsedLines, fromStart, fromEnd } = trailingRegion;
2455
+ const len = fromStart + fromEnd;
2456
+ if (walkContextLines(state, len, diffStyle, (index) => {
2457
+ const isLastLine = index === len - 1;
2458
+ return state.emit({
2459
+ hunkIndex: diff.hunks.length,
2460
+ hunk: void 0,
2461
+ collapsedBefore: 0,
2462
+ collapsedAfter: isLastLine ? collapsedLines : 0,
2463
+ type: "context-expanded",
2464
+ deletionLine: {
2465
+ lineNumber: deletionLineNumber + index,
2466
+ lineIndex: deletionLineIndex + index,
2467
+ noEOFCR: false,
2468
+ unifiedLineIndex: unifiedLineIndex + index,
2469
+ splitLineIndex: splitLineIndex + index
2470
+ },
2471
+ additionLine: {
2472
+ unifiedLineIndex: unifiedLineIndex + index,
2473
+ splitLineIndex: splitLineIndex + index,
2474
+ lineIndex: additionLineIndex + index,
2475
+ lineNumber: additionLineNumber + index,
2476
+ noEOFCR: false
2477
+ }
2478
+ });
2479
+ }, void 0, () => state.shouldBreak())) break hunkIterator;
2480
+ }
2481
+ }
2482
+ }
2483
+ function getIterationStartState({ diff, diffStyle, startingLine, expandedHunks, collapsedContextThreshold }) {
2484
+ if (startingLine <= 0 || diffStyle === "both") return {
2485
+ hunkIndex: 0,
2486
+ splitCount: 0,
2487
+ unifiedCount: 0
2488
+ };
2489
+ const prefixCounts = getHunkPrefixCounts({
2490
+ diff,
2491
+ expandedHunks,
2492
+ collapsedContextThreshold
2493
+ });
2494
+ let low = 0;
2495
+ let high = diff.hunks.length - 1;
2496
+ let result = diff.hunks.length;
2497
+ while (low <= high) {
2498
+ const mid = low + high >> 1;
2499
+ const counts2 = prefixCounts[mid + 1];
2500
+ if (counts2 == null) throw new Error("iterateOverDiff: invalid hunk prefix index");
2501
+ if ((diffStyle === "unified" ? counts2.unifiedCount : counts2.splitCount) > startingLine) {
2502
+ result = mid;
2503
+ high = mid - 1;
2504
+ } else low = mid + 1;
2505
+ }
2506
+ if (result >= diff.hunks.length) {
2507
+ const counts2 = prefixCounts[diff.hunks.length];
2508
+ if (counts2 == null) throw new Error("iterateOverDiff: invalid terminal hunk prefix index");
2509
+ return {
2510
+ hunkIndex: diff.hunks.length,
2511
+ splitCount: counts2.splitCount,
2512
+ unifiedCount: counts2.unifiedCount
2513
+ };
2514
+ }
2515
+ const counts = prefixCounts[result];
2516
+ if (counts == null) throw new Error("iterateOverDiff: invalid selected hunk prefix index");
2517
+ return {
2518
+ hunkIndex: result,
2519
+ splitCount: counts.splitCount,
2520
+ unifiedCount: counts.unifiedCount
2521
+ };
2522
+ }
2523
+ function getHunkPrefixCounts({ diff, expandedHunks, collapsedContextThreshold }) {
2524
+ let splitCount = 0;
2525
+ let unifiedCount = 0;
2526
+ const finalHunkIndex = diff.hunks.length - 1;
2527
+ const prefixCounts = [{
2528
+ splitCount: 0,
2529
+ unifiedCount: 0
2530
+ }];
2531
+ for (let index = 0; index < diff.hunks.length; index++) {
2532
+ const hunk = diff.hunks[index];
2533
+ if (hunk == null) throw new Error("iterateOverDiff: invalid hunk summary index");
2534
+ const leadingRegion = getExpandedRegion({
2535
+ isPartial: diff.isPartial,
2536
+ rangeSize: hunk.collapsedBefore,
2537
+ expandedHunks,
2538
+ hunkIndex: index,
2539
+ collapsedContextThreshold
2540
+ });
2541
+ const leadingCount = leadingRegion.fromStart + leadingRegion.fromEnd;
2542
+ splitCount += leadingCount + hunk.splitLineCount;
2543
+ unifiedCount += leadingCount + hunk.unifiedLineCount;
2544
+ const trailingRegion = index === finalHunkIndex ? getTrailingExpandedRegion({
2545
+ fileDiff: diff,
2546
+ hunkIndex: index,
2547
+ expandedHunks,
2548
+ collapsedContextThreshold,
2549
+ errorPrefix: "iterateOverDiff"
2550
+ }) : void 0;
2551
+ if (trailingRegion != null) {
2552
+ const trailingCount = trailingRegion.fromStart + trailingRegion.fromEnd;
2553
+ splitCount += trailingCount;
2554
+ unifiedCount += trailingCount;
2555
+ }
2556
+ prefixCounts.push({
2557
+ splitCount,
2558
+ unifiedCount
2559
+ });
2560
+ }
2561
+ return prefixCounts;
2562
+ }
2563
+ function getContextLineIterationBounds(state, count, diffStyle) {
2564
+ if (!state.isWindowedHighlight || count <= 0) return [0, count];
2565
+ const ranges = [];
2566
+ function pushRange(currentCount) {
2567
+ const start2 = Math.max(0, state.viewportStart - currentCount);
2568
+ const end2 = Math.min(count, state.viewportEnd - currentCount);
2569
+ if (end2 > start2) ranges.push([start2, end2]);
2570
+ }
2571
+ if (diffStyle !== "split") pushRange(state.unifiedCount);
2572
+ if (diffStyle !== "unified") pushRange(state.splitCount);
2573
+ if (ranges.length === 0) return [0, 0];
2574
+ let start = ranges[0][0];
2575
+ let end = ranges[0][1];
2576
+ for (let index = 1; index < ranges.length; index++) {
2577
+ const range = ranges[index];
2578
+ start = Math.min(start, range[0]);
2579
+ end = Math.max(end, range[1]);
2580
+ }
2581
+ return [start, end];
2582
+ }
2583
+ function walkContextLines(state, count, diffStyle, callback, onSkippedStart, shouldBreak) {
2584
+ const [startIndex, endIndex] = getContextLineIterationBounds(state, count, diffStyle);
2585
+ if (startIndex > 0) {
2586
+ state.incrementCounts(startIndex, startIndex);
2587
+ onSkippedStart?.();
2588
+ }
2589
+ let index = startIndex;
2590
+ while (index < count) {
2591
+ if (shouldBreak?.() === true) return true;
2592
+ if (index >= endIndex) {
2593
+ state.incrementCounts(count - index, count - index);
2594
+ break;
2595
+ }
2596
+ if (state.isInWindow(0, 0)) {
2597
+ if (callback(index) === true) return true;
2598
+ } else state.incrementCounts(1, 1);
2599
+ index++;
2600
+ }
2601
+ return false;
2602
+ }
2603
+ function getChangeIterationRanges(state, content, diffStyle) {
2604
+ if (!state.isWindowedHighlight) return [[0, diffStyle === "unified" ? content.deletions + content.additions : Math.max(content.deletions, content.additions)]];
2605
+ const useUnified = diffStyle !== "split";
2606
+ const useSplit = diffStyle !== "unified";
2607
+ const iterationSpace = diffStyle === "unified" ? "unified" : "split";
2608
+ const iterationRanges = [];
2609
+ function getVisibleRange(start, count) {
2610
+ if (start + count <= state.viewportStart || start >= state.viewportEnd) return;
2611
+ const visibleStart = Math.max(0, state.viewportStart - start);
2612
+ const visibleEnd = Math.min(count, state.viewportEnd - start);
2613
+ return visibleEnd > visibleStart ? [visibleStart, visibleEnd] : void 0;
2614
+ }
2615
+ function mapRangeToIteration(range, kind) {
2616
+ if (iterationSpace === "split") return range;
2617
+ return kind === "additions" ? [range[0] + content.deletions, range[1] + content.deletions] : range;
2618
+ }
2619
+ function pushRange(range, kind) {
2620
+ if (range == null) return;
2621
+ const [start, end] = mapRangeToIteration(range, kind);
2622
+ if (end > start) iterationRanges.push([start, end]);
2623
+ }
2624
+ if (useUnified) {
2625
+ pushRange(getVisibleRange(state.unifiedCount, content.deletions), "deletions");
2626
+ pushRange(getVisibleRange(state.unifiedCount + content.deletions, content.additions), "additions");
2627
+ }
2628
+ if (useSplit) {
2629
+ pushRange(getVisibleRange(state.splitCount, content.deletions), "deletions");
2630
+ pushRange(getVisibleRange(state.splitCount, content.additions), "additions");
2631
+ }
2632
+ if (iterationRanges.length === 0) return iterationRanges;
2633
+ iterationRanges.sort((a, b) => a[0] - b[0]);
2634
+ const merged = [iterationRanges[0]];
2635
+ for (const [start, end] of iterationRanges.slice(1)) {
2636
+ const last = merged[merged.length - 1];
2637
+ if (start <= last[1]) last[1] = Math.max(last[1], end);
2638
+ else merged.push([start, end]);
2639
+ }
2640
+ return merged;
2641
+ }
2642
+ function getChangeLineData({ hunkIndex, hunk, collapsedAfter, collapsedBefore, diffStyle, index, unifiedLineIndex, splitLineIndex, additionLineIndex, deletionLineIndex, additionLineNumber, deletionLineNumber, content, isLastContent, unifiedCount, splitCount }) {
2643
+ const unifiedDeletionLineIndex = index < content.deletions ? unifiedLineIndex + index : void 0;
2644
+ const unifiedAdditionLineIndex = diffStyle === "unified" ? index >= content.deletions ? unifiedLineIndex + index : void 0 : index < content.additions ? unifiedLineIndex + content.deletions + index : void 0;
2645
+ const resolvedSplitLineIndex = diffStyle === "unified" ? splitLineIndex + (index < content.deletions ? index : index - content.deletions) : splitLineIndex + index;
2646
+ const deletionLineIndexValue = index < content.deletions ? deletionLineIndex + index : void 0;
2647
+ const deletionLineNumberValue = index < content.deletions ? deletionLineNumber + index : void 0;
2648
+ const additionLineIndexValue = diffStyle === "unified" ? index >= content.deletions ? additionLineIndex + (index - content.deletions) : void 0 : index < content.additions ? additionLineIndex + index : void 0;
2649
+ const additionLineNumberValue = diffStyle === "unified" ? index >= content.deletions ? additionLineNumber + (index - content.deletions) : void 0 : index < content.additions ? additionLineNumber + index : void 0;
2650
+ const noEOFCRDeletion = diffStyle === "unified" ? isLastContent && index === content.deletions - 1 && hunk.noEOFCRDeletions : isLastContent && index === splitCount - 1 && hunk.noEOFCRDeletions;
2651
+ const noEOFCRAddition = diffStyle === "unified" ? isLastContent && index === unifiedCount - 1 && hunk.noEOFCRAdditions : isLastContent && index === splitCount - 1 && hunk.noEOFCRAdditions;
2652
+ const deletionLine = deletionLineIndexValue != null && deletionLineNumberValue != null && unifiedDeletionLineIndex != null ? {
2653
+ lineNumber: deletionLineNumberValue,
2654
+ lineIndex: deletionLineIndexValue,
2655
+ noEOFCR: noEOFCRDeletion,
2656
+ unifiedLineIndex: unifiedDeletionLineIndex,
2657
+ splitLineIndex: resolvedSplitLineIndex
2658
+ } : void 0;
2659
+ const additionLine = additionLineIndexValue != null && additionLineNumberValue != null && unifiedAdditionLineIndex != null ? {
2660
+ unifiedLineIndex: unifiedAdditionLineIndex,
2661
+ splitLineIndex: resolvedSplitLineIndex,
2662
+ lineIndex: additionLineIndexValue,
2663
+ lineNumber: additionLineNumberValue,
2664
+ noEOFCR: noEOFCRAddition
2665
+ } : void 0;
2666
+ if (deletionLine == null && additionLine != null) return {
2667
+ type: "change",
2668
+ hunkIndex,
2669
+ hunk,
2670
+ collapsedAfter,
2671
+ collapsedBefore,
2672
+ deletionLine: void 0,
2673
+ additionLine
2674
+ };
2675
+ else if (deletionLine != null && additionLine == null) return {
2676
+ type: "change",
2677
+ hunkIndex,
2678
+ hunk,
2679
+ collapsedAfter,
2680
+ collapsedBefore,
2681
+ deletionLine,
2682
+ additionLine: void 0
2683
+ };
2684
+ if (deletionLine == null || additionLine == null) throw new Error("iterateOverDiff: missing change line data");
2685
+ return {
2686
+ type: "change",
2687
+ hunkIndex,
2688
+ hunk,
2689
+ collapsedAfter,
2690
+ collapsedBefore,
2691
+ deletionLine,
2692
+ additionLine
2693
+ };
2694
+ }
2695
+ const DEFAULT_PLAIN_TEXT_OPTIONS = { forcePlainText: false };
2696
+ function renderDiffWithHighlighter(diff, highlighter2, options, { forcePlainText, startingLine, totalLines, expandedHunks, collapsedContextThreshold = 1 } = DEFAULT_PLAIN_TEXT_OPTIONS) {
2697
+ if (forcePlainText) {
2698
+ startingLine ??= 0;
2699
+ totalLines ??= Infinity;
2700
+ } else {
2701
+ startingLine = 0;
2702
+ totalLines = Infinity;
2703
+ }
2704
+ const isWindowedHighlight = startingLine > 0 || totalLines < Infinity;
2705
+ const baseThemeType = typeof options.theme === "string" ? highlighter2.getTheme(options.theme).type : void 0;
2706
+ const themeStyles = getHighlighterThemeStyles({
2707
+ theme: options.theme,
2708
+ highlighter: highlighter2
2709
+ });
2710
+ const lineDiffType = forcePlainText && !isWindowedHighlight && (diff.unifiedLineCount > 1e3 || diff.splitLineCount > 1e3) ? "none" : options.lineDiffType;
2711
+ const code = {
2712
+ deletionLines: [],
2713
+ additionLines: []
2714
+ };
2715
+ const { maxLineDiffLength } = options;
2716
+ const shouldGroupAll = !forcePlainText && !diff.isPartial;
2717
+ const expandedHunksForIteration = forcePlainText ? expandedHunks : void 0;
2718
+ const buckets = /* @__PURE__ */ new Map();
2719
+ function getBucketForHunk(hunkIndex) {
2720
+ const index = shouldGroupAll ? 0 : hunkIndex;
2721
+ const bucket = buckets.get(index) ?? createBucket();
2722
+ buckets.set(index, bucket);
2723
+ return bucket;
2724
+ }
2725
+ function appendContent(lineContent, lineIndex, segments, contentWrapper) {
2726
+ if (isWindowedHighlight) {
2727
+ let segment = segments.at(-1);
2728
+ if (segment == null || segment.targetIndex + segment.count !== lineIndex) {
2729
+ segment = {
2730
+ targetIndex: lineIndex,
2731
+ originalOffset: contentWrapper.length,
2732
+ count: 0
2733
+ };
2734
+ segments.push(segment);
2735
+ }
2736
+ segment.count++;
2737
+ }
2738
+ contentWrapper.push(lineContent);
2739
+ }
2740
+ iterateOverDiff({
2741
+ diff,
2742
+ diffStyle: "both",
2743
+ startingLine,
2744
+ totalLines,
2745
+ expandedHunks: isWindowedHighlight ? expandedHunksForIteration : true,
2746
+ collapsedContextThreshold,
2747
+ callback: ({ hunkIndex, additionLine, deletionLine, type }) => {
2748
+ const bucket = getBucketForHunk(hunkIndex);
2749
+ const splitLineIndex = additionLine != null ? additionLine.splitLineIndex : deletionLine.splitLineIndex;
2750
+ if (type === "change" && additionLine != null && deletionLine != null) computeLineDiffDecorations({
2751
+ additionLine: diff.additionLines[additionLine.lineIndex],
2752
+ deletionLine: diff.deletionLines[deletionLine.lineIndex],
2753
+ deletionLineIndex: bucket.deletionContent.length,
2754
+ additionLineIndex: bucket.additionContent.length,
2755
+ deletionDecorations: bucket.deletionDecorations,
2756
+ additionDecorations: bucket.additionDecorations,
2757
+ lineDiffType,
2758
+ maxLineDiffLength
2759
+ });
2760
+ if (deletionLine != null) {
2761
+ appendContent(diff.deletionLines[deletionLine.lineIndex], deletionLine.lineIndex, bucket.deletionSegments, bucket.deletionContent);
2762
+ bucket.deletionInfo.push({
2763
+ type: type === "change" ? "change-deletion" : type,
2764
+ lineNumber: deletionLine.lineNumber,
2765
+ altLineNumber: type === "change" ? void 0 : additionLine.lineNumber ?? void 0,
2766
+ lineIndex: `${deletionLine.unifiedLineIndex},${splitLineIndex}`
2767
+ });
2768
+ }
2769
+ if (additionLine != null) {
2770
+ appendContent(diff.additionLines[additionLine.lineIndex], additionLine.lineIndex, bucket.additionSegments, bucket.additionContent);
2771
+ bucket.additionInfo.push({
2772
+ type: type === "change" ? "change-addition" : type,
2773
+ lineNumber: additionLine.lineNumber,
2774
+ altLineNumber: type === "change" ? void 0 : deletionLine.lineNumber ?? void 0,
2775
+ lineIndex: `${additionLine.unifiedLineIndex},${splitLineIndex}`
2776
+ });
2777
+ }
2778
+ }
2779
+ });
2780
+ for (const bucket of buckets.values()) {
2781
+ if (bucket.deletionContent.length === 0 && bucket.additionContent.length === 0) continue;
2782
+ const deletionFile = {
2783
+ name: diff.prevName ?? diff.name,
2784
+ contents: bucket.deletionContent.value
2785
+ };
2786
+ const additionFile = {
2787
+ name: diff.name,
2788
+ contents: bucket.additionContent.value
2789
+ };
2790
+ const { deletionLines, additionLines } = renderTwoFiles({
2791
+ deletionFile,
2792
+ deletionInfo: bucket.deletionInfo,
2793
+ deletionDecorations: bucket.deletionDecorations,
2794
+ additionFile,
2795
+ additionInfo: bucket.additionInfo,
2796
+ additionDecorations: bucket.additionDecorations,
2797
+ highlighter: highlighter2,
2798
+ options,
2799
+ languageOverride: forcePlainText ? "text" : diff.lang
2800
+ });
2801
+ if (shouldGroupAll) {
2802
+ code.deletionLines = deletionLines;
2803
+ code.additionLines = additionLines;
2804
+ continue;
2805
+ }
2806
+ if (bucket.deletionSegments.length > 0) for (const seg of bucket.deletionSegments) for (let i = 0; i < seg.count; i++) code.deletionLines[seg.targetIndex + i] = deletionLines[seg.originalOffset + i];
2807
+ else appendItems(code.deletionLines, deletionLines);
2808
+ if (bucket.additionSegments.length > 0) for (const seg of bucket.additionSegments) for (let i = 0; i < seg.count; i++) code.additionLines[seg.targetIndex + i] = additionLines[seg.originalOffset + i];
2809
+ else appendItems(code.additionLines, additionLines);
2810
+ }
2811
+ return {
2812
+ code,
2813
+ themeStyles,
2814
+ baseThemeType
2815
+ };
2816
+ }
2817
+ function pushWordLineDecorations(lineDiff, { deletionLineIndex, additionLineIndex, deletionDecorations, additionDecorations }) {
2818
+ let deletionOffset = 0;
2819
+ let additionOffset = 0;
2820
+ let deletionStart = -1;
2821
+ let deletionEnd = 0;
2822
+ let additionStart = -1;
2823
+ let additionEnd = 0;
2824
+ for (const { value, added, removed } of lineDiff) if (removed) {
2825
+ if (deletionStart === -1) deletionStart = deletionOffset;
2826
+ deletionOffset += value.length;
2827
+ deletionEnd = deletionOffset;
2828
+ } else if (added) {
2829
+ if (additionStart === -1) additionStart = additionOffset;
2830
+ additionOffset += value.length;
2831
+ additionEnd = additionOffset;
2832
+ } else {
2833
+ deletionOffset += value.length;
2834
+ additionOffset += value.length;
2835
+ }
2836
+ if (deletionStart !== -1) deletionDecorations.push(createDiffSpanDecoration({
2837
+ line: deletionLineIndex,
2838
+ spanStart: deletionStart,
2839
+ spanLength: deletionEnd - deletionStart
2840
+ }));
2841
+ if (additionStart !== -1) additionDecorations.push(createDiffSpanDecoration({
2842
+ line: additionLineIndex,
2843
+ spanStart: additionStart,
2844
+ spanLength: additionEnd - additionStart
2845
+ }));
2846
+ }
2847
+ function computeLineDiffDecorations({ deletionLine, additionLine, deletionLineIndex, additionLineIndex, deletionDecorations, additionDecorations, lineDiffType, maxLineDiffLength }) {
2848
+ if (deletionLine == null || additionLine == null || lineDiffType === "none") return;
2849
+ deletionLine = cleanLastNewline(deletionLine);
2850
+ additionLine = cleanLastNewline(additionLine);
2851
+ if (deletionLine.length > maxLineDiffLength || additionLine.length > maxLineDiffLength) return;
2852
+ const lineDiff = lineDiffType === "char" ? diffChars(deletionLine, additionLine) : diffWordsWithSpace(deletionLine, additionLine);
2853
+ if (lineDiffType === "word-line") {
2854
+ pushWordLineDecorations(lineDiff, {
2855
+ deletionLineIndex,
2856
+ additionLineIndex,
2857
+ deletionDecorations,
2858
+ additionDecorations
2859
+ });
2860
+ return;
2861
+ }
2862
+ const deletionSpans = [];
2863
+ const additionSpans = [];
2864
+ const enableJoin = lineDiffType === "word-alt";
2865
+ const lastItem = lineDiff.at(-1);
2866
+ for (const item of lineDiff) {
2867
+ const isLastItem = item === lastItem;
2868
+ if (!item.added && !item.removed) {
2869
+ pushOrJoinSpan({
2870
+ item,
2871
+ arr: deletionSpans,
2872
+ enableJoin,
2873
+ isNeutral: true,
2874
+ isLastItem
2875
+ });
2876
+ pushOrJoinSpan({
2877
+ item,
2878
+ arr: additionSpans,
2879
+ enableJoin,
2880
+ isNeutral: true,
2881
+ isLastItem
2882
+ });
2883
+ } else if (item.removed) pushOrJoinSpan({
2884
+ item,
2885
+ arr: deletionSpans,
2886
+ enableJoin,
2887
+ isLastItem
2888
+ });
2889
+ else pushOrJoinSpan({
2890
+ item,
2891
+ arr: additionSpans,
2892
+ enableJoin,
2893
+ isLastItem
2894
+ });
2895
+ }
2896
+ let spanIndex = 0;
2897
+ for (const span of deletionSpans) {
2898
+ if (span[0] === 1) deletionDecorations.push(createDiffSpanDecoration({
2899
+ line: deletionLineIndex,
2900
+ spanStart: spanIndex,
2901
+ spanLength: span[1].length
2902
+ }));
2903
+ spanIndex += span[1].length;
2904
+ }
2905
+ spanIndex = 0;
2906
+ for (const span of additionSpans) {
2907
+ if (span[0] === 1) additionDecorations.push(createDiffSpanDecoration({
2908
+ line: additionLineIndex,
2909
+ spanStart: spanIndex,
2910
+ spanLength: span[1].length
2911
+ }));
2912
+ spanIndex += span[1].length;
2913
+ }
2914
+ }
2915
+ function createBucket() {
2916
+ return {
2917
+ deletionContent: {
2918
+ push(value) {
2919
+ this.value += value;
2920
+ this.length++;
2921
+ },
2922
+ value: "",
2923
+ length: 0
2924
+ },
2925
+ additionContent: {
2926
+ push(value) {
2927
+ this.value += value;
2928
+ this.length++;
2929
+ },
2930
+ value: "",
2931
+ length: 0
2932
+ },
2933
+ deletionInfo: [],
2934
+ additionInfo: [],
2935
+ deletionDecorations: [],
2936
+ additionDecorations: [],
2937
+ deletionSegments: [],
2938
+ additionSegments: []
2939
+ };
2940
+ }
2941
+ function renderTwoFiles({ deletionFile, additionFile, deletionInfo, additionInfo, highlighter: highlighter2, deletionDecorations, additionDecorations, languageOverride, options: { theme: themeOrThemes, ...options } }) {
2942
+ const deletionLang = languageOverride ?? getFiletypeFromFileName(deletionFile.name);
2943
+ const additionLang = languageOverride ?? getFiletypeFromFileName(additionFile.name);
2944
+ const { state, transformers } = createTransformerWithState(options.useTokenTransformer);
2945
+ const hastConfig = (() => {
2946
+ return typeof themeOrThemes === "string" ? {
2947
+ ...options,
2948
+ lang: "text",
2949
+ theme: themeOrThemes,
2950
+ transformers,
2951
+ decorations: void 0,
2952
+ defaultColor: false,
2953
+ cssVariablePrefix: formatCSSVariablePrefix("token"),
2954
+ tokenizeTimeLimit: 0
2955
+ } : {
2956
+ ...options,
2957
+ lang: "text",
2958
+ themes: themeOrThemes,
2959
+ transformers,
2960
+ decorations: void 0,
2961
+ defaultColor: false,
2962
+ cssVariablePrefix: formatCSSVariablePrefix("token"),
2963
+ tokenizeTimeLimit: 0
2964
+ };
2965
+ })();
2966
+ return {
2967
+ deletionLines: (() => {
2968
+ if (deletionFile.contents === "") return [];
2969
+ hastConfig.lang = deletionLang;
2970
+ state.lineInfo = deletionInfo;
2971
+ hastConfig.decorations = deletionDecorations;
2972
+ return getLineNodes(highlighter2.codeToHast(cleanLastNewline(deletionFile.contents), hastConfig));
2973
+ })(),
2974
+ additionLines: (() => {
2975
+ if (additionFile.contents === "") return [];
2976
+ hastConfig.lang = additionLang;
2977
+ hastConfig.decorations = additionDecorations;
2978
+ state.lineInfo = additionInfo;
2979
+ return getLineNodes(highlighter2.codeToHast(cleanLastNewline(additionFile.contents), hastConfig));
2980
+ })()
2981
+ };
2982
+ }
2983
+ function isDiffPlainText(diff) {
2984
+ const computedLang = diff.lang ?? getFiletypeFromFileName(diff.name);
2985
+ const computedPreviousLang = diff.lang ?? (diff.prevName != null ? getFiletypeFromFileName(diff.prevName) : "text");
2986
+ return computedLang === "text" && computedPreviousLang === "text";
2987
+ }
2988
+ function getResolvedLanguages(languages) {
2989
+ const resolvedLanguages = [];
2990
+ for (const language of languages) {
2991
+ const resolvedLanguage = ResolvedLanguages.get(language);
2992
+ if (resolvedLanguage == null) throw new Error(`getResolvedLanguages: ${language} is not resolved. Please resolve languages before calling getResolvedLanguages`);
2993
+ resolvedLanguages.push(resolvedLanguage);
2994
+ }
2995
+ return resolvedLanguages;
2996
+ }
2997
+ function hasResolvedLanguages(languages) {
2998
+ for (const language of Array.isArray(languages) ? languages : [languages]) if (!ResolvedLanguages.has(language)) return false;
2999
+ return true;
3000
+ }
3001
+ async function resolveLanguages(languages) {
3002
+ const resolvedLanguages = [];
3003
+ const languagesToResolve = [];
3004
+ for (const language of languages) {
3005
+ if (language === "text" || language === "ansi") continue;
3006
+ const maybeResolvedLanguage = getResolvedOrResolveLanguage(language) ?? resolveLanguage(language);
3007
+ if ("then" in maybeResolvedLanguage) languagesToResolve.push(maybeResolvedLanguage);
3008
+ else resolvedLanguages.push(maybeResolvedLanguage);
3009
+ }
3010
+ if (languagesToResolve.length > 0) await Promise.all(languagesToResolve).then((_resolvedLanguages) => {
3011
+ for (const resolvedLanguage of _resolvedLanguages) {
3012
+ if (resolvedLanguage == null) throw new Error("resolvedLanguages: unable to resolve language");
3013
+ resolvedLanguages.push(resolvedLanguage);
3014
+ }
3015
+ });
3016
+ return resolvedLanguages;
3017
+ }
3018
+ function getResolvedThemes(themeNames) {
3019
+ return themeResolver.getResolvedThemes(themeNames);
3020
+ }
3021
+ async function resolveThemes(themes) {
3022
+ for (const themeName of themes) prepareThemeResolution(themeName);
3023
+ const resolvedThemes = await themeResolver.resolveThemes(themes);
3024
+ for (let i = 0; i < themes.length; i++) validateResolvedThemeName(themes[i], resolvedThemes[i]);
3025
+ return resolvedThemes;
3026
+ }
3027
+ var lru$1 = { exports: {} };
3028
+ var lru = lru$1.exports;
3029
+ var hasRequiredLru;
3030
+ function requireLru() {
3031
+ if (hasRequiredLru) return lru$1.exports;
3032
+ hasRequiredLru = 1;
3033
+ (function(module, exports) {
3034
+ !(function(g, c) {
3035
+ c(exports);
3036
+ })(lru, function(g) {
3037
+ const c = /* @__PURE__ */ Symbol("newer"), e = /* @__PURE__ */ Symbol("older");
3038
+ class n {
3039
+ constructor(a, b) {
3040
+ typeof a !== "number" && (b = a, a = 0), this.size = 0, this.limit = a, this.oldest = this.newest = void 0, this._keymap = /* @__PURE__ */ new Map(), b && (this.assign(b), a < 1 && (this.limit = this.size));
3041
+ }
3042
+ _markEntryAsUsed(a) {
3043
+ if (a === this.newest) return;
3044
+ a[c] && (a === this.oldest && (this.oldest = a[c]), a[c][e] = a[e]), a[e] && (a[e][c] = a[c]), a[c] = void 0, a[e] = this.newest, this.newest && (this.newest[c] = a), this.newest = a;
3045
+ }
3046
+ assign(a) {
3047
+ let b, d = this.limit || Number.MAX_VALUE;
3048
+ this._keymap.clear();
3049
+ let m = a[Symbol.iterator]();
3050
+ for (let h = m.next(); !h.done; h = m.next()) {
3051
+ let f = new l(h.value[0], h.value[1]);
3052
+ this._keymap.set(f.key, f), b ? (b[c] = f, f[e] = b) : this.oldest = f, b = f;
3053
+ if (d-- == 0) throw new Error("overflow");
3054
+ }
3055
+ this.newest = b, this.size = this._keymap.size;
3056
+ }
3057
+ get(a) {
3058
+ var b = this._keymap.get(a);
3059
+ return b ? (this._markEntryAsUsed(b), b.value) : void 0;
3060
+ }
3061
+ set(a, b) {
3062
+ var d = this._keymap.get(a);
3063
+ return d ? (d.value = b, this._markEntryAsUsed(d), this) : (this._keymap.set(a, d = new l(a, b)), this.newest ? (this.newest[c] = d, d[e] = this.newest) : this.oldest = d, this.newest = d, ++this.size, this.size > this.limit && this.shift(), this);
3064
+ }
3065
+ shift() {
3066
+ var a = this.oldest;
3067
+ if (a) return this.oldest[c] ? (this.oldest = this.oldest[c], this.oldest[e] = void 0) : (this.oldest = void 0, this.newest = void 0), a[c] = a[e] = void 0, this._keymap.delete(a.key), --this.size, [a.key, a.value];
3068
+ }
3069
+ find(a) {
3070
+ let b = this._keymap.get(a);
3071
+ return b ? b.value : void 0;
3072
+ }
3073
+ has(a) {
3074
+ return this._keymap.has(a);
3075
+ }
3076
+ delete(a) {
3077
+ var b = this._keymap.get(a);
3078
+ return b ? (this._keymap.delete(b.key), b[c] && b[e] ? (b[e][c] = b[c], b[c][e] = b[e]) : b[c] ? (b[c][e] = void 0, this.oldest = b[c]) : b[e] ? (b[e][c] = void 0, this.newest = b[e]) : this.oldest = this.newest = void 0, this.size--, b.value) : void 0;
3079
+ }
3080
+ clear() {
3081
+ this.oldest = this.newest = void 0, this.size = 0, this._keymap.clear();
3082
+ }
3083
+ keys() {
3084
+ return new j(this.oldest);
3085
+ }
3086
+ values() {
3087
+ return new k(this.oldest);
3088
+ }
3089
+ entries() {
3090
+ return this;
3091
+ }
3092
+ [Symbol.iterator]() {
3093
+ return new i(this.oldest);
3094
+ }
3095
+ forEach(a, b) {
3096
+ typeof b !== "object" && (b = this);
3097
+ let d = this.oldest;
3098
+ for (; d; ) a.call(b, d.value, d.key, this), d = d[c];
3099
+ }
3100
+ toJSON() {
3101
+ for (var a = new Array(this.size), b = 0, d = this.oldest; d; ) a[b++] = { key: d.key, value: d.value }, d = d[c];
3102
+ return a;
3103
+ }
3104
+ toString() {
3105
+ for (var a = "", b = this.oldest; b; ) a += String(b.key) + ":" + b.value, b = b[c], b && (a += " < ");
3106
+ return a;
3107
+ }
3108
+ }
3109
+ g.LRUMap = n;
3110
+ function l(a, b) {
3111
+ this.key = a, this.value = b, this[c] = void 0, this[e] = void 0;
3112
+ }
3113
+ function i(a) {
3114
+ this.entry = a;
3115
+ }
3116
+ i.prototype[Symbol.iterator] = function() {
3117
+ return this;
3118
+ }, i.prototype.next = function() {
3119
+ let a = this.entry;
3120
+ return a ? (this.entry = a[c], { done: false, value: [a.key, a.value] }) : { done: true, value: void 0 };
3121
+ };
3122
+ function j(a) {
3123
+ this.entry = a;
3124
+ }
3125
+ j.prototype[Symbol.iterator] = function() {
3126
+ return this;
3127
+ }, j.prototype.next = function() {
3128
+ let a = this.entry;
3129
+ return a ? (this.entry = a[c], { done: false, value: a.key }) : { done: true, value: void 0 };
3130
+ };
3131
+ function k(a) {
3132
+ this.entry = a;
3133
+ }
3134
+ k.prototype[Symbol.iterator] = function() {
3135
+ return this;
3136
+ }, k.prototype.next = function() {
3137
+ let a = this.entry;
3138
+ return a ? (this.entry = a[c], { done: false, value: a.value }) : { done: true, value: void 0 };
3139
+ };
3140
+ });
3141
+ })(lru$1, lru$1.exports);
3142
+ return lru$1.exports;
3143
+ }
3144
+ var lruExports = requireLru();
3145
+ const LRUMapPkg = /* @__PURE__ */ getDefaultExportFromCjs(lruExports);
3146
+ const IGNORE_RESPONSE = /* @__PURE__ */ Symbol("IGNORE_RESPONSE");
3147
+ const DEFAULT_WORKER_INITIALIZATION_TIMEOUT = 1e4;
3148
+ var WorkerPoolManager = class {
3149
+ options;
3150
+ highlighter;
3151
+ preferredHighlighter;
3152
+ renderOptions;
3153
+ renderOptionsRequestVersion = 0;
3154
+ renderOptionsVersion = 0;
3155
+ initialized = false;
3156
+ workers = [];
3157
+ queuedTasks = [];
3158
+ queuedTaskByInstance = /* @__PURE__ */ new Map();
3159
+ taskByHighlightKey = /* @__PURE__ */ new Map();
3160
+ activeTaskById = /* @__PURE__ */ new Map();
3161
+ activeRequestByInstance = /* @__PURE__ */ new Map();
3162
+ nextRequestId = 0;
3163
+ themeSubscribers = /* @__PURE__ */ new Set();
3164
+ workersFailed = false;
3165
+ statSubscribers = /* @__PURE__ */ new Set();
3166
+ fileCache;
3167
+ diffCache;
3168
+ _queuedBroadcast;
3169
+ lifecycleGeneration = 0;
3170
+ constructor(options, { langs, theme = DEFAULT_THEMES, useTokenTransformer = false, lineDiffType = "word-alt", maxLineDiffLength = 1e3, tokenizeMaxLineLength = 1e3, preferredHighlighter = "shiki-js" }) {
3171
+ this.options = options;
3172
+ this.preferredHighlighter = preferredHighlighter;
3173
+ this.renderOptions = {
3174
+ theme,
3175
+ useTokenTransformer,
3176
+ lineDiffType,
3177
+ maxLineDiffLength,
3178
+ tokenizeMaxLineLength
3179
+ };
3180
+ this.fileCache = new LRUMapPkg.LRUMap(options.totalASTLRUCacheSize ?? 100);
3181
+ this.diffCache = new LRUMapPkg.LRUMap(options.totalASTLRUCacheSize ?? 100);
3182
+ this.queueInitialization(langs);
3183
+ }
3184
+ isWorkingPool() {
3185
+ return !this.workersFailed;
3186
+ }
3187
+ getFileResultCache(file) {
3188
+ return file.cacheKey != null ? this.fileCache.get(file.cacheKey) : void 0;
3189
+ }
3190
+ getDiffResultCache(diff) {
3191
+ return diff.cacheKey != null ? this.diffCache.get(diff.cacheKey) : void 0;
3192
+ }
3193
+ inspectCaches() {
3194
+ const { fileCache, diffCache } = this;
3195
+ return {
3196
+ fileCache,
3197
+ diffCache
3198
+ };
3199
+ }
3200
+ evictFileFromCache(cacheKey) {
3201
+ try {
3202
+ return this.fileCache.delete(cacheKey) !== void 0;
3203
+ } finally {
3204
+ this.queueBroadcastStateChanges();
3205
+ }
3206
+ }
3207
+ evictDiffFromCache(cacheKey) {
3208
+ try {
3209
+ return this.diffCache.delete(cacheKey) !== void 0;
3210
+ } finally {
3211
+ this.queueBroadcastStateChanges();
3212
+ }
3213
+ }
3214
+ async setRenderOptions({ theme = this.renderOptions.theme ?? DEFAULT_THEMES, useTokenTransformer = this.renderOptions.useTokenTransformer ?? false, lineDiffType = this.renderOptions.lineDiffType ?? "word-alt", maxLineDiffLength = this.renderOptions.maxLineDiffLength ?? 1e3, tokenizeMaxLineLength = this.renderOptions.tokenizeMaxLineLength ?? 1e3 }) {
3215
+ const { lifecycleGeneration } = this;
3216
+ const renderOptionsRequestVersion = ++this.renderOptionsRequestVersion;
3217
+ const isCurrentRequest = () => this.isCurrentLifecycle(lifecycleGeneration) && this.renderOptionsRequestVersion === renderOptionsRequestVersion;
3218
+ try {
3219
+ const newRenderOptions = {
3220
+ theme,
3221
+ useTokenTransformer,
3222
+ lineDiffType,
3223
+ maxLineDiffLength,
3224
+ tokenizeMaxLineLength
3225
+ };
3226
+ if (!this.isInitialized()) await this.initialize();
3227
+ if (!isCurrentRequest() || areDiffRenderOptionsEqual(newRenderOptions, this.renderOptions)) return;
3228
+ const themeNames = getThemes(theme);
3229
+ let resolvedThemes = [];
3230
+ if (!areThemesEqual(newRenderOptions.theme, this.renderOptions.theme)) {
3231
+ if (hasResolvedThemes(themeNames)) resolvedThemes = getResolvedThemes(themeNames);
3232
+ else resolvedThemes = await resolveThemes(themeNames);
3233
+ }
3234
+ if (!isCurrentRequest()) return;
3235
+ if (this.highlighter != null) attachResolvedThemes(resolvedThemes, this.highlighter);
3236
+ else {
3237
+ const highlighter2 = await getSharedHighlighter({
3238
+ themes: themeNames,
3239
+ langs: ["text"],
3240
+ preferredHighlighter: this.preferredHighlighter
3241
+ });
3242
+ if (!isCurrentRequest()) return;
3243
+ this.highlighter = highlighter2;
3244
+ }
3245
+ const workerSetup = this.setRenderOptionsOnWorkers(newRenderOptions, resolvedThemes);
3246
+ this.renderOptions = newRenderOptions;
3247
+ this.renderOptionsVersion++;
3248
+ this.diffCache.clear();
3249
+ this.fileCache.clear();
3250
+ this.invalidateRenderTasks();
3251
+ for (const instance of this.themeSubscribers) instance.onThemeChange();
3252
+ await workerSetup;
3253
+ } catch (error) {
3254
+ if (error instanceof WorkerPoolTerminatedError || !isCurrentRequest()) return;
3255
+ throw error;
3256
+ }
3257
+ }
3258
+ getPreferredHighlighter() {
3259
+ return this.preferredHighlighter;
3260
+ }
3261
+ getFileRenderOptions() {
3262
+ const { tokenizeMaxLineLength, theme, useTokenTransformer } = this.renderOptions;
3263
+ return {
3264
+ theme,
3265
+ useTokenTransformer,
3266
+ tokenizeMaxLineLength
3267
+ };
3268
+ }
3269
+ getDiffRenderOptions() {
3270
+ return { ...this.renderOptions };
3271
+ }
3272
+ async setRenderOptionsOnWorkers(renderOptions, resolvedThemes) {
3273
+ if (this.workersFailed) return;
3274
+ if (!this.isInitialized()) await this.initialize();
3275
+ const taskPromises = [];
3276
+ for (const managedWorker of this.workers) {
3277
+ if (!managedWorker.initialized) {
3278
+ console.log({ managedWorker });
3279
+ throw new Error("setRenderOptionsOnWorkers: Somehow we have an uninitialized worker");
3280
+ }
3281
+ taskPromises.push(new Promise((resolve, reject) => {
3282
+ const id = this.generateRequestId();
3283
+ const task = {
3284
+ type: "set-render-options",
3285
+ id,
3286
+ request: {
3287
+ type: "set-render-options",
3288
+ id,
3289
+ renderOptions,
3290
+ resolvedThemes
3291
+ },
3292
+ resolve,
3293
+ reject,
3294
+ requestStart: Date.now()
3295
+ };
3296
+ this.activeTaskById.set(id, task);
3297
+ managedWorker.pendingSetupRequestId = id;
3298
+ managedWorker.worker.postMessage(task.request);
3299
+ }));
3300
+ }
3301
+ await Promise.all(taskPromises);
3302
+ }
3303
+ subscribeToThemeChanges(instance) {
3304
+ this.themeSubscribers.add(instance);
3305
+ this.queueBroadcastStateChanges();
3306
+ return () => {
3307
+ this.unsubscribeToThemeChanges(instance);
3308
+ this.queueBroadcastStateChanges();
3309
+ };
3310
+ }
3311
+ unsubscribeToThemeChanges(instance) {
3312
+ this.themeSubscribers.delete(instance);
3313
+ this.queueBroadcastStateChanges();
3314
+ }
3315
+ subscribeToStatChanges(callback) {
3316
+ this.statSubscribers.add(callback);
3317
+ callback(this.getStats());
3318
+ return () => {
3319
+ this.statSubscribers.delete(callback);
3320
+ };
3321
+ }
3322
+ queueBroadcastStateChanges() {
3323
+ if (this._queuedBroadcast != null) return;
3324
+ this._queuedBroadcast = requestAnimationFrame(this._broadcastStateChanges);
3325
+ }
3326
+ _broadcastStateChanges = () => {
3327
+ if (this._queuedBroadcast != null) {
3328
+ cancelAnimationFrame(this._queuedBroadcast);
3329
+ this._queuedBroadcast = void 0;
3330
+ }
3331
+ const stats = this.getStats();
3332
+ for (const callback of this.statSubscribers) callback(stats);
3333
+ };
3334
+ cleanUpTasks(instance) {
3335
+ this.detachInstanceFromQueuedTasks(instance);
3336
+ const requestId = this.activeRequestByInstance.get(instance);
3337
+ if (requestId != null) {
3338
+ const task = this.activeTaskById.get(requestId);
3339
+ if (isRenderTask(task)) {
3340
+ this.detachInstanceFromRenderTask(task, instance);
3341
+ if (!task.primeCache && task.instances.size === 0) this.removeActiveTask(task);
3342
+ } else this.activeTaskById.delete(requestId);
3343
+ }
3344
+ this.activeRequestByInstance.delete(instance);
3345
+ this.queueBroadcastStateChanges();
3346
+ }
3347
+ isInitialized() {
3348
+ return this.initialized === true;
3349
+ }
3350
+ async initialize(languages = []) {
3351
+ if (this.initialized === true) return;
3352
+ else if (this.initialized === false) {
3353
+ const { lifecycleGeneration } = this;
3354
+ const initialization = new Promise((resolve, reject) => {
3355
+ (async () => {
3356
+ try {
3357
+ const themes = getThemes(this.renderOptions.theme);
3358
+ let resolvedThemes = [];
3359
+ if (hasResolvedThemes(themes)) resolvedThemes = getResolvedThemes(themes);
3360
+ else resolvedThemes = await resolveThemes(themes);
3361
+ if (!this.isCurrentLifecycle(lifecycleGeneration)) {
3362
+ resolve();
3363
+ return;
3364
+ }
3365
+ let resolvedLanguages = [];
3366
+ if (hasResolvedLanguages(languages)) resolvedLanguages = getResolvedLanguages(languages);
3367
+ else resolvedLanguages = await resolveLanguages(languages);
3368
+ if (!this.isCurrentLifecycle(lifecycleGeneration)) {
3369
+ resolve();
3370
+ return;
3371
+ }
3372
+ const [highlighter2] = await Promise.all([getSharedHighlighter({
3373
+ themes,
3374
+ langs: ["text", ...languages],
3375
+ preferredHighlighter: this.preferredHighlighter
3376
+ }), this.initializeWorkers(resolvedThemes, resolvedLanguages)]);
3377
+ if (!this.isCurrentLifecycle(lifecycleGeneration)) {
3378
+ this.terminateWorkers();
3379
+ resolve();
3380
+ return;
3381
+ }
3382
+ this.highlighter = highlighter2;
3383
+ this.initialized = true;
3384
+ this.diffCache.clear();
3385
+ this.fileCache.clear();
3386
+ this.drainQueue();
3387
+ this.queueBroadcastStateChanges();
3388
+ resolve();
3389
+ } catch (e) {
3390
+ if (e instanceof WorkerPoolTerminatedError || !this.isCurrentLifecycle(lifecycleGeneration)) {
3391
+ resolve();
3392
+ return;
3393
+ }
3394
+ this.initialized = false;
3395
+ this.workersFailed = true;
3396
+ this.cancelActiveWorkerTasks();
3397
+ this.terminateWorkers();
3398
+ this.activeTaskById.clear();
3399
+ for (const task of this.queuedTasks) this.rejectRenderTaskCallbacks(task, normalizeWorkerError(e));
3400
+ this.queueBroadcastStateChanges();
3401
+ reject(e);
3402
+ }
3403
+ })();
3404
+ });
3405
+ this.initialized = initialization;
3406
+ this.queueBroadcastStateChanges();
3407
+ return initialization;
3408
+ } else return this.initialized;
3409
+ }
3410
+ async initializeWorkers(resolvedThemes, resolvedLanguages) {
3411
+ this.workersFailed = false;
3412
+ const initPromises = [];
3413
+ const customExtensionVersion = getCustomExtensionsVersion();
3414
+ const customExtensionMap = customExtensionVersion > 0 ? getCustomExtensionsMap() : void 0;
3415
+ if (this.workers.length > 0) this.terminateWorkers();
3416
+ for (let i = 0; i < (this.options.poolSize ?? 8); i++) {
3417
+ const worker = this.options.workerFactory();
3418
+ const managedWorker = {
3419
+ worker,
3420
+ requestId: void 0,
3421
+ pendingSetupRequestId: void 0,
3422
+ initialized: false,
3423
+ langs: /* @__PURE__ */ new Set(["text", ...resolvedLanguages.map(({ name }) => name)]),
3424
+ customExtensionsVersion: 0
3425
+ };
3426
+ worker.addEventListener("message", (event) => {
3427
+ this.handleWorkerMessage(managedWorker, event.data);
3428
+ });
3429
+ worker.addEventListener("error", (error) => this.handleWorkerError(managedWorker, error));
3430
+ this.workers.push(managedWorker);
3431
+ initPromises.push(new Promise((resolve, reject) => {
3432
+ const id = this.generateRequestId();
3433
+ const task = {
3434
+ type: "initialize",
3435
+ id,
3436
+ request: {
3437
+ type: "initialize",
3438
+ id,
3439
+ renderOptions: this.renderOptions,
3440
+ preferredHighlighter: this.preferredHighlighter,
3441
+ resolvedThemes,
3442
+ resolvedLanguages,
3443
+ customExtensionsVersion: customExtensionMap != null ? customExtensionVersion : void 0,
3444
+ customExtensionMap
3445
+ },
3446
+ resolve() {
3447
+ managedWorker.initialized = true;
3448
+ resolve();
3449
+ },
3450
+ reject,
3451
+ requestStart: Date.now()
3452
+ };
3453
+ managedWorker.pendingSetupRequestId = id;
3454
+ this.activeTaskById.set(id, task);
3455
+ this.executeTask(managedWorker, task);
3456
+ }));
3457
+ }
3458
+ const timeoutMs = this.options.workerInitializationTimeout ?? DEFAULT_WORKER_INITIALIZATION_TIMEOUT;
3459
+ let timeoutId;
3460
+ try {
3461
+ await Promise.race([Promise.all(initPromises), new Promise((_, reject) => {
3462
+ timeoutId = setTimeout(() => {
3463
+ reject(/* @__PURE__ */ new Error(`WorkerPoolManager: worker initialization timed out after ${timeoutMs}ms`));
3464
+ }, timeoutMs);
3465
+ })]);
3466
+ } finally {
3467
+ if (timeoutId != null) clearTimeout(timeoutId);
3468
+ }
3469
+ }
3470
+ /**
3471
+ * Pass worker errors to onWorkerError, or log them if no callback is set.
3472
+ *
3473
+ * A startup error rejects initialization so components can highlight on the
3474
+ * main thread. Other requests wait for their own responses: worker.ts catches
3475
+ * request errors, so this event may be unrelated to the current request.
3476
+ * A worker that stops responding remains busy and receives no further work.
3477
+ */
3478
+ handleWorkerError(managedWorker, event) {
3479
+ const { onWorkerError } = this.options;
3480
+ if (onWorkerError != null) try {
3481
+ onWorkerError(event, managedWorker.worker);
3482
+ } catch (hookError) {
3483
+ console.error("WorkerPoolManager: onWorkerError threw:", hookError);
3484
+ }
3485
+ else console.error("Worker error:", event, managedWorker);
3486
+ const { pendingSetupRequestId } = managedWorker;
3487
+ if (pendingSetupRequestId == null) return;
3488
+ const task = this.activeTaskById.get(pendingSetupRequestId);
3489
+ if (task?.type !== "initialize") return;
3490
+ const error = errorFromWorkerErrorEvent(event);
3491
+ if (onWorkerError != null) markWorkerErrorReported(error);
3492
+ task.reject(error);
3493
+ this.cleanWorkerAndTask(managedWorker, task);
3494
+ }
3495
+ drainQueue = () => {
3496
+ this._queuedDrain = void 0;
3497
+ if (this.initialized !== true || this.queuedTasks.length === 0) return;
3498
+ for (let i = 0; i < this.queuedTasks.length; ) {
3499
+ const task = this.queuedTasks[i];
3500
+ if (this.hasActiveRequest(task)) {
3501
+ i++;
3502
+ continue;
3503
+ }
3504
+ const langs = getLangsFromTask(task);
3505
+ const availableWorker = this.getAvailableWorker(langs);
3506
+ if (availableWorker == null) break;
3507
+ this.queuedTasks.splice(i, 1);
3508
+ this.assignWorkerToTask(task, availableWorker);
3509
+ this.resolveLanguagesAndExecuteTask(availableWorker, task, langs);
3510
+ }
3511
+ this.queueBroadcastStateChanges();
3512
+ };
3513
+ highlightFileAST(instance, file) {
3514
+ const cachedResult = this.getFileResultCache(file);
3515
+ if (isFilePlainText(file) || cachedResult != null && areFileRenderOptionsEqual(cachedResult.options, this.getFileRenderOptions())) return;
3516
+ if (!this.hasMatchingFileInstanceTask(instance, file)) this.submitTask(instance, {
3517
+ type: "file",
3518
+ file
3519
+ });
3520
+ }
3521
+ primeFileHighlightCache(file) {
3522
+ if (!this.isWorkingPool()) return Promise.reject(/* @__PURE__ */ new Error("WorkerPoolManager.primeFileHighlightCache: worker pool is not working"));
3523
+ const task = this.getOrCreateFileHighlightCacheTask(file);
3524
+ return task != null ? this.createRenderTaskCallbacks(task) : Promise.resolve();
3525
+ }
3526
+ getOrCreateFileHighlightCacheTask(file) {
3527
+ if (file.cacheKey == null) {
3528
+ console.warn(`WorkerPoolManager.primeFileHighlightCache: priming highlight cache requires file.cacheKey; skipping "${file.name}".`);
3529
+ return;
3530
+ }
3531
+ const cachedResult = this.getFileResultCache(file);
3532
+ const highlightKey = this.getFileHighlightKey(file);
3533
+ if (highlightKey == null || isFilePlainText(file) || cachedResult != null && areFileRenderOptionsEqual(cachedResult.options, this.getFileRenderOptions())) return;
3534
+ const existingTask = this.getTaskByHighlightKey(highlightKey);
3535
+ if (existingTask != null) {
3536
+ existingTask.primeCache = true;
3537
+ return existingTask.type === "file" ? existingTask : void 0;
3538
+ } else {
3539
+ const task = this.submitCacheTask({
3540
+ type: "file",
3541
+ file
3542
+ }, highlightKey);
3543
+ return task.type === "file" ? task : void 0;
3544
+ }
3545
+ }
3546
+ getPlainFileAST(file, startingLine, totalLines, lines) {
3547
+ if (this.highlighter == null) {
3548
+ this.queueInitialization();
3549
+ return;
3550
+ }
3551
+ return renderFileWithHighlighter(file, this.highlighter, this.renderOptions, {
3552
+ forcePlainText: true,
3553
+ startingLine,
3554
+ totalLines,
3555
+ lines
3556
+ });
3557
+ }
3558
+ highlightDiffAST(instance, diff) {
3559
+ const cachedResult = this.getDiffResultCache(diff);
3560
+ if (isDiffPlainText(diff) || cachedResult != null && areDiffRenderOptionsEqual(cachedResult.options, this.getDiffRenderOptions())) return;
3561
+ if (!this.hasMatchingDiffInstanceTask(instance, diff)) this.submitTask(instance, {
3562
+ type: "diff",
3563
+ diff
3564
+ });
3565
+ }
3566
+ primeDiffHighlightCache(diff) {
3567
+ if (!this.isWorkingPool()) return Promise.reject(/* @__PURE__ */ new Error("WorkerPoolManager.primeDiffHighlightCache: worker pool is not working"));
3568
+ const task = this.getOrCreateDiffHighlightCacheTask(diff);
3569
+ return task != null ? this.createRenderTaskCallbacks(task) : Promise.resolve();
3570
+ }
3571
+ getOrCreateDiffHighlightCacheTask(diff) {
3572
+ if (diff.cacheKey == null) {
3573
+ console.warn(`WorkerPoolManager.primeDiffHighlightCache: priming highlight cache requires diff.cacheKey; skipping "${diff.prevName ?? diff.name}" -> "${diff.name}".`);
3574
+ return;
3575
+ }
3576
+ const cachedResult = this.getDiffResultCache(diff);
3577
+ const highlightKey = this.getDiffHighlightKey(diff);
3578
+ if (highlightKey == null || isDiffPlainText(diff) || cachedResult != null && areDiffRenderOptionsEqual(cachedResult.options, this.getDiffRenderOptions())) return;
3579
+ const existingTask = this.getTaskByHighlightKey(highlightKey);
3580
+ if (existingTask != null) {
3581
+ existingTask.primeCache = true;
3582
+ return existingTask.type === "diff" ? existingTask : void 0;
3583
+ } else {
3584
+ const task = this.submitCacheTask({
3585
+ type: "diff",
3586
+ diff
3587
+ }, highlightKey);
3588
+ return task.type === "diff" ? task : void 0;
3589
+ }
3590
+ }
3591
+ getPlainDiffAST(diff, startingLine, totalLines, expandedHunks, collapsedContextThreshold) {
3592
+ return this.highlighter != null ? renderDiffWithHighlighter(diff, this.highlighter, this.renderOptions, {
3593
+ forcePlainText: true,
3594
+ startingLine,
3595
+ totalLines,
3596
+ expandedHunks,
3597
+ collapsedContextThreshold
3598
+ }) : void 0;
3599
+ }
3600
+ terminate() {
3601
+ this.lifecycleGeneration++;
3602
+ this.cancelActiveWorkerTasks();
3603
+ this.terminateWorkers();
3604
+ const error = new WorkerPoolTerminatedError();
3605
+ for (const task of this.queuedTasks) this.rejectRenderTaskCallbacks(task, error);
3606
+ this.fileCache.clear();
3607
+ this.diffCache.clear();
3608
+ this.activeRequestByInstance.clear();
3609
+ this.queuedTasks.length = 0;
3610
+ this.queuedTaskByInstance.clear();
3611
+ this.taskByHighlightKey.clear();
3612
+ this.activeTaskById.clear();
3613
+ this.highlighter = void 0;
3614
+ this.initialized = false;
3615
+ this.workersFailed = false;
3616
+ this.queueBroadcastStateChanges();
3617
+ }
3618
+ isCurrentLifecycle(lifecycleGeneration) {
3619
+ return this.lifecycleGeneration === lifecycleGeneration;
3620
+ }
3621
+ queueInitialization(languages) {
3622
+ this.initialize(languages).catch((error) => {
3623
+ if (isHandledWorkerPoolError(error)) return;
3624
+ console.error(error);
3625
+ });
3626
+ }
3627
+ cancelActiveWorkerTasks() {
3628
+ const error = new WorkerPoolTerminatedError();
3629
+ for (const task of this.activeTaskById.values()) if ("reject" in task) task.reject(error);
3630
+ else if (isRenderTask(task)) this.rejectRenderTaskCallbacks(task, error);
3631
+ }
3632
+ terminateWorkers() {
3633
+ for (const managedWorker of this.workers) managedWorker.worker.terminate();
3634
+ this.workers.length = 0;
3635
+ }
3636
+ getStats() {
3637
+ return {
3638
+ managerState: (() => {
3639
+ if (this.initialized === false) return "waiting";
3640
+ if (this.initialized !== true) return "initializing";
3641
+ return "initialized";
3642
+ })(),
3643
+ totalWorkers: this.workers.length,
3644
+ workersFailed: this.workersFailed,
3645
+ busyWorkers: this.workers.filter((w) => w.requestId != null || w.pendingSetupRequestId != null).length,
3646
+ queuedTasks: this.queuedTasks.length,
3647
+ activeTasks: this.activeTaskById.size,
3648
+ themeSubscribers: this.themeSubscribers.size,
3649
+ fileCacheSize: this.fileCache.size,
3650
+ diffCacheSize: this.diffCache.size
3651
+ };
3652
+ }
3653
+ submitTask(instance, request) {
3654
+ if (this.initialized === false) this.queueInitialization();
3655
+ const highlightKey = this.getHighlightKeyForRequest(request);
3656
+ const existingTask = highlightKey != null ? this.getTaskByHighlightKey(highlightKey) : void 0;
3657
+ if (existingTask != null) {
3658
+ this.detachInstanceFromQueuedTasks(instance, existingTask);
3659
+ this.addInstanceToTask(existingTask, instance);
3660
+ this.queueBroadcastStateChanges();
3661
+ return;
3662
+ }
3663
+ this.detachInstanceFromQueuedTasks(instance);
3664
+ const id = this.generateRequestId();
3665
+ const requestStart = Date.now();
3666
+ const { renderOptionsVersion } = this;
3667
+ const task = (() => {
3668
+ switch (request.type) {
3669
+ case "file":
3670
+ return {
3671
+ type: "file",
3672
+ id,
3673
+ request: {
3674
+ ...request,
3675
+ id
3676
+ },
3677
+ instances: /* @__PURE__ */ new Set([instance]),
3678
+ primeCache: false,
3679
+ highlightKey,
3680
+ callbacks: /* @__PURE__ */ new Set(),
3681
+ renderOptionsVersion,
3682
+ requestStart
3683
+ };
3684
+ case "diff":
3685
+ return {
3686
+ type: "diff",
3687
+ id,
3688
+ request: {
3689
+ ...request,
3690
+ id
3691
+ },
3692
+ instances: /* @__PURE__ */ new Set([instance]),
3693
+ primeCache: false,
3694
+ highlightKey,
3695
+ callbacks: /* @__PURE__ */ new Set(),
3696
+ renderOptionsVersion,
3697
+ requestStart
3698
+ };
3699
+ }
3700
+ })();
3701
+ this.enqueueRenderTask(task, instance);
3702
+ }
3703
+ submitCacheTask(request, highlightKey) {
3704
+ if (this.initialized === false) this.queueInitialization();
3705
+ const id = this.generateRequestId();
3706
+ const requestStart = Date.now();
3707
+ const { renderOptionsVersion } = this;
3708
+ const task = (() => {
3709
+ switch (request.type) {
3710
+ case "file":
3711
+ return {
3712
+ type: "file",
3713
+ id,
3714
+ request: {
3715
+ ...request,
3716
+ id
3717
+ },
3718
+ instances: /* @__PURE__ */ new Set(),
3719
+ primeCache: true,
3720
+ highlightKey,
3721
+ callbacks: /* @__PURE__ */ new Set(),
3722
+ renderOptionsVersion,
3723
+ requestStart
3724
+ };
3725
+ case "diff":
3726
+ return {
3727
+ type: "diff",
3728
+ id,
3729
+ request: {
3730
+ ...request,
3731
+ id
3732
+ },
3733
+ instances: /* @__PURE__ */ new Set(),
3734
+ primeCache: true,
3735
+ highlightKey,
3736
+ callbacks: /* @__PURE__ */ new Set(),
3737
+ renderOptionsVersion,
3738
+ requestStart
3739
+ };
3740
+ }
3741
+ })();
3742
+ this.enqueueRenderTask(task);
3743
+ return task;
3744
+ }
3745
+ enqueueRenderTask(task, instance) {
3746
+ this.queuedTasks.push(task);
3747
+ if (instance != null) this.queuedTaskByInstance.set(instance, task);
3748
+ if (task.highlightKey != null) this.taskByHighlightKey.set(task.highlightKey, task);
3749
+ this.queueDrain();
3750
+ }
3751
+ async resolveLanguagesAndExecuteTask(availableWorker, task, langs) {
3752
+ try {
3753
+ const mainThreadLangs = langs.filter((lang) => !areLanguagesAttached(lang));
3754
+ if (mainThreadLangs.length > 0) getSharedHighlighter({
3755
+ themes: getThemes(this.renderOptions.theme),
3756
+ langs: ["text", ...mainThreadLangs],
3757
+ preferredHighlighter: this.preferredHighlighter
3758
+ }).catch((error) => {
3759
+ console.error(error);
3760
+ });
3761
+ const workerMissingLangs = langs.filter((lang) => !availableWorker.langs.has(lang));
3762
+ if (workerMissingLangs.length > 0) {
3763
+ if (hasResolvedLanguages(workerMissingLangs)) task.request.resolvedLanguages = getResolvedLanguages(workerMissingLangs);
3764
+ else task.request.resolvedLanguages = await resolveLanguages(workerMissingLangs);
3765
+ }
3766
+ if (!this.activeTaskById.has(task.id)) {
3767
+ if (availableWorker.requestId === task.id) {
3768
+ this.cleanWorkerAndTask(availableWorker, task);
3769
+ this.queueBroadcastStateChanges();
3770
+ if (this.queuedTasks.length > 0) this.queueDrain();
3771
+ }
3772
+ return;
3773
+ }
3774
+ this.executeTask(availableWorker, task);
3775
+ } catch (error) {
3776
+ this.rejectRenderTaskCallbacks(task, normalizeWorkerError(error));
3777
+ this.cleanWorkerAndTask(availableWorker, task);
3778
+ this.queueBroadcastStateChanges();
3779
+ if (this.queuedTasks.length > 0) this.queueDrain();
3780
+ }
3781
+ }
3782
+ handleWorkerMessage(managedWorker, response) {
3783
+ const task = this.activeTaskById.get(response.id);
3784
+ try {
3785
+ if (task == null) throw IGNORE_RESPONSE;
3786
+ else if (response.type === "error") {
3787
+ const error = new Error(response.error);
3788
+ if (response.stack) error.stack = response.stack;
3789
+ if ("reject" in task) task.reject(error);
3790
+ else if (isRenderTask(task)) {
3791
+ this.notifyHighlightError(task, error);
3792
+ this.rejectRenderTaskCallbacks(task, error);
3793
+ } else throw new Error("handleWorkerMessage: unknown task type");
3794
+ throw error;
3795
+ } else {
3796
+ if (isRenderTask(task)) for (const { name } of task.request.resolvedLanguages ?? []) managedWorker.langs.add(name);
3797
+ switch (response.requestType) {
3798
+ case "initialize":
3799
+ if (task.type !== "initialize") throw new Error("handleWorkerMessage: task/response dont match");
3800
+ this.syncCustomExtensionVersion(managedWorker, task.request);
3801
+ task.resolve();
3802
+ break;
3803
+ case "set-render-options":
3804
+ if (task.type !== "set-render-options") throw new Error("handleWorkerMessage: task/response dont match");
3805
+ task.resolve();
3806
+ break;
3807
+ case "file": {
3808
+ if (task.type !== "file") throw new Error("handleWorkerMessage: task/response dont match");
3809
+ const { result, options } = response;
3810
+ if (!this.isCurrentRenderTask(task) || !areFileRenderOptionsEqual(options, this.getFileRenderOptions())) throw IGNORE_RESPONSE;
3811
+ const { request } = task;
3812
+ this.syncCustomExtensionVersion(managedWorker, request);
3813
+ if (task.cacheKeyAtDispatch != null) this.fileCache.set(task.cacheKeyAtDispatch, {
3814
+ result,
3815
+ options
3816
+ });
3817
+ this.resolveRenderTaskCallbacks(task);
3818
+ this.notifyFileInstances(task, result, options);
3819
+ break;
3820
+ }
3821
+ case "diff": {
3822
+ if (task.type !== "diff") throw new Error("handleWorkerMessage: task/response dont match");
3823
+ const { result, options } = response;
3824
+ if (!this.isCurrentRenderTask(task) || !areDiffRenderOptionsEqual(options, this.getDiffRenderOptions())) throw IGNORE_RESPONSE;
3825
+ const { request } = task;
3826
+ this.syncCustomExtensionVersion(managedWorker, request);
3827
+ if (task.cacheKeyAtDispatch != null) this.diffCache.set(task.cacheKeyAtDispatch, {
3828
+ result,
3829
+ options
3830
+ });
3831
+ this.resolveRenderTaskCallbacks(task);
3832
+ this.notifyDiffInstances(task, result, options);
3833
+ break;
3834
+ }
3835
+ }
3836
+ }
3837
+ } catch (error) {
3838
+ if (error !== IGNORE_RESPONSE) console.error(error, task, response);
3839
+ }
3840
+ this.cleanWorkerAndTask(managedWorker, task, response.id);
3841
+ this.queueBroadcastStateChanges();
3842
+ if (this.queuedTasks.length > 0) this.queueDrain();
3843
+ }
3844
+ _queuedDrain;
3845
+ queueDrain() {
3846
+ if (this._queuedDrain != null) return;
3847
+ this._queuedDrain = Promise.resolve().then(this.drainQueue);
3848
+ this.queueBroadcastStateChanges();
3849
+ }
3850
+ assignWorkerToTask(task, managedWorker) {
3851
+ managedWorker.requestId = task.id;
3852
+ if (isRenderTask(task)) {
3853
+ this.clearQueuedInstanceRequests(task);
3854
+ this.trackInstanceRequests(task);
3855
+ }
3856
+ this.activeTaskById.set(task.id, task);
3857
+ }
3858
+ cleanWorkerAndTask(managedWorker, task, requestId = task?.id) {
3859
+ if (managedWorker.requestId === requestId) managedWorker.requestId = void 0;
3860
+ if (managedWorker.pendingSetupRequestId === requestId) managedWorker.pendingSetupRequestId = void 0;
3861
+ if (task != null) {
3862
+ if (isRenderTask(task)) {
3863
+ this.rejectRenderTaskCallbacks(task, new WorkerPoolTaskCanceledError());
3864
+ this.clearInstanceRequests(task);
3865
+ this.clearHighlightKey(task);
3866
+ }
3867
+ this.activeTaskById.delete(task.id);
3868
+ }
3869
+ }
3870
+ executeTask(managedWorker, task) {
3871
+ if (shouldSyncCustomExtensions(task.request)) this.maybeAttachCustomExtensions(managedWorker, task.request);
3872
+ if (!this.activeTaskById.has(task.id)) this.assignWorkerToTask(task, managedWorker);
3873
+ try {
3874
+ if (task.type === "file") task.cacheKeyAtDispatch = task.request.file.cacheKey;
3875
+ else if (task.type === "diff") task.cacheKeyAtDispatch = task.request.diff.cacheKey;
3876
+ managedWorker.worker.postMessage(task.request);
3877
+ } catch (error) {
3878
+ console.error("Failed to post message to worker:", error);
3879
+ if (isRenderTask(task)) {
3880
+ this.notifyHighlightError(task, error);
3881
+ this.rejectRenderTaskCallbacks(task, normalizeWorkerError(error));
3882
+ } else if ("reject" in task) task.reject(error);
3883
+ this.cleanWorkerAndTask(managedWorker, task);
3884
+ if (this.queuedTasks.length > 0) this.queueDrain();
3885
+ }
3886
+ this.queueBroadcastStateChanges();
3887
+ }
3888
+ maybeAttachCustomExtensions(managedWorker, request) {
3889
+ if (request.customExtensionsVersion != null) return;
3890
+ const version = getCustomExtensionsVersion();
3891
+ if (managedWorker.customExtensionsVersion >= version) return;
3892
+ request.customExtensionsVersion = version;
3893
+ request.customExtensionMap = getCustomExtensionsMap();
3894
+ }
3895
+ syncCustomExtensionVersion(managedWorker, request) {
3896
+ if (request.customExtensionsVersion == null) return;
3897
+ managedWorker.customExtensionsVersion = request.customExtensionsVersion;
3898
+ }
3899
+ getAvailableWorker(langs) {
3900
+ let worker;
3901
+ for (const managedWorker of this.workers) {
3902
+ if (managedWorker.requestId != null || managedWorker.pendingSetupRequestId != null || !managedWorker.initialized) continue;
3903
+ worker = managedWorker;
3904
+ if (langs.length === 0) break;
3905
+ let hasEveryLang = true;
3906
+ for (const lang of langs) if (!managedWorker.langs.has(lang)) {
3907
+ hasEveryLang = false;
3908
+ break;
3909
+ }
3910
+ if (hasEveryLang) break;
3911
+ }
3912
+ return worker;
3913
+ }
3914
+ getFileHighlightKey(file) {
3915
+ if (file.cacheKey == null) return;
3916
+ return `file:${file.cacheKey}:${this.renderOptionsVersion}`;
3917
+ }
3918
+ getDiffHighlightKey(diff) {
3919
+ if (diff.cacheKey == null) return;
3920
+ return `diff:${diff.cacheKey}:${this.renderOptionsVersion}`;
3921
+ }
3922
+ getHighlightKeyForRequest(request) {
3923
+ switch (request.type) {
3924
+ case "file":
3925
+ return this.getFileHighlightKey(request.file);
3926
+ case "diff":
3927
+ return this.getDiffHighlightKey(request.diff);
3928
+ }
3929
+ }
3930
+ hasActiveRequest(task) {
3931
+ for (const instance of getInstances(task)) if (this.activeRequestByInstance.has(instance)) return true;
3932
+ return false;
3933
+ }
3934
+ addInstanceToTask(task, instance) {
3935
+ if (task.type === "file") task.instances.add(instance);
3936
+ else task.instances.add(instance);
3937
+ if (this.activeTaskById.has(task.id)) this.activeRequestByInstance.set(instance, task.id);
3938
+ else this.queuedTaskByInstance.set(instance, task);
3939
+ }
3940
+ detachInstanceFromQueuedTasks(instance, exceptTask) {
3941
+ const task = this.queuedTaskByInstance.get(instance);
3942
+ if (task == null || task === exceptTask) return;
3943
+ this.queuedTaskByInstance.delete(instance);
3944
+ this.detachInstanceFromRenderTask(task, instance);
3945
+ if (!task.primeCache && task.instances.size === 0) this.removeQueuedTask(task);
3946
+ }
3947
+ detachInstanceFromRenderTask(task, instance) {
3948
+ if (task.type === "file") task.instances.delete(instance);
3949
+ else task.instances.delete(instance);
3950
+ }
3951
+ removeQueuedTask(task) {
3952
+ const index = this.queuedTasks.indexOf(task);
3953
+ if (index !== -1) this.queuedTasks.splice(index, 1);
3954
+ this.rejectRenderTaskCallbacks(task, new WorkerPoolTaskCanceledError());
3955
+ this.clearQueuedInstanceRequests(task);
3956
+ this.clearHighlightKey(task);
3957
+ }
3958
+ removeActiveTask(task) {
3959
+ this.rejectRenderTaskCallbacks(task, new WorkerPoolTaskCanceledError());
3960
+ this.clearInstanceRequests(task);
3961
+ this.clearHighlightKey(task);
3962
+ this.activeTaskById.delete(task.id);
3963
+ }
3964
+ createRenderTaskCallbacks(task) {
3965
+ return new Promise((resolve, reject) => {
3966
+ task.callbacks.add({
3967
+ resolve,
3968
+ reject
3969
+ });
3970
+ });
3971
+ }
3972
+ resolveRenderTaskCallbacks(task) {
3973
+ for (const callbacks of task.callbacks) callbacks.resolve();
3974
+ task.callbacks.clear();
3975
+ }
3976
+ rejectRenderTaskCallbacks(task, error) {
3977
+ for (const callbacks of task.callbacks) callbacks.reject(error);
3978
+ task.callbacks.clear();
3979
+ }
3980
+ invalidateRenderTasks() {
3981
+ for (let index = this.queuedTasks.length - 1; index >= 0; index--) {
3982
+ const task = this.queuedTasks[index];
3983
+ if (task.renderOptionsVersion !== this.renderOptionsVersion) this.removeQueuedTask(task);
3984
+ }
3985
+ for (const task of Array.from(this.activeTaskById.values())) if (isRenderTask(task) && task.renderOptionsVersion !== this.renderOptionsVersion) this.removeActiveTask(task);
3986
+ }
3987
+ clearQueuedInstanceRequests(task) {
3988
+ for (const instance of getInstances(task)) if (this.queuedTaskByInstance.get(instance) === task) this.queuedTaskByInstance.delete(instance);
3989
+ }
3990
+ clearHighlightKey(task) {
3991
+ if (task.highlightKey != null && this.taskByHighlightKey.get(task.highlightKey) === task) this.taskByHighlightKey.delete(task.highlightKey);
3992
+ }
3993
+ trackInstanceRequests(task) {
3994
+ for (const instance of getInstances(task)) this.activeRequestByInstance.set(instance, task.id);
3995
+ }
3996
+ clearInstanceRequests(task) {
3997
+ for (const instance of getInstances(task)) if (this.activeRequestByInstance.get(instance) === task.id) this.activeRequestByInstance.delete(instance);
3998
+ }
3999
+ notifyFileInstances(task, result, options) {
4000
+ for (const instance of task.instances) if (this.activeRequestByInstance.get(instance) === task.id) instance.onHighlightSuccess(task.request.file, result, options);
4001
+ }
4002
+ notifyDiffInstances(task, result, options) {
4003
+ for (const instance of task.instances) if (this.activeRequestByInstance.get(instance) === task.id) instance.onHighlightSuccess(task.request.diff, result, options);
4004
+ }
4005
+ notifyHighlightError(task, error) {
4006
+ for (const instance of getInstances(task)) if (this.activeRequestByInstance.get(instance) === task.id) instance.onHighlightError(error);
4007
+ }
4008
+ hasMatchingFileInstanceTask(instance, file) {
4009
+ for (const task of this.iterateRenderTasks()) if (task.type === "file" && this.isCurrentRenderTask(task) && task.instances.has(instance) && areFilesEqual(file, task.request.file)) return true;
4010
+ return false;
4011
+ }
4012
+ hasMatchingDiffInstanceTask(instance, diff) {
4013
+ for (const task of this.iterateRenderTasks()) if (task.type === "diff" && this.isCurrentRenderTask(task) && task.instances.has(instance) && areDiffTargetsEqual(task.request.diff, diff)) return true;
4014
+ return false;
4015
+ }
4016
+ getTaskByHighlightKey(highlightKey) {
4017
+ const task = this.taskByHighlightKey.get(highlightKey);
4018
+ return task != null && this.isCurrentRenderTask(task) ? task : void 0;
4019
+ }
4020
+ isCurrentRenderTask(task) {
4021
+ return task.renderOptionsVersion === this.renderOptionsVersion;
4022
+ }
4023
+ *iterateRenderTasks() {
4024
+ for (const task of this.queuedTasks) yield task;
4025
+ for (const task of this.activeTaskById.values()) if (isRenderTask(task)) yield task;
4026
+ }
4027
+ generateRequestId() {
4028
+ return `req_${++this.nextRequestId}`;
4029
+ }
4030
+ };
4031
+ function shouldSyncCustomExtensions(request) {
4032
+ return request.type === "initialize" || request.type === "file" || request.type === "diff";
4033
+ }
4034
+ function getLangsFromTask(task) {
4035
+ const langs = /* @__PURE__ */ new Set();
4036
+ if (task.type === "initialize" || task.type === "set-render-options") return [];
4037
+ switch (task.type) {
4038
+ case "file":
4039
+ langs.add(task.request.file.lang ?? getFiletypeFromFileName(task.request.file.name));
4040
+ break;
4041
+ case "diff":
4042
+ langs.add(task.request.diff.lang ?? getFiletypeFromFileName(task.request.diff.name));
4043
+ langs.add(task.request.diff.lang ?? getFiletypeFromFileName(task.request.diff.prevName ?? "-"));
4044
+ }
4045
+ langs.delete("text");
4046
+ return Array.from(langs);
4047
+ }
4048
+ function isRenderTask(task) {
4049
+ return task?.type === "file" || task?.type === "diff";
4050
+ }
4051
+ function getInstances(task) {
4052
+ return task.instances;
4053
+ }
4054
+ function normalizeWorkerError(error) {
4055
+ if (error instanceof Error) return error;
4056
+ if (error != null && typeof error === "object") {
4057
+ if ("error" in error && error.error instanceof Error) return error.error;
4058
+ if ("message" in error && typeof error.message === "string") return new Error(error.message);
4059
+ }
4060
+ return new Error(String(error));
4061
+ }
4062
+ function errorFromWorkerErrorEvent(event) {
4063
+ const cause = "error" in event ? event.error : void 0;
4064
+ const message = "message" in event && typeof event.message === "string" && event.message !== "" ? event.message : cause instanceof Error ? cause.message : "the worker script failed to load (the error event carries no message)";
4065
+ return new WorkerPoolWorkerError(`WorkerPoolManager: worker failed: ${message}`, cause instanceof Error ? { cause } : void 0);
4066
+ }
4067
+ let workerPoolSingleton;
4068
+ function getOrCreateWorkerPoolSingleton({ poolOptions, highlighterOptions }) {
4069
+ workerPoolSingleton ??= new WorkerPoolManager(poolOptions, highlighterOptions);
4070
+ return workerPoolSingleton;
4071
+ }
4072
+ function terminateWorkerPoolSingleton() {
4073
+ if (workerPoolSingleton == null) return;
4074
+ workerPoolSingleton.terminate();
4075
+ workerPoolSingleton = void 0;
4076
+ }
4077
+ const WorkerPoolContext = reactExports.createContext(void 0);
4078
+ let instanceCount = 0;
4079
+ function WorkerPoolContextProvider({ children, poolOptions, highlighterOptions }) {
4080
+ const [poolManager] = reactExports.useState(() => {
4081
+ if (typeof window === "undefined") return;
4082
+ return getOrCreateWorkerPoolSingleton({
4083
+ poolOptions,
4084
+ highlighterOptions
4085
+ });
4086
+ });
4087
+ reactExports.useInsertionEffect(() => {
4088
+ if (poolManager != null) {
4089
+ instanceCount++;
4090
+ return () => {
4091
+ instanceCount--;
4092
+ };
4093
+ }
4094
+ }, [poolManager]);
4095
+ reactExports.useEffect(() => {
4096
+ return () => {
4097
+ if (instanceCount === 0) terminateWorkerPoolSingleton();
4098
+ };
4099
+ }, []);
4100
+ return /* @__PURE__ */ jsxRuntimeExports.jsx(WorkerPoolContext.Provider, {
4101
+ value: poolManager,
4102
+ children
4103
+ });
4104
+ }
4105
+ function useWorkerPool() {
4106
+ return reactExports.useContext(WorkerPoolContext);
4107
+ }
4108
+ const DIFFS_HOST_STYLE = {
4109
+ "--diffs-bg-context-override": "var(--zg-bg)",
4110
+ "--diffs-bg-context-gutter-override": "var(--zg-bg)",
4111
+ "--diffs-bg-separator-override": "var(--zg-tray)",
4112
+ "--diffs-bg-buffer-override": "var(--zg-bg)",
4113
+ "--diffs-bg-hover-override": "var(--zg-row-hover)",
4114
+ "--diffs-bg-addition-override": "var(--zg-diff-add-bg)",
4115
+ "--diffs-bg-addition-emphasis-override": "var(--zg-diff-add-content-bg)",
4116
+ "--diffs-bg-addition-number-override": "var(--zg-diff-add-bg)",
4117
+ "--diffs-bg-deletion-override": "var(--zg-diff-remove-bg)",
4118
+ "--diffs-bg-deletion-emphasis-override": "var(--zg-diff-remove-content-bg)",
4119
+ "--diffs-bg-deletion-number-override": "var(--zg-diff-remove-bg)",
4120
+ "--diffs-fg-number-override": "var(--zg-text-subtle)",
4121
+ // Editor selection colour (pierre reads the shiki theme's editor.selectionBackground, often unset).
4122
+ "--diffs-editor-selection-bg": "color-mix(in srgb, var(--zg-accent) 28%, transparent)",
4123
+ "--diffs-fg-number-addition-override": "var(--zg-diff-add-fg)",
4124
+ "--diffs-fg-number-deletion-override": "var(--zg-diff-remove-fg)",
4125
+ "--diffs-bg-selection-override": "var(--zg-accent-soft)",
4126
+ "--diffs-bg-selection-number-override": "var(--zg-accent-soft-strong)",
4127
+ "--diffs-annotation-bg": "var(--zg-tray)",
4128
+ "--diffs-font-family": "var(--zg-font-mono)",
4129
+ "--diffs-header-font-family": "var(--zg-font-ui)",
4130
+ "--diffs-font-size": "var(--zg-font-size-code)",
4131
+ "--diffs-line-height": "calc(var(--zg-font-size-code) * 1.65)"
4132
+ };
4133
+ const PREFERRED_HIGHLIGHTER = "shiki-wasm";
4134
+ const VIRTUALIZER_CONFIG = { overscrollSize: 600, intersectionObserverMargin: 1200 };
4135
+ const DIFFS_UNSAFE_CSS = `
4136
+ /* One hover surface: findings ride in our HoverCard; keep pierre's squiggles, drop its popover. */
4137
+ [data-marker-popover] { display: none !important; }
4138
+ [data-diffs-header] {
4139
+ min-height: 32px;
4140
+ padding-inline: 10px 12px;
4141
+ font-size: var(--zg-font-size-label);
4142
+ border-bottom: 1px solid var(--zg-hairline);
4143
+ background: var(--zg-tray);
4144
+ }
4145
+ [data-separator] { color: var(--zg-text-subtle); }
4146
+ [data-line]:hover { box-shadow: inset 3px 0 var(--zg-border-strong); }
4147
+ [data-selected-line] { box-shadow: inset 3px 0 var(--zg-accent); }
4148
+ [data-column-number] { cursor: pointer; user-select: none; }
4149
+ [data-line] { cursor: text; }
4150
+ /* Text selection. Read-only: the native highlight (pierre's default is an
4151
+ 8% mix, invisible on our surface). Editor: pierre paints selection ranges
4152
+ under the line background at z-index -10; our opaque line background hid
4153
+ them, so lift them above the background and under the text. */
4154
+ ::selection { background-color: color-mix(in srgb, var(--zg-accent) 32%, transparent) !important; }
4155
+ [data-selection-range] {
4156
+ z-index: 1 !important;
4157
+ mix-blend-mode: screen;
4158
+ background-color: color-mix(in srgb, var(--zg-accent) 28%, transparent) !important;
4159
+ }
4160
+ /* Gutter "+" (comment on hover / on the selection end): lives in its own
4161
+ lane at the left of the gutter, so it neither covers the line number
4162
+ (which stays clickable for selection) nor the first characters. */
4163
+ [data-column-number] { padding-left: calc(1lh + 6px); }
4164
+ [data-gutter-utility-slot] {
4165
+ justify-content: flex-start;
4166
+ left: 3px;
4167
+ right: auto;
4168
+ }
4169
+ [data-utility-button] {
4170
+ margin-right: 0;
4171
+ width: calc(1lh - 2px);
4172
+ height: calc(1lh - 2px);
4173
+ background-color: var(--zg-accent-fill);
4174
+ color: var(--zg-accent-fill-fg);
4175
+ border-radius: var(--zg-radius-xs);
4176
+ box-shadow: 0 1px 2px rgb(0 0 0 / 0.25);
4177
+ }
4178
+ [data-utility-button]:hover { background-color: var(--zg-accent-fill-hover); }
4179
+ /* Cmd-hover over a symbol with a language server: link affordance on
4180
+ the symbol as the server delimits it, an identifier or a whole import
4181
+ path (a CSS custom highlight, see FileView LINK_HIGHLIGHT). */
4182
+ ::highlight(zg-link) { text-decoration: underline; text-decoration-color: var(--zg-accent); }
4183
+ /* Find (code/find): every match, and the current one stronger. Same tones as the transcript's find. */
4184
+ ::highlight(zg-find) { background-color: color-mix(in srgb, var(--zg-accent) 30%, transparent); }
4185
+ ::highlight(zg-find-current) { background-color: color-mix(in srgb, var(--zg-accent) 65%, transparent); }
4186
+ :host-context([data-zg-linking]) [data-char] { cursor: pointer; }
4187
+ /* A body that mounts before its tokens is held back, then eases in once
4188
+ they land (code/reveal.ts), so it never shows plain and re-colors; one
4189
+ that mounts highlighted shows at once, and a tab coming back from hidden
4190
+ replays nothing. Opacity only: pierre owns the geometry. The fade motion
4191
+ (its vars inherit into the shadow root): brief under reduced motion,
4192
+ instant with motion off. */
4193
+ :host([data-zg-held]) :is([data-diff], [data-file]) { transition: opacity var(--zg-motion-fade); }
4194
+ :host([data-zg-pending]) :is([data-diff], [data-file]) { opacity: 0; }
4195
+ /* A column that scrolls sideways takes focus (code/scroll-reach.ts): the kit's ring, inside it. */
4196
+ code[data-code][tabindex]:focus-visible { outline: 2px solid var(--zg-ring); outline-offset: -2px; }
4197
+ `;
4198
+ const TREES_HOST_STYLE = {
4199
+ // A real colour, not transparent: the tree's truncation fade markers paint
4200
+ // this over long names, so it must match the surface the tree sits on (the
4201
+ // side panel's tray, SidePanel.tsx).
4202
+ "--trees-bg-override": "var(--zg-tray)",
4203
+ "--trees-bg-muted-override": "var(--zg-row-hover)",
4204
+ "--trees-fg-override": "var(--zg-text)",
4205
+ "--trees-fg-muted-override": "var(--zg-text-muted)",
4206
+ "--trees-selected-bg-override": "var(--zg-row-active)",
4207
+ "--trees-selected-fg-override": "var(--zg-text)",
4208
+ "--trees-selected-focused-border-color-override": "var(--zg-accent)",
4209
+ "--trees-border-color-override": "var(--zg-hairline)",
4210
+ "--trees-border-radius-override": "var(--zg-radius-sm)",
4211
+ "--trees-accent-override": "var(--zg-accent)",
4212
+ "--trees-indent-guide-bg-override": "var(--zg-hairline)",
4213
+ "--trees-font-family-override": "var(--zg-font-ui)",
4214
+ "--trees-font-size-override": "12px",
4215
+ "--trees-scrollbar-thumb-override": "var(--zg-border-strong)",
4216
+ "--trees-git-added-color-override": "var(--zg-success)",
4217
+ "--trees-git-modified-color-override": "var(--zg-warn)",
4218
+ "--trees-git-deleted-color-override": "var(--zg-danger)",
4219
+ "--trees-git-renamed-color-override": "var(--zg-info)",
4220
+ "--trees-git-untracked-color-override": "var(--zg-success)",
4221
+ "--trees-git-ignored-color-override": "var(--zg-text-subtle)"
4222
+ };
4223
+ const TREES_UNSAFE_CSS = `
4224
+ button[data-type='item'] { border-radius: var(--zg-radius-sm); }
4225
+ /* Middle-truncation markers: no fill, just the fade. */
4226
+ [data-truncate-marker] { --truncate-marker-background-overlay-color: transparent; }
4227
+ `;
4228
+ export {
4229
+ COMMIT_METADATA_SPLIT as $,
4230
+ areThemesEqual as A,
4231
+ isHandledWorkerPoolError as B,
4232
+ CUSTOM_HEADER_SLOT_ID as C,
4233
+ DEFAULT_THEMES as D,
4234
+ EMPTY_RENDER_RANGE as E,
4235
+ HEADER_FILENAME_SUFFIX_SLOT_ID as F,
4236
+ HEADER_METADATA_SLOT_ID as G,
4237
+ HEADER_PREFIX_SLOT_ID as H,
4238
+ DEFAULT_VIRTUAL_FILE_METRICS as I,
4239
+ computeVirtualFileMetrics as J,
4240
+ getVirtualFileHeaderHeight as K,
4241
+ getVirtualFileHeaderRegion as L,
4242
+ getVirtualFilePaddingBottom as M,
4243
+ WorkerPoolContext as N,
4244
+ DIFFS_TAG_NAME as O,
4245
+ PREFERRED_HIGHLIGHTER as P,
4246
+ computeLineOffsets as Q,
4247
+ countLineBreaks as R,
4248
+ LRUMapPkg as S,
4249
+ DIFFS_UNSAFE_CSS as T,
4250
+ DIFFS_HOST_STYLE as U,
4251
+ VIRTUALIZER_CONFIG as V,
4252
+ WorkerPoolContextProvider as W,
4253
+ DEFAULT_TOKENIZE_MAX_LENGTH as X,
4254
+ SPLIT_WITH_NEWLINES as Y,
4255
+ getHunkSideStartBoundary as Z,
4256
+ getHunkSideEndBoundary as _,
4257
+ isDarkSurface as a,
4258
+ GIT_DIFF_FILE_BREAK_REGEX as a0,
4259
+ FILENAME_HEADER_REGEX as a1,
4260
+ INDEX_LINE_METADATA as a2,
4261
+ cleanLastNewline as a3,
4262
+ Diff as a4,
4263
+ createTextNodeElement as a5,
4264
+ createIconElement as a6,
4265
+ hasTrailingContextMismatch as a7,
4266
+ getExpandedRegion as a8,
4267
+ getTrailingExpandedRegion as a9,
4268
+ areDiffTargetsEqual as aa,
4269
+ areDiffRenderOptionsEqual as ab,
4270
+ isDiffPlainText as ac,
4271
+ DEFAULT_EXPANDED_REGION as ad,
4272
+ renderDiffWithHighlighter as ae,
4273
+ iterateOverDiff as af,
4274
+ getTrailingContextRangeSize as ag,
4275
+ isAdditionLineRenderable as ah,
4276
+ getNearestRenderableAdditionLine as ai,
4277
+ getHunkAdditionLineRange as aj,
4278
+ areFilesEqual as ak,
4279
+ getLeadingHunkSeparatorLayout as al,
4280
+ getTrailingHunkSeparatorLayout as am,
4281
+ UNSAFE_CSS_ATTRIBUTE as an,
4282
+ DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE as ao,
4283
+ DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY as ap,
4284
+ THEME_CSS_ATTRIBUTE as aq,
4285
+ TREES_HOST_STYLE as ar,
4286
+ TREES_UNSAFE_CSS as as,
4287
+ compositeOverBg as b,
4288
+ contrastRatio as c,
4289
+ deriveMutedFg as d,
4290
+ areThemesAttached as e,
4291
+ areFileRenderOptionsEqual as f,
4292
+ getHighlighterIfLoaded as g,
4293
+ hoverWouldEraseText as h,
4294
+ isFullyTransparent as i,
4295
+ isFilePlainText as j,
4296
+ getFiletypeFromFileName as k,
4297
+ linesFromFileContents as l,
4298
+ DEFAULT_RENDER_RANGE as m,
4299
+ areLanguagesAttached as n,
4300
+ hasResolvedThemes as o,
4301
+ pickReadableForeground as p,
4302
+ getThemes as q,
4303
+ relativeLuminance as r,
4304
+ surfacesMatch as s,
4305
+ renderFileWithHighlighter as t,
4306
+ useWorkerPool as u,
4307
+ createGutterGap as v,
4308
+ createGutterItem as w,
4309
+ createHastElement as x,
4310
+ getSharedHighlighter as y,
4311
+ createGutterWrapper as z
4312
+ };