@mhjuma/traverse 0.2.0 → 0.3.0

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.
@@ -0,0 +1,57 @@
1
+ import { loader } from '@monaco-editor/react';
2
+ import * as monaco from 'monaco-editor';
3
+
4
+ import { bootstrapKustoLanguage } from './bootstrapKustoLanguage';
5
+
6
+ /**
7
+ * Configure `@monaco-editor/react` to use the locally bundled Monaco instance
8
+ * instead of fetching it from the default CDN. This is required so that any
9
+ * Monaco contributions registered by this library (e.g. `@kusto/monaco-kusto`)
10
+ * attach to the same Monaco instance the `<Editor>` component uses — otherwise
11
+ * contributions are silently dropped ("two Monacos" problem).
12
+ *
13
+ * The call is idempotent and a no-op on the server. It is intentionally
14
+ * lightweight — it only configures the loader. Pre-loading the kusto
15
+ * language is gated behind `preloadKustoLanguage()` so consumers using only
16
+ * non-editor APIs (e.g. `createKustoClient`) do not pay for the multi-MB
17
+ * `@kusto/monaco-kusto` chunk.
18
+ */
19
+ let configured = false;
20
+ export function configureMonacoLoader(): void {
21
+ if (configured || typeof window === 'undefined') {
22
+ return;
23
+ }
24
+ configured = true;
25
+ loader.config({ monaco });
26
+ }
27
+
28
+ configureMonacoLoader();
29
+
30
+ /**
31
+ * Trigger registration of the kusto language (Monarch tokens provider, themes,
32
+ * completion/hover providers) ahead of the editor first mounting. Call from
33
+ * any component that will render the KQL editor (e.g. `<Explorer>`) so the
34
+ * dynamic import of `@kusto/monaco-kusto` overlaps with React/auth init —
35
+ * the editor's first paint then shows colored keywords/strings/numbers
36
+ * instead of plain text that "upgrades" a beat later.
37
+ *
38
+ * Editor-gated by design: consumers of `@mhjuma/traverse` that use only
39
+ * non-editor APIs (e.g. `createKustoClient`) should not call this and will
40
+ * not incur the kusto chunk download.
41
+ *
42
+ * Idempotent — repeated calls are no-ops. Errors are swallowed here and
43
+ * surfaced by `ExplorerWorkspace`'s mount-time bootstrap on retry.
44
+ */
45
+ let preloadStarted = false;
46
+ export function preloadKustoLanguage(): void {
47
+ if (preloadStarted || typeof window === 'undefined') {
48
+ return;
49
+ }
50
+ preloadStarted = true;
51
+ void bootstrapKustoLanguage(monaco).catch(() => { /* surfaced in ExplorerWorkspace */ });
52
+ }
53
+
54
+ /** Test-only: reset preload state so each test exercises the first-call path. */
55
+ export function __resetPreloadStateForTests(): void {
56
+ preloadStarted = false;
57
+ }
@@ -0,0 +1,81 @@
1
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
2
+
3
+ import { configureTraverseMonacoWorkers, __resetWorkerConfigForTests } from './monacoWorkers';
4
+
5
+ interface GlobalWithMonaco {
6
+ MonacoEnvironment?: { getWorker?: (workerId: string, label: string) => Worker };
7
+ }
8
+
9
+ function getMonacoEnvironment(): GlobalWithMonaco['MonacoEnvironment'] {
10
+ return (globalThis as unknown as GlobalWithMonaco).MonacoEnvironment;
11
+ }
12
+
13
+ describe('configureTraverseMonacoWorkers', () => {
14
+ beforeEach(() => {
15
+ __resetWorkerConfigForTests();
16
+ });
17
+
18
+ it('installs MonacoEnvironment.getWorker on first call', () => {
19
+ expect(getMonacoEnvironment()).toBeUndefined();
20
+ configureTraverseMonacoWorkers({});
21
+ expect(getMonacoEnvironment()?.getWorker).toBeTypeOf('function');
22
+ });
23
+
24
+ it('dispatches the "kusto" label to getKustoWorker', () => {
25
+ const kustoWorker = {} as Worker;
26
+ const editorWorker = {} as Worker;
27
+ const getKusto = vi.fn(() => kustoWorker);
28
+ const getEditor = vi.fn(() => editorWorker);
29
+ configureTraverseMonacoWorkers({ getKustoWorker: getKusto, getEditorWorker: getEditor });
30
+
31
+ const w = getMonacoEnvironment()!.getWorker!('id-1', 'kusto');
32
+ expect(w).toBe(kustoWorker);
33
+ expect(getKusto).toHaveBeenCalledTimes(1);
34
+ expect(getEditor).not.toHaveBeenCalled();
35
+ });
36
+
37
+ it('dispatches any non-kusto label to getEditorWorker', () => {
38
+ const editorWorker = {} as Worker;
39
+ const getEditor = vi.fn(() => editorWorker);
40
+ configureTraverseMonacoWorkers({ getEditorWorker: getEditor });
41
+
42
+ const a = getMonacoEnvironment()!.getWorker!('id-1', 'editorWorkerService');
43
+ const b = getMonacoEnvironment()!.getWorker!('id-2', 'css');
44
+ expect(a).toBe(editorWorker);
45
+ expect(b).toBe(editorWorker);
46
+ expect(getEditor).toHaveBeenCalledTimes(2);
47
+ });
48
+
49
+ it('throws a helpful error when the Kusto worker factory is missing', () => {
50
+ configureTraverseMonacoWorkers({});
51
+ expect(() => getMonacoEnvironment()!.getWorker!('id-1', 'kusto')).toThrow(/Kusto worker factory/);
52
+ });
53
+
54
+ it('throws a helpful error when the editor worker factory is missing and no pre-existing handler is present', () => {
55
+ configureTraverseMonacoWorkers({});
56
+ expect(() => getMonacoEnvironment()!.getWorker!('id-1', 'editorWorkerService'))
57
+ .toThrow(/No Monaco worker factory configured for label "editorWorkerService"/);
58
+ });
59
+
60
+ it('reconfigure swaps the active factories without re-installing the environment', () => {
61
+ const w1 = {} as Worker;
62
+ const w2 = {} as Worker;
63
+ configureTraverseMonacoWorkers({ getKustoWorker: () => w1 });
64
+ const env1 = getMonacoEnvironment();
65
+ configureTraverseMonacoWorkers({ getKustoWorker: () => w2 });
66
+ const env2 = getMonacoEnvironment();
67
+ expect(env1).toBe(env2);
68
+ expect(env2!.getWorker!('id', 'kusto')).toBe(w2);
69
+ });
70
+
71
+ it('falls back to a pre-existing host MonacoEnvironment.getWorker for unknown labels', () => {
72
+ const hostWorker = {} as Worker;
73
+ const hostGetWorker = vi.fn(() => hostWorker);
74
+ (globalThis as unknown as GlobalWithMonaco).MonacoEnvironment = { getWorker: hostGetWorker };
75
+
76
+ configureTraverseMonacoWorkers({});
77
+ const w = getMonacoEnvironment()!.getWorker!('id-1', 'editorWorkerService');
78
+ expect(w).toBe(hostWorker);
79
+ expect(hostGetWorker).toHaveBeenCalledWith('id-1', 'editorWorkerService');
80
+ });
81
+ });
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Worker factory: returns a fresh `Worker` instance that monaco-editor (or
3
+ * `@kusto/monaco-kusto`) will dispatch messages to.
4
+ */
5
+ export type MonacoWorkerFactory = () => Worker;
6
+
7
+ export interface MonacoWorkerConfig {
8
+ /**
9
+ * Factory for monaco-editor's base "editor worker service" — required for
10
+ * features like undo coalescing, find/replace, and large-document diffing.
11
+ * Will be invoked for any worker label other than `"kusto"`.
12
+ */
13
+ getEditorWorker?: MonacoWorkerFactory;
14
+ /**
15
+ * Factory for `@kusto/monaco-kusto`'s language-service worker (parser,
16
+ * binder, IntelliSense, diagnostics). Invoked when Monaco requests a
17
+ * worker with label `"kusto"`.
18
+ */
19
+ getKustoWorker?: MonacoWorkerFactory;
20
+ }
21
+
22
+ let currentConfig: MonacoWorkerConfig = {};
23
+ let installed = false;
24
+
25
+ interface GlobalWithMonaco {
26
+ MonacoEnvironment?: { getWorker?: (workerId: string, label: string) => Worker };
27
+ }
28
+
29
+ /**
30
+ * Configure how `@mhjuma/traverse` obtains Monaco web workers. Must be called
31
+ * once, before mounting `<Explorer>`. Bundler-aware hosts (Vite, webpack)
32
+ * typically construct workers via `new Worker(new URL(..., import.meta.url))`
33
+ * or `import Worker from '...?worker'` and pass the factories here.
34
+ *
35
+ * Calling more than once replaces the previous configuration. Subsequent
36
+ * Monaco worker spawns will pick up the new factories.
37
+ */
38
+ export function configureTraverseMonacoWorkers(config: MonacoWorkerConfig): void {
39
+ currentConfig = config;
40
+ installMonacoEnvironment();
41
+ }
42
+
43
+ function installMonacoEnvironment(): void {
44
+ if (typeof window === 'undefined') {
45
+ return;
46
+ }
47
+ if (installed) {
48
+ return;
49
+ }
50
+ installed = true;
51
+ const g = globalThis as unknown as GlobalWithMonaco;
52
+ const previous = g.MonacoEnvironment;
53
+ g.MonacoEnvironment = {
54
+ ...(previous ?? {}),
55
+ getWorker(workerId: string, label: string): Worker {
56
+ if (label === 'kusto') {
57
+ if (currentConfig.getKustoWorker) {
58
+ return currentConfig.getKustoWorker();
59
+ }
60
+ throw new Error(
61
+ '[traverse] No Kusto worker factory configured. Call ' +
62
+ 'configureTraverseMonacoWorkers({ getKustoWorker }) before mounting <Explorer>.',
63
+ );
64
+ }
65
+ if (currentConfig.getEditorWorker) {
66
+ return currentConfig.getEditorWorker();
67
+ }
68
+ if (previous?.getWorker) {
69
+ return previous.getWorker(workerId, label);
70
+ }
71
+ throw new Error(
72
+ `[traverse] No Monaco worker factory configured for label "${label}". Call ` +
73
+ 'configureTraverseMonacoWorkers({ getEditorWorker }) before mounting <Explorer>.',
74
+ );
75
+ },
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Test-only escape hatch. Resets the module's internal state so each test can
81
+ * exercise the first-install path. Not exported from the package index.
82
+ */
83
+ export function __resetWorkerConfigForTests(): void {
84
+ currentConfig = {};
85
+ installed = false;
86
+ if (typeof window !== 'undefined') {
87
+ const g = globalThis as unknown as GlobalWithMonaco;
88
+ delete g.MonacoEnvironment;
89
+ }
90
+ }
package/src/index.ts CHANGED
@@ -14,3 +14,5 @@ export { bootstrapExplorer, useExplorerTheme } from './bootstrap';
14
14
  export type { BootstrapExplorerOptions } from './bootstrap';
15
15
  export { loadSnapshot, saveSnapshot, clearSnapshot, validateAndCleanSnapshot, extractSnapshot, SNAPSHOT_VERSION } from './state/persistence';
16
16
  export type { ExplorerTabsSnapshot } from './state/persistence';
17
+ export { configureTraverseMonacoWorkers } from './components/ExplorerWorkspace/monacoWorkers';
18
+ export type { MonacoWorkerConfig, MonacoWorkerFactory } from './components/ExplorerWorkspace/monacoWorkers';
@@ -1,7 +1,7 @@
1
1
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
2
 
3
- import { parseSchema, loadSchema, reloadSchema, getSchema, getSchemaFolders, listDatabases, getPersistedDatabases, persistDatabases, KQL_FUNCTIONS, KQL_AGGREGATIONS, KQL_SCALAR_FUNCTIONS } from './schema';
4
- import type { KustoSchemaDb } from './schema';
3
+ import { parseSchema, loadSchema, reloadSchema, getSchema, getSchemaFolders, getRawShowSchema, listDatabases, getPersistedDatabases, persistDatabases } from './schema';
4
+ import type { KustoSchemaDb, RawShowSchema } from './schema';
5
5
  import type { KustoClient } from './kusto';
6
6
 
7
7
  const mockStore = new Map<string, unknown>();
@@ -364,32 +364,6 @@ describe('getSchemaFolders', () => {
364
364
  });
365
365
  });
366
366
 
367
- describe('KQL constants', () => {
368
- it('KQL_FUNCTIONS contains expected keywords', () => {
369
- expect(KQL_FUNCTIONS).toContain('where');
370
- expect(KQL_FUNCTIONS).toContain('project');
371
- expect(KQL_FUNCTIONS).toContain('summarize');
372
- expect(KQL_FUNCTIONS).toContain('join');
373
- expect(KQL_FUNCTIONS).toContain('union');
374
- });
375
-
376
- it('KQL_AGGREGATIONS contains expected functions', () => {
377
- expect(KQL_AGGREGATIONS).toContain('count');
378
- expect(KQL_AGGREGATIONS).toContain('sum');
379
- expect(KQL_AGGREGATIONS).toContain('avg');
380
- expect(KQL_AGGREGATIONS).toContain('dcount');
381
- expect(KQL_AGGREGATIONS).toContain('percentile');
382
- });
383
-
384
- it('KQL_SCALAR_FUNCTIONS contains expected functions', () => {
385
- expect(KQL_SCALAR_FUNCTIONS).toContain('ago');
386
- expect(KQL_SCALAR_FUNCTIONS).toContain('now');
387
- expect(KQL_SCALAR_FUNCTIONS).toContain('strlen');
388
- expect(KQL_SCALAR_FUNCTIONS).toContain('iif');
389
- expect(KQL_SCALAR_FUNCTIONS).toContain('parse_json');
390
- });
391
- });
392
-
393
367
  describe('per-cluster schema', () => {
394
368
  it('getSchema returns empty for unknown target', () => {
395
369
  const schema = getSchema({ clusterUrl: 'https://unknown.kusto.windows.net', database: 'UnknownDB' });
@@ -616,3 +590,108 @@ describe('listDatabases with forceRefresh', () => {
616
590
  expect(getPersistedDatabases(clusterUrl)).toEqual(['NewDB']);
617
591
  });
618
592
  });
593
+
594
+ describe('getRawShowSchema', () => {
595
+ it('returns the raw .show schema payload that loadSchema captured', async () => {
596
+ const mockDb: KustoSchemaDb = {
597
+ Tables: {
598
+ RawTable: { Folder: 'Raw', OrderedColumns: [{ Name: 'X', CslType: 'long' }] },
599
+ },
600
+ };
601
+ const raw: RawShowSchema = { Plugins: [], Databases: { rawdb: mockDb as never } };
602
+ const client = createMockClient({
603
+ rows: [{ DatabaseSchema: JSON.stringify(raw) }],
604
+ columns: [],
605
+ });
606
+ const target = { clusterUrl: 'https://raw.kusto.windows.net', database: 'rawdb' };
607
+
608
+ await reloadSchema(client, target);
609
+
610
+ const result = getRawShowSchema(target);
611
+ expect(result).not.toBeNull();
612
+ expect(result?.Databases['rawdb']).toBeDefined();
613
+ expect(result?.Plugins).toEqual([]);
614
+ });
615
+
616
+ it('returns null when no schema has been loaded for the target', () => {
617
+ const target = { clusterUrl: 'https://never-loaded.kusto.windows.net', database: 'x' };
618
+ expect(getRawShowSchema(target)).toBeNull();
619
+ });
620
+
621
+ it('restores the raw payload from persistent storage when in-memory is empty', () => {
622
+ const mockDb: KustoSchemaDb = {
623
+ Tables: { PersistedTable: { OrderedColumns: [] } },
624
+ };
625
+ const raw: RawShowSchema = { Plugins: [], Databases: { persistdb: mockDb as never } };
626
+ const target = { clusterUrl: 'https://restore.kusto.windows.net', database: 'persistdb' };
627
+
628
+ // Seed the persistent store directly, simulating a prior session writing
629
+ // raw-schema:<cluster>|<db>. No prior in-memory load for this target.
630
+ mockStore.set(`raw-schema:${target.clusterUrl}|${target.database}`, raw);
631
+
632
+ const result = getRawShowSchema(target);
633
+ expect(result).not.toBeNull();
634
+ expect(result?.Databases['persistdb']).toBeDefined();
635
+ // Second call should hit the warmed in-memory cache (still equal payload).
636
+ expect(getRawShowSchema(target)).toBe(result);
637
+ });
638
+
639
+ it('persists raw payload under both target and effectiveTarget cache keys when auto-discovering', async () => {
640
+ const mockDb: KustoSchemaDb = {
641
+ Tables: { AutoDiscoveredTable: { OrderedColumns: [] } },
642
+ };
643
+ const raw: RawShowSchema = { Plugins: [], Databases: { autodb: mockDb as never } };
644
+ const clusterUrl = 'https://auto.kusto.windows.net';
645
+ // Mgmt query #1 (auto-discovery): list databases; returns one db.
646
+ // Mgmt query #2: schema for that db.
647
+ const queryKustoMgmt = vi.fn()
648
+ .mockResolvedValueOnce({ rows: [{ DatabaseName: 'autodb' }], columns: [] })
649
+ .mockResolvedValueOnce({ rows: [{ DatabaseSchema: JSON.stringify(raw) }], columns: [] });
650
+ const client: KustoClient = {
651
+ queryKusto: vi.fn(),
652
+ queryKustoMgmt,
653
+ clearQueryCache: vi.fn(),
654
+ getQueryCacheSize: vi.fn().mockReturnValue(0),
655
+ };
656
+ const originalTarget = { clusterUrl, database: '' };
657
+
658
+ await reloadSchema(client, originalTarget);
659
+
660
+ // Raw payload retrievable under the original (empty-db) target.
661
+ expect(getRawShowSchema(originalTarget)).not.toBeNull();
662
+ // …and under the effective target after auto-discovery.
663
+ expect(getRawShowSchema({ clusterUrl, database: 'autodb' })).not.toBeNull();
664
+ });
665
+
666
+ it('clears the raw cache on reloadSchema', async () => {
667
+ const mockDb: KustoSchemaDb = {
668
+ Tables: { ClearedTable: { OrderedColumns: [] } },
669
+ };
670
+ const raw: RawShowSchema = { Plugins: [], Databases: { cleardb: mockDb as never } };
671
+ const target = { clusterUrl: 'https://clear.kusto.windows.net', database: 'cleardb' };
672
+
673
+ const client = createMockClient({
674
+ rows: [{ DatabaseSchema: JSON.stringify(raw) }],
675
+ columns: [],
676
+ });
677
+
678
+ await reloadSchema(client, target);
679
+ expect(getRawShowSchema(target)).not.toBeNull();
680
+
681
+ // Reload with a client that returns a brand-new payload; the old one
682
+ // should not be retained.
683
+ const newRaw: RawShowSchema = { Plugins: [], Databases: { cleardb: { Tables: { NewTable: {} } } as never } };
684
+ const client2 = createMockClient({
685
+ rows: [{ DatabaseSchema: JSON.stringify(newRaw) }],
686
+ columns: [],
687
+ });
688
+ await reloadSchema(client2, target);
689
+
690
+ const result = getRawShowSchema(target);
691
+ expect(result?.Databases['cleardb']).toBeDefined();
692
+ // Verify the new payload took the place of the old one (different Tables key).
693
+ const tables = (result?.Databases['cleardb'] as { Tables: Record<string, unknown> } | undefined)?.Tables;
694
+ expect(tables && 'NewTable' in tables).toBe(true);
695
+ expect(tables && 'ClearedTable' in tables).toBe(false);
696
+ });
697
+ });
@@ -25,9 +25,33 @@ export interface KustoSchemaDb {
25
25
  ExternalTables?: Record<string, { Folder?: string; DocString?: string; OrderedColumns?: { Name: string; CslType: string }[] }>;
26
26
  }
27
27
 
28
+ /**
29
+ * Root payload returned by Kusto's `.show database schema as json` command.
30
+ * Shape matches what `@kusto/monaco-kusto`'s `setSchemaFromShowSchema` expects.
31
+ * Kept loose (optional fields) so older cluster responses still parse.
32
+ */
33
+ export interface RawShowSchema {
34
+ readonly Plugins?: readonly unknown[];
35
+ readonly Databases: Record<string, RawShowSchemaDatabase>;
36
+ }
37
+
38
+ export interface RawShowSchemaDatabase {
39
+ readonly Name?: string;
40
+ readonly Tables?: Record<string, unknown>;
41
+ readonly ExternalTables?: Record<string, unknown>;
42
+ readonly MaterializedViews?: Record<string, unknown>;
43
+ readonly Functions?: Record<string, unknown>;
44
+ readonly EntityGroups?: Record<string, readonly string[]>;
45
+ readonly Graphs?: Record<string, unknown>;
46
+ readonly MajorVersion?: number;
47
+ readonly MinorVersion?: number;
48
+ readonly DatabaseAccessMode?: string;
49
+ }
50
+
28
51
  // Per-cluster schema cache
29
52
  const schemaCache = new Map<string, SchemaTable[]>();
30
53
  const foldersCache = new Map<string, string[]>();
54
+ const rawSchemaCache = new Map<string, RawShowSchema>();
31
55
  const loadingPromises = new Map<string, Promise<void>>();
32
56
 
33
57
  function cacheKey(target?: KustoTarget): string {
@@ -41,6 +65,10 @@ function persistSchemaKey(target: KustoTarget): string {
41
65
  return `schema:${target.clusterUrl}|${target.database}`;
42
66
  }
43
67
 
68
+ function persistRawSchemaKey(target: KustoTarget): string {
69
+ return `raw-schema:${target.clusterUrl}|${target.database}`;
70
+ }
71
+
44
72
  function persistDbKey(clusterUrl: string): string {
45
73
  return `dbs:${clusterUrl}`;
46
74
  }
@@ -54,6 +82,11 @@ function restoreSchemaFromStore(target: KustoTarget): boolean {
54
82
  if (stored && stored.length > 0) {
55
83
  schemaCache.set(key, stored);
56
84
  foldersCache.set(key, [...new Set(stored.map((t) => t.folder))].filter(Boolean).sort());
85
+ // Best-effort raw restore — language service IntelliSense needs this.
86
+ const rawStored = stateService.get<RawShowSchema>('explorerCache', persistRawSchemaKey(target));
87
+ if (rawStored && rawStored.Databases) {
88
+ rawSchemaCache.set(key, rawStored);
89
+ }
57
90
  return true;
58
91
  }
59
92
  return false;
@@ -63,6 +96,10 @@ function persistSchema(target: KustoTarget, schema: SchemaTable[]): void {
63
96
  stateService.set('explorerCache', persistSchemaKey(target), schema);
64
97
  }
65
98
 
99
+ function persistRawSchema(target: KustoTarget, raw: RawShowSchema): void {
100
+ stateService.set('explorerCache', persistRawSchemaKey(target), raw);
101
+ }
102
+
66
103
  export function getPersistedDatabases(clusterUrl: string): string[] | null {
67
104
  return stateService.get<string[]>('explorerCache', persistDbKey(clusterUrl));
68
105
  }
@@ -172,21 +209,25 @@ export async function loadSchema(client: KustoClient, target?: KustoTarget): Pro
172
209
  try {
173
210
  const result = await client.queryKustoMgmt<{ DatabaseSchema: string }>('.show database schema as json', effectiveTarget);
174
211
  if (result.rows.length > 0) {
175
- const schemaJson = JSON.parse(result.rows[0].DatabaseSchema);
212
+ const schemaJson = JSON.parse(result.rows[0].DatabaseSchema) as RawShowSchema;
176
213
  const dbName = Object.keys(schemaJson.Databases)[0];
177
214
  const db = schemaJson.Databases[dbName] as KustoSchemaDb;
178
215
  const parsed = parseSchema(db);
179
216
  schemaCache.set(key, parsed);
180
217
  foldersCache.set(key, [...new Set(parsed.map((t) => t.folder))].filter(Boolean).sort());
218
+ rawSchemaCache.set(key, schemaJson);
181
219
  // Persist to IndexedDB
182
220
  if (effectiveTarget) {
183
221
  persistSchema(effectiveTarget, parsed);
222
+ persistRawSchema(effectiveTarget, schemaJson);
184
223
  }
185
224
  // Also cache under the original target key if different
186
225
  if (target && cacheKey(target) !== key) {
187
226
  schemaCache.set(cacheKey(target), parsed);
188
227
  foldersCache.set(cacheKey(target), [...new Set(parsed.map((t) => t.folder))].filter(Boolean).sort());
228
+ rawSchemaCache.set(cacheKey(target), schemaJson);
189
229
  persistSchema(target, parsed);
230
+ persistRawSchema(target, schemaJson);
190
231
  }
191
232
  } else {
192
233
  schemaCache.set(key, []);
@@ -223,8 +264,10 @@ export async function reloadSchema(client: KustoClient, target?: KustoTarget): P
223
264
  const key = cacheKey(target);
224
265
  schemaCache.delete(key);
225
266
  foldersCache.delete(key);
267
+ rawSchemaCache.delete(key);
226
268
  if (target) {
227
269
  stateService.delete('explorerCache', persistSchemaKey(target));
270
+ stateService.delete('explorerCache', persistRawSchemaKey(target));
228
271
  }
229
272
  return loadSchema(client, target);
230
273
  }
@@ -247,6 +290,28 @@ export function getSchemaFolders(target?: KustoTarget): string[] {
247
290
  return target ? [] : [];
248
291
  }
249
292
 
293
+ /**
294
+ * Returns the raw `.show database schema as json` payload for the given target,
295
+ * if known. The payload's shape matches what `@kusto/monaco-kusto`'s
296
+ * `setSchemaFromShowSchema` accepts. Returns null when no schema has been
297
+ * loaded (or persisted) for this target.
298
+ */
299
+ export function getRawShowSchema(target?: KustoTarget): RawShowSchema | null {
300
+ const key = cacheKey(target);
301
+ const cached = rawSchemaCache.get(key);
302
+ if (cached) {
303
+ return cached;
304
+ }
305
+ if (target) {
306
+ const persisted = stateService.get<RawShowSchema>('explorerCache', persistRawSchemaKey(target));
307
+ if (persisted && persisted.Databases) {
308
+ rawSchemaCache.set(key, persisted);
309
+ return persisted;
310
+ }
311
+ }
312
+ return null;
313
+ }
314
+
250
315
  /** List databases on a Kusto cluster. Uses persistent cache; pass forceRefresh to bypass. */
251
316
  export async function listDatabases(client: KustoClient, clusterUrl: string, forceRefresh = false): Promise<string[]> {
252
317
  if (!forceRefresh) {
@@ -268,27 +333,3 @@ export async function listDatabases(client: KustoClient, clusterUrl: string, for
268
333
  return [];
269
334
  }
270
335
  }
271
-
272
- // --- KQL language tokens (not from Kusto, always static) ---
273
-
274
- export const KQL_FUNCTIONS = [
275
- 'where', 'project', 'extend', 'summarize', 'count', 'take', 'top', 'order', 'sort',
276
- 'join', 'union', 'lookup', 'mv-expand', 'parse', 'evaluate',
277
- 'render', 'as', 'let', 'set', 'alias', 'restrict', 'pattern',
278
- ];
279
-
280
- export const KQL_AGGREGATIONS = [
281
- 'count', 'countif', 'dcount', 'sum', 'sumif', 'avg', 'min', 'max',
282
- 'percentile', 'percentiles', 'stdev', 'variance', 'make_list', 'make_set',
283
- 'arg_max', 'arg_min', 'any', 'take_any',
284
- ];
285
-
286
- export const KQL_SCALAR_FUNCTIONS = [
287
- 'ago', 'now', 'datetime', 'timespan', 'bin', 'floor', 'ceiling',
288
- 'strlen', 'substring', 'tolower', 'toupper', 'trim', 'replace',
289
- 'strcat', 'split', 'parse_json', 'tostring', 'toint', 'tolong', 'todouble', 'tobool',
290
- 'iif', 'iff', 'case', 'coalesce', 'isempty', 'isnotempty', 'isnull', 'isnotnull',
291
- 'format_datetime', 'datetime_diff', 'startofday', 'startofweek', 'startofmonth',
292
- 'round', 'abs', 'log', 'pow', 'sqrt',
293
- 'array_length', 'pack', 'bag_keys',
294
- ];
@@ -0,0 +1,3 @@
1
+ import { vi } from 'vitest';
2
+
3
+ vi.mock('monaco-editor', () => ({}));
package/vitest.config.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  import { defineConfig } from 'vitest/config';
2
2
 
3
3
  export default defineConfig({
4
+ optimizeDeps: {
5
+ include: ['monaco-editor'],
6
+ },
7
+ resolve: {
8
+ mainFields: ['module', 'jsnext:main', 'jsnext', 'main', 'browser'],
9
+ },
4
10
  test: {
5
11
  globals: false,
6
12
  environment: 'jsdom',
@@ -8,6 +14,7 @@ export default defineConfig({
8
14
  exclude: ['**/node_modules/**', '**/.{idea,git,cache,output,temp}/**'],
9
15
  passWithNoTests: false,
10
16
  retry: 0,
17
+ setupFiles: ['./src/test-setup.ts'],
11
18
  typecheck: {
12
19
  enabled: true,
13
20
  tsconfig: 'tsconfig.spec.json',