@singapore-editor/lsp-plugin 0.2.13 → 0.2.14

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 (45) hide show
  1. package/dist/codeActions.js.map +1 -1
  2. package/dist/colorAlpha.js.map +1 -1
  3. package/dist/completion.js.map +1 -1
  4. package/dist/completionCommit.js.map +1 -1
  5. package/dist/completionController.js.map +1 -1
  6. package/dist/completionProviders.js.map +1 -1
  7. package/dist/definitionLinkController.js.map +1 -1
  8. package/dist/definitionNavigation.js.map +1 -1
  9. package/dist/diagnosticNotes.js.map +1 -1
  10. package/dist/diagnosticProjection.js.map +1 -1
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/diagnosticsPresenter.js.map +1 -1
  13. package/dist/document.js.map +1 -1
  14. package/dist/documentHighlightController.js.map +1 -1
  15. package/dist/documentSnapshot.js.map +1 -1
  16. package/dist/documentSync.js.map +1 -1
  17. package/dist/documentSyncController.js.map +1 -1
  18. package/dist/formatOnType.js.map +1 -1
  19. package/dist/formatting.js.map +1 -1
  20. package/dist/fuzzyMatch.js.map +1 -1
  21. package/dist/hoverParticipant.js.map +1 -1
  22. package/dist/keyCommands.js.map +1 -1
  23. package/dist/lane.js.map +1 -1
  24. package/dist/lspConnection.js.map +1 -1
  25. package/dist/lspConnectionPool.js.map +1 -1
  26. package/dist/minimalEdits.js.map +1 -1
  27. package/dist/paths.js.map +1 -1
  28. package/dist/plugin.js.map +1 -1
  29. package/dist/plugin.styles.js.map +1 -1
  30. package/dist/pullDiagnostics.js.map +1 -1
  31. package/dist/renameWidget.js.map +1 -1
  32. package/dist/retainedSource.js.map +1 -1
  33. package/dist/semanticTokenDecoder.js.map +1 -1
  34. package/dist/semanticTokens.js.map +1 -1
  35. package/dist/serverSet.js.map +1 -1
  36. package/dist/signatureHelp.js.map +1 -1
  37. package/dist/signatureHelpController.js.map +1 -1
  38. package/dist/sourceConnection.js.map +1 -1
  39. package/dist/sourceText.js.map +1 -1
  40. package/dist/types.js.map +1 -1
  41. package/dist/viewDocumentSnapshot.js.map +1 -1
  42. package/dist/workspaceEdit.js.map +1 -1
  43. package/dist/workspaceEditProvenance.js.map +1 -1
  44. package/dist/workspaceTextEdits.js.map +1 -1
  45. package/package.json +7 -7
@@ -1 +1 @@
1
- {"version":3,"file":"document.js","names":[],"sources":["../src/document.ts"],"sourcesContent":["import type { EditorTextBuffer } from '@singapore-editor/core/document'\nimport type {\n EditorDisposable,\n EditorViewContributionUpdateKind,\n} from '@singapore-editor/core/extensions'\nimport type { LspTextDocumentSnapshot } from '@singapore-editor/lsp'\nimport type * as lsp from 'vscode-languageserver-protocol'\nimport { DocumentSync } from './documentSync'\nimport { summarizeDiagnostics } from './diagnostics'\nimport {\n acquireResolvedLanguageServerLane,\n resolveLanguageServerLaneOptions,\n type AcquiredLanguageServerLane,\n type LanguageServerResolvedLaneOptions,\n} from './lane'\nimport { PullDiagnosticsController } from './pullDiagnostics'\nimport type {\n LanguageServerDocumentSnapshot,\n LanguageServerDiagnosticsFreshness,\n LanguageServerDocumentSyncOptions,\n LanguageServerLaneOptions,\n LanguageServerStatus,\n OnApplyWorkspaceEdit,\n} from './types'\nimport { bufferDocumentSnapshot } from './documentSnapshot'\nimport type { LanguageServerSourceOwner } from './retainedSource'\nimport { languageServerSourceConnection } from './sourceConnection'\n\n/** A view's share of one lane's diagnostics for the document. */\nexport type DocumentLaneDiagnosticsObserver = {\n clear(): void\n render(document: LspTextDocumentSnapshot, diagnostics: readonly lsp.Diagnostic[]): void\n publishSummary(\n uri: lsp.DocumentUri,\n version: number | null,\n diagnostics: readonly lsp.Diagnostic[],\n freshness: LanguageServerDiagnosticsFreshness,\n ): void\n}\n\ntype DocumentSource = {\n getSnapshot(): LanguageServerDocumentSnapshot\n getSourceOwner(): LanguageServerSourceOwner | null\n}\n\nexport type LanguageServerDocumentOptions = {\n readonly buffer: EditorTextBuffer\n readonly uri: string\n readonly languageId: string\n readonly documentId?: string\n readonly lanes: readonly LanguageServerLaneOptions[]\n readonly onApplyWorkspaceEdit?: OnApplyWorkspaceEdit\n readonly controller?: LanguageServerDocumentSyncOptions['controller']\n}\n\n/** A document's protocol state. Views borrow it; its creator disposes it. */\nexport class LanguageServerDocument {\n readonly lanes: readonly DocumentLanguageServerLane[]\n readonly syncOptions: LanguageServerDocumentSyncOptions\n private disposed = false\n\n constructor(\n source: DocumentSource,\n options: {\n readonly lanes: readonly LanguageServerResolvedLaneOptions[]\n readonly documentSync: LanguageServerDocumentSyncOptions\n },\n ) {\n this.syncOptions = options.documentSync\n this.lanes = options.lanes.map(\n (lane) => new DocumentLanguageServerLane(source, lane, options.documentSync),\n )\n }\n\n synchronize(kind: EditorViewContributionUpdateKind = 'content'): void {\n if (this.disposed) return\n for (const lane of this.lanes) lane.synchronize(kind)\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n for (const lane of this.lanes) lane.dispose()\n }\n}\n\nexport function createLanguageServerDocument(\n options: LanguageServerDocumentOptions,\n): LanguageServerDocument {\n return new LanguageServerDocument(\n {\n getSnapshot: () => bufferDocumentSnapshot(options),\n getSourceOwner: () => ({\n buffer: options.buffer,\n documentId: options.documentId ?? options.uri,\n }),\n },\n {\n lanes: options.lanes.map((lane) =>\n resolveLanguageServerLaneOptions({\n ...lane,\n onApplyWorkspaceEdit: options.onApplyWorkspaceEdit ?? lane.onApplyWorkspaceEdit,\n }),\n ),\n documentSync: {\n controller: options.controller,\n uriForDocument: () => options.uri,\n },\n },\n )\n}\n\nexport class DocumentLanguageServerLane {\n private connectionStatus: LanguageServerStatus = 'idle'\n\n get status(): LanguageServerStatus {\n return this.connectionStatus\n }\n readonly connection: AcquiredLanguageServerLane\n readonly sync: DocumentSync\n private readonly pullDiagnostics: PullDiagnosticsController | null\n private readonly registration: EditorDisposable | undefined\n private readonly observers = new Set<DocumentLaneDiagnosticsObserver>()\n /** Whether the server has answered for the active document since it became active. */\n private diagnosticsReceived = false\n private diagnosticsVersion: number | null = null\n private unavailable = false\n private readonly listeners = new Set<() => void>()\n private disposed = false\n\n constructor(\n private readonly source: DocumentSource,\n readonly options: LanguageServerResolvedLaneOptions,\n syncOptions: LanguageServerDocumentSyncOptions,\n ) {\n this.connection = acquireResolvedLanguageServerLane(\n {\n ...options,\n onStatusChange: (status) => {\n this.connectionStatus = status\n options.onStatusChange?.(status)\n },\n },\n {\n beforeReady: () => this.synchronizeSource(),\n onReady: () => {\n this.unavailable = false\n // After a reconnect the document is the same one; only a new request can refresh it.\n if (!this.pullDiagnostics?.pending) this.pullDiagnostics?.synchronize()\n this.republishSummary()\n this.notify()\n },\n onReconnecting: () => {\n this.unavailable = true\n this.sync.close()\n this.pullDiagnostics?.cancel()\n this.sync.clearDiagnostics()\n this.notify()\n },\n onDiagnosticRefresh: () => this.pullDiagnostics?.refresh(),\n onPublishDiagnostics: (params) => {\n if (options.features.diagnostics !== undefined) this.sync.publishDiagnostics(params)\n },\n onUnavailable: () => {\n this.connectionStatus = 'error'\n this.unavailable = true\n this.sync.close()\n this.pullDiagnostics?.cancel()\n this.sync.clearDiagnostics()\n this.notify()\n },\n },\n )\n this.sync = new DocumentSync(\n this.connection.workspace,\n {\n clear: () => {\n for (const observer of this.observers) observer.clear()\n },\n render: (document, diagnostics) => {\n for (const observer of this.observers) observer.render(document, diagnostics)\n },\n publishSummary: (uri, version, diagnostics, kind) => {\n this.diagnosticsReceived = kind === 'result'\n this.diagnosticsVersion = version\n this.publishSummary(uri, version, diagnostics)\n },\n },\n {\n ...syncOptions,\n logicalRevisionScope: this.connection.logicalRevisionScope,\n getSourceOwner: () => this.source.getSourceOwner(),\n getConnection: () => languageServerSourceConnection(this.connection.client),\n onDocumentClosed: () => this.notify(),\n onDocumentChanged: () => {\n this.pullDiagnostics?.synchronize()\n },\n onError: (error) => options.onError?.(error),\n },\n )\n this.pullDiagnostics =\n options.features.diagnostics === undefined\n ? null\n : new PullDiagnosticsController({\n client: this.connection.client,\n getDocument: () => {\n const active = this.sync.activeDocument\n return active ? { uri: active.uri, version: active.lspVersion } : null\n },\n publish: (document, items) =>\n this.sync.pullDiagnostics(document.uri, document.version, items),\n onRequestError: (error) => options.onRequestError?.('textDocument/diagnostic', error),\n onPendingChange: () => this.republishSummary(),\n })\n this.registration = syncOptions.controller?.register({\n getSnapshot: () => source.getSnapshot(),\n sync: this.sync,\n })\n void this.connection.ready.catch(() => undefined)\n }\n\n /** How far the active document's diagnostics can be trusted. */\n get diagnosticsFreshness(): LanguageServerDiagnosticsFreshness {\n if (this.unavailable) return 'unavailable'\n if (this.pullDiagnostics?.pending) return this.diagnosticsReceived ? 'refreshing' : 'awaiting'\n return this.diagnosticsReceived ? 'current' : 'silent'\n }\n\n attach(\n presenter: DocumentLaneDiagnosticsObserver,\n onConnectionChange: () => void,\n ): EditorDisposable {\n this.observers.add(presenter)\n this.listeners.add(onConnectionChange)\n const active = this.sync.activeDocument\n if (active) {\n presenter.render(active, this.sync.diagnostics)\n presenter.publishSummary(\n active.uri,\n this.diagnosticsVersion,\n this.sync.diagnostics,\n this.diagnosticsFreshness,\n )\n }\n return {\n dispose: () => {\n this.observers.delete(presenter)\n this.listeners.delete(onConnectionChange)\n },\n }\n }\n\n synchronize(kind: EditorViewContributionUpdateKind = 'content'): void {\n if (this.disposed || !this.connection.isReady()) return\n const snapshot = this.source.getSnapshot()\n if (!this.sync.shouldSync(kind, snapshot)) return\n void this.sync.sync(snapshot).catch((error) => {\n if (!isCancellation(error)) this.options.onError?.(error)\n })\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n this.registration?.dispose()\n this.pullDiagnostics?.dispose()\n this.sync.dispose()\n this.connection.release()\n this.observers.clear()\n this.listeners.clear()\n }\n\n private async synchronizeSource(): Promise<void> {\n try {\n await this.sync.sync(this.source.getSnapshot())\n } catch (error) {\n if (!isCancellation(error)) throw error\n }\n }\n\n private notify(): void {\n for (const listener of this.listeners) listener()\n }\n\n private publishSummary(\n uri: lsp.DocumentUri,\n version: number | null,\n diagnostics: readonly lsp.Diagnostic[],\n ): void {\n if (this.disposed) return\n const freshness = this.diagnosticsFreshness\n this.options.onDiagnostics?.(summarizeDiagnostics(uri, version, diagnostics, freshness))\n for (const observer of this.observers)\n observer.publishSummary(uri, version, diagnostics, freshness)\n }\n\n /** The diagnostics did not change, but how far they can be trusted did. */\n private republishSummary(): void {\n const active = this.sync?.activeDocument\n if (!active) return\n this.publishSummary(active.uri, this.diagnosticsVersion, this.sync.diagnostics)\n }\n}\n\nfunction isCancellation(error: unknown): boolean {\n return error instanceof DOMException && error.name === 'AbortError'\n}\n"],"mappings":";;;;;;;;AAwDA,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA,WAAmB;CAEnB,YACE,QACA,SAIA;EACA,KAAK,cAAc,QAAQ;EAC3B,KAAK,QAAQ,QAAQ,MAAM,KACxB,SAAS,IAAI,2BAA2B,QAAQ,MAAM,QAAQ,YAAY,CAC7E;CACF;CAEA,YAAY,OAAyC,WAAiB;EACpE,IAAI,KAAK,UAAU;EACnB,KAAK,MAAM,QAAQ,KAAK,OAAO,KAAK,YAAY,IAAI;CACtD;CAEA,UAAgB;EACd,IAAI,KAAK,UAAU;EACnB,KAAK,WAAW;EAChB,KAAK,MAAM,QAAQ,KAAK,OAAO,KAAK,QAAQ;CAC9C;AACF;AAEA,SAAgB,6BACd,SACwB;CACxB,OAAO,IAAI,uBACT;EACE,mBAAmB,uBAAuB,OAAO;EACjD,uBAAuB;GACrB,QAAQ,QAAQ;GAChB,YAAY,QAAQ,cAAc,QAAQ;EAC5C;CACF,GACA;EACE,OAAO,QAAQ,MAAM,KAAK,SACxB,iCAAiC;GAC/B,GAAG;GACH,sBAAsB,QAAQ,wBAAwB,KAAK;EAC7D,CAAC,CACH;EACA,cAAc;GACZ,YAAY,QAAQ;GACpB,sBAAsB,QAAQ;EAChC;CACF,CACF;AACF;AAEA,IAAa,6BAAb,MAAwC;CAmBnB;CACR;CAnBX,mBAAiD;CAEjD,IAAI,SAA+B;EACjC,OAAO,KAAK;CACd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AQ,UAAU,KAAK;EAC1D,CAAC;CACH;CAEA,UAAgB;EACd,IAAI,KAAK,UAAU;EACnB,KAAK,WAAW;EAChB,KAAK,cAAc,QAAQ;EAC3B,KAAK,iBAAiB,QAAQ;EAC9B,KAAK,KAAK,QAAQ;EAClB,KAAK,WAAW,QAAQ;EACxB,KAAK,UAAU,MAAM;EACrB,KAAK,UAAU,MAAM;CACvB;CAEA,MAAc,oBAAmC;EAC/C,IAAI;GACF,MAAM,KAAK,KAAK,KAAK,KAAK,OAAO,YAAY,CAAC;EAChD,SAAS,OAAO;GACd,IAAI,CAAC,eAAe,KAAK,GAAG,MAAM;EACpC;CACF;CAEA,SAAuB;EACrB,KAAK,MAAM,YAAY,KAAK,WAAW,SAAS;CAClD;CAEA,eACE,KACA,SACA,aACM;EACN,IAAI,KAAK,UAAU;EACnB,MAAM,YAAY,KAAK;EACvB,KAAK,QAAQ,gBAAgB,qBAAqB,KAAK,SAAS,aAAa,SAAS,CAAC;EACvF,KAAK,MAAM,YAAY,KAAK,WAC1B,SAAS,eAAe,KAAK,SAAS,aAAa,SAAS;CAChE;;CAGA,mBAAiC;EAC/B,MAAM,SAAS,KAAK,MAAM;EAC1B,IAAI,CAAC,QAAQ;EACb,KAAK,eAAe,OAAO,KAAK,KAAK,oBAAoB,KAAK,KAAK,WAAW;CAChF;AACF;AAEA,SAAS,eAAe,OAAyB;CAC/C,OAAO,iBAAiB,gBAAgB,MAAM,SAAS;AACzD"}
@@ -1 +1 @@
1
- {"version":3,"file":"documentHighlightController.js","names":[],"sources":["../src/documentHighlightController.ts"],"sourcesContent":["import type * as lsp from 'vscode-languageserver-protocol'\n\nimport type {\n EditorViewContributionContext,\n EditorViewContributionUpdateKind,\n EditorViewSnapshot,\n} from '@singapore-editor/core'\nimport { lspPositionToOffsetInSnapshot, offsetToLspPositionInSnapshot } from '@singapore-editor/lsp'\n\nimport type { ActiveDocument } from './pluginTypes'\nimport type { LanguageServerFeatureRouter } from './serverSet'\n\n/** Matches the hover debounce: both answer \"what is under the caret\", and should feel alike. */\nconst DOCUMENT_HIGHLIGHT_DEBOUNCE_MS = 150\n\nexport type DocumentHighlightControllerOptions = {\n readonly context: EditorViewContributionContext\n readonly router: LanguageServerFeatureRouter\n readonly highlightName: string\n readonly getActiveDocument: () => ActiveDocument | null\n readonly onRequestError: (error: unknown) => void\n}\n\n/**\n * Paints every reference to the symbol under the caret, as the language server sees them.\n *\n * More precise than a textual occurrence match: the server knows scope, so a local `value` does not\n * light up an unrelated `value` in another function. The textual highlighter stays as the fallback\n * for documents with no server.\n */\nexport class DocumentHighlightController {\n private timer: ReturnType<typeof setTimeout> | null = null\n private abort: AbortController | null = null\n private requestId = 0\n private painted = false\n private disposed = false\n\n public constructor(private readonly options: DocumentHighlightControllerOptions) {}\n\n public update(snapshot: EditorViewSnapshot, kind: EditorViewContributionUpdateKind): void {\n if (kind === 'document' || kind === 'clear') {\n this.clear()\n return\n }\n if (kind !== 'selection' && kind !== 'content') return\n\n const primary = snapshot.selections[0]\n // A dragged selection has its own meaning; only a resting caret asks \"where else is this used\".\n if (!primary || primary.startOffset !== primary.endOffset) {\n this.clear()\n return\n }\n\n this.schedule(primary.headOffset)\n }\n\n public dispose(): void {\n if (this.disposed) return\n\n this.disposed = true\n this.clear()\n }\n\n private schedule(offset: number): void {\n this.cancel()\n /**\n * @justification Debounces a request to the language server against the caret, not against\n * rendering, and `cancel()` clears it on every move — so the server sees one question per\n * pause rather than one per keystroke.\n */\n this.timer = setTimeout(() => {\n this.timer = null\n void this.request(offset)\n }, DOCUMENT_HIGHLIGHT_DEBOUNCE_MS)\n }\n\n private cancel(): void {\n if (this.timer) clearTimeout(this.timer)\n this.timer = null\n this.abort?.abort()\n this.abort = null\n }\n\n private async request(offset: number): Promise<void> {\n const active = this.options.getActiveDocument()\n if (!active) return this.clear()\n if (!this.options.router.hasReady('documentHighlights', 'textDocument/documentHighlight')) {\n return\n }\n\n const abort = new AbortController()\n const requestId = this.requestId + 1\n this.requestId = requestId\n this.abort = abort\n\n try {\n const highlights = await this.options.router.request<lsp.DocumentHighlight[] | null>(\n 'textDocument/documentHighlight',\n {\n position: offsetToLspPositionInSnapshot(active, offset),\n textDocument: { uri: active.uri },\n },\n { signal: abort.signal },\n )\n if (requestId !== this.requestId) return\n if (this.disposed) return\n if (active !== this.options.getActiveDocument()) return\n\n this.paint(active, highlights)\n } catch (error) {\n this.options.onRequestError(error)\n }\n }\n\n private paint(active: ActiveDocument, highlights: lsp.DocumentHighlight[] | null): void {\n const ranges = (highlights ?? []).map((highlight) => ({\n end: lspPositionToOffsetInSnapshot(active, highlight.range.end),\n start: lspPositionToOffsetInSnapshot(active, highlight.range.start),\n }))\n // A lone highlight is the symbol the caret is already in — painting it says nothing.\n if (ranges.length < 2) {\n this.clear()\n return\n }\n\n this.painted = true\n this.options.context.setRangeHighlight(this.options.highlightName, ranges, {\n backgroundColor: 'rgba(128, 128, 128, 0.18)',\n })\n }\n\n private clear(): void {\n this.cancel()\n if (!this.painted) return\n\n this.painted = false\n this.options.context.clearRangeHighlight(this.options.highlightName)\n }\n}\n"],"mappings":";;;AAaA,IAAM,iCAAiC;;;;;;;;AAiBvC,IAAa,8BAAb,MAAyC;CAOH;CANpC,QAAsD;CACtD,QAAwC;CACxC,YAAoB;CACpB,UAAkB;CAClB,WAAmB;CAEnB,YAAmB,SAA8D;EAA7C,KAAA,UAAA;CAA8C;CAElF,OAAc,UAA8B,MAA8C;EACxF,IAAI,SAAS,cAAc,SAAS,SAAS;GAC3C,KAAK,MAAM;GACX;EACF;EACA,IAAI,SAAS,eAAe,SAAS,WAAW;EAEhD,MAAM,UAAU,SAAS,WAAW;EAEpC,IAAI,CAAC,WAAW,QAAQ,gBAAgB,QAAQ,WAAW;GACzD,KAAK,MAAM;GACX;EACF;EAEA,KAAK,SAAS,QAAQ,UAAU;CAClC;CAEA,UAAuB;EACrB,IAAI,KAAK,UAAU;EAEnB,KAAK,WAAW;EAChB,KAAK,MAAM;CACb;CAEA,SAAiB,Q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Q,IAAI,gBAAgB;EAClC,MAAM,YAAY,KAAK,YAAY;EACnC,KAAK,YAAY;EACjB,KAAK,QAAQ;EAEb,IAAI;GACF,MAAM,aAAa,MAAM,KAAK,QAAQ,OAAO,QAC3C,kCACA;IACE,UAAU,8BAA8B,QAAQ,MAAM;IACtD,cAAc,EAAE,KAAK,OAAO,IAAI;GAClC,GACA,EAAE,QAAQ,MAAM,OAAO,CACzB;GACA,IAAI,cAAc,KAAK,WAAW;GAClC,IAAI,KAAK,UAAU;GACnB,IAAI,WAAW,KAAK,QAAQ,kBAAkB,GAAG;GAEjD,KAAK,MAAM,QAAQ,UAAU;EAC/B,SAAS,OAAO;GACd,KAAK,QAAQ,eAAe,KAAK;EACnC;CACF;CAEA,MAAc,QAAwB,YAAkD;EACtF,MAAM,UAAU,cAAc,CAAC,EAAA,CAAG,KAAK,eAAe;GACpD,KAAK,8BAA8B,QAAQ,UAAU,MAAM,GAAG;GAC9D,OAAO,8BAA8B,QAAQ,UAAU,MAAM,KAAK;EACpE,EAAE;EAEF,IAAI,OAAO,SAAS,GAAG;GACrB,KAAK,MAAM;GACX;EACF;EAEA,KAAK,UAAU;EACf,KAAK,QAAQ,QAAQ,kBAAkB,KAAK,QAAQ,eAAe,QAAQ,EACzE,iBAAiB,4BACnB,CAAC;CACH;CAEA,QAAsB;EACpB,KAAK,OAAO;EACZ,IAAI,CAAC,KAAK,SAAS;EAEnB,KAAK,UAAU;EACf,KAAK,QAAQ,QAAQ,oBAAoB,KAAK,QAAQ,aAAa;CACrE;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"documentSnapshot.js","names":[],"sources":["../src/documentSnapshot.ts"],"sourcesContent":["import type { EditorTextBuffer, EditorTextBufferChange } from '@singapore-editor/core/document'\nimport type { LanguageServerDocumentSnapshot } from './types'\n\nexport function bufferDocumentSnapshot({\n buffer,\n documentId,\n uri,\n languageId,\n publication,\n}: {\n readonly buffer: EditorTextBuffer\n readonly documentId?: string\n readonly uri: string\n readonly languageId: string\n readonly publication?: EditorTextBufferChange\n}): LanguageServerDocumentSnapshot {\n const textSnapshot = publication?.change.textSnapshot ?? buffer.getTextSnapshot()\n const point = publication?.syncPointAfter ?? buffer.getDocumentSyncPoint()\n const lineStartsView = {\n length: textSnapshot.lineCount,\n at: (index: number) =>\n index < 0 || index >= textSnapshot.lineCount ? undefined : textSnapshot.lineStart(index),\n indexForOffset: (offset: number) => textSnapshot.lineAt(offset),\n firstIndexAtOrAfter: (offset: number) => {\n const index = textSnapshot.lineAt(offset)\n return textSnapshot.lineStart(index) < offset ? index + 1 : index\n },\n toArray: () =>\n Array.from({ length: textSnapshot.lineCount }, (_, index) => textSnapshot.lineStart(index)),\n }\n return {\n documentId: documentId ?? uri,\n languageId,\n textSnapshot,\n textVersion: point.textVersion,\n documentSyncPoint: point,\n changesSinceDocumentSyncPoint: (previous, scope) =>\n publication\n ? publication.changesSinceDocumentSyncPoint(previous, scope)\n : buffer.changesSinceDocumentSyncPoint(previous, scope),\n lineStartsView,\n get lineStarts() {\n return lineStartsView.toArray()\n },\n }\n}\n"],"mappings":";AAGA,SAAgB,uBAAuB,EACrC,QACA,YACA,KACA,YACA,eAOiC;CACjC,MAAM,eAAe,aAAa,OAAO,gBAAgB,OAAO,gBAAgB;CAChF,MAAM,QAAQ,aAAa,kBAAkB,OAAO,qBAAqB;CACzE,MAAM,iBAAiB;EACrB,QAAQ,aAAa;EACrB,KAAK,UACH,QAAQ,KAAK,SAAS,aAAa,YAAY,KAAA,IAAY,aAAa,UAAU,KAAK;EACzF,iBAAiB,WAAmB,aAAa,OAAO,MAAM;EAC9D,sBAAsB,WAAmB;GACvC,MAAM,QAAQ,aAAa,OAAO,MAAM;GACxC,OAAO,aAAa,UAAU,KAAK,IAAI,SAAS,QAAQ,IAAI;EAC9D;EACA,eACE,MAAM,KAAK,EAAE,QAAQ,aAAa,UAAU,IAAI,GAAG,UAAU,aAAa,UAAU,KAAK,CAAC;CAC9F;CACA,OAAO;EACL,YAAY,cAAc;EAC1B;EACA;EACA,aAAa,MAAM;EACnB,mBAAmB;EACnB,gCAAgC,UAAU,UACxC,cACI,YAAY,8BAA8B,UAAU,KAAK,IACzD,OAAO,8BAA8B,UAAU,KAAK;EAC1D;EACA,IAAI,aAAa;GACf,OAAO,eAAe,QAAQ;EAChC;CACF;AACF"}
1
+ {"version":3,"file":"documentSnapshot.js","names":[],"sources":["../src/documentSnapshot.ts"],"mappings":";AAGA,SAAgB,uBAAuB,EACrC,QACA,YACA,KACA,YACA,eAOiC;CACjC,MAAM,eAAe,aAAa,OAAO,gBAAgB,OAAO,gBAAgB;CAChF,MAAM,QAAQ,aAAa,kBAAkB,OAAO,qBAAqB;CACzE,MAAM,iBAAiB;EACrB,QAAQ,aAAa;EACrB,KAAK,UACH,QAAQ,KAAK,SAAS,aAAa,YAAY,KAAA,IAAY,aAAa,UAAU,KAAK;EACzF,iBAAiB,WAAmB,aAAa,OAAO,MAAM;EAC9D,sBAAsB,WAAmB;GACvC,MAAM,QAAQ,aAAa,OAAO,MAAM;GACxC,OAAO,aAAa,UAAU,KAAK,IAAI,SAAS,QAAQ,IAAI;EAC9D;EACA,eACE,MAAM,KAAK,EAAE,QAAQ,aAAa,UAAU,IAAI,GAAG,UAAU,aAAa,UAAU,KAAK,CAAC;CAC9F;CACA,OAAO;EACL,YAAY,cAAc;EAC1B;EACA;EACA,aAAa,MAAM;EACnB,mBAAmB;EACnB,gCAAgC,UAAU,UACxC,cACI,YAAY,8BAA8B,UAAU,KAAK,IACzD,OAAO,8BAA8B,UAAU,KAAK;EAC1D;EACA,IAAI,aAAa;GACf,OAAO,eAAe,QAAQ;EAChC;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"documentSync.js","names":[],"sources":["../src/documentSync.ts"],"sourcesContent":["import type { LanguageServerDocumentSnapshot, LanguageServerDocumentSyncOptions } from './types'\nimport type {\n DocumentLogicalRevisionScope,\n DocumentSyncSegment,\n} from '@singapore-editor/core/document'\nimport type { EditorViewContributionUpdateKind } from '@singapore-editor/core/extensions'\nimport type { LspTextDocumentSnapshot, LspWorkspace } from '@singapore-editor/lsp'\nimport type * as lsp from 'vscode-languageserver-protocol'\nimport { projectDiagnosticsInSnapshot } from './diagnosticProjection'\nimport type { LanguageServerDocumentUriTransition } from './documentSyncController'\nimport { pathOrUriToDocumentUri } from './paths'\nimport type { ActiveDocument, DocumentDescriptor } from './pluginTypes'\nimport { viewDocumentSnapshot } from './viewDocumentSnapshot'\nimport {\n observeLanguageServerSource,\n retainLanguageServerSource,\n type LanguageServerSourceConnection,\n type LanguageServerSourceOwner,\n type LanguageServerSourcePublication,\n} from './retainedSource'\n\nexport type DocumentSyncSummaryKind = 'result' | 'reset'\nexport type DocumentSyncDiagnosticsPresenter = {\n clear(): void\n render(document: LspTextDocumentSnapshot, diagnostics: readonly lsp.Diagnostic[]): void\n publishSummary(\n uri: lsp.DocumentUri,\n version: number | null,\n diagnostics: readonly lsp.Diagnostic[],\n kind: DocumentSyncSummaryKind,\n ): void\n}\nexport type DocumentSyncOptions = LanguageServerDocumentSyncOptions & {\n readonly logicalRevisionScope: DocumentLogicalRevisionScope\n getSourceOwner(): LanguageServerSourceOwner | null\n getConnection(): LanguageServerSourceConnection | null\n onDocumentClosed(): void\n onDocumentChanged(): void\n onError(error: unknown): void\n}\ntype SourceLease = NonNullable<ReturnType<typeof retainLanguageServerSource>>\ntype Binding = {\n readonly source: LanguageServerSourceOwner\n readonly connection: LanguageServerSourceConnection\n readonly uri: string\n readonly languageId: string\n readonly lease: SourceLease\n}\ntype UriProjection = {\n readonly fromUri: string\n readonly toUri: string\n readonly segment: DocumentSyncSegment\n readonly previousSegment: DocumentSyncSegment\n}\n\nexport class DocumentSync {\n private binding: Binding | null = null\n private document: ActiveDocument | null = null\n private diagnosticItems: readonly lsp.Diagnostic[] = []\n private pendingUriProjection: UriProjection | null = null\n private readonly unsubscribe: () => void\n\n constructor(\n private readonly workspace: LspWorkspace,\n private readonly presenter: DocumentSyncDiagnosticsPresenter,\n private readonly options: DocumentSyncOptions,\n ) {\n this.unsubscribe = observeLanguageServerSource(workspace, {\n deliver: this.adoptPublication,\n onError: options.onError,\n })\n }\n get activeDocument(): ActiveDocument | null {\n return this.document\n }\n get diagnostics(): readonly lsp.Diagnostic[] {\n return this.diagnosticItems\n }\n\n shouldSync(\n kind: EditorViewContributionUpdateKind,\n snapshot: LanguageServerDocumentSnapshot,\n ): boolean {\n if (kind === 'document' || kind === 'content' || kind === 'clear') return true\n const descriptor = this.descriptor(snapshot)\n return (\n descriptor?.uri !== this.binding?.uri || descriptor?.languageId !== this.binding?.languageId\n )\n }\n\n async sync(snapshot: LanguageServerDocumentSnapshot): Promise<void> {\n const descriptor = this.descriptor(snapshot)\n const source = this.options.getSourceOwner()\n const connection = this.options.getConnection()\n if (!descriptor || !source || !connection) {\n this.detach()\n return\n }\n const binding = this.bind(source, connection, descriptor)\n await binding?.lease.request()\n }\n\n close(): void {\n this.pendingUriProjection = null\n this.detach()\n }\n dispose(): void {\n this.unsubscribe()\n this.close()\n }\n\n transitionDocumentUri(\n snapshot: LanguageServerDocumentSnapshot,\n transition: LanguageServerDocumentUriTransition,\n ): boolean {\n const active = this.document\n const binding = this.binding\n if (!active || !binding || active.uri !== transition.fromUri) return false\n if (active.sourceSegment !== transition.previousSyncPoint.segment) return false\n if (active.sourceRevision > transition.previousSyncPoint.revision) return false\n if (\n transition.previousSyncPoint.revision !== transition.syncPoint.revision ||\n transition.previousSyncPoint.textVersion !== transition.syncPoint.textVersion\n )\n return false\n if (transition.previousSyncPoint.segment === transition.syncPoint.segment) return false\n const descriptor = documentDescriptor(snapshot, this.options, transition.toUri)\n if (!descriptor) {\n this.close()\n return true\n }\n this.pendingUriProjection = {\n fromUri: documentUri(snapshot, this.options) ?? transition.fromUri,\n toUri: transition.toUri,\n segment: transition.syncPoint.segment,\n previousSegment: transition.previousSyncPoint.segment,\n }\n const source = this.options.getSourceOwner()\n const connection = this.options.getConnection()\n if (!source || !connection) {\n this.detach()\n return true\n }\n const next = this.bind(source, connection, descriptor)\n void next?.lease.request().catch(this.options.onError)\n return true\n }\n\n publishDiagnostics(params: unknown): void {\n const diagnostics = publishDiagnosticsParams(params)\n const active = this.document\n if (!diagnostics || !active || diagnostics.uri !== active.uri) return\n if (diagnostics.version !== null && diagnostics.version !== active.lspVersion) return\n this.replaceDiagnostics(active, diagnostics.version, diagnostics.diagnostics)\n }\n pullDiagnostics(\n uri: lsp.DocumentUri,\n version: number,\n diagnostics: readonly lsp.Diagnostic[],\n ): void {\n const active = this.document\n if (!active || active.uri !== uri || active.lspVersion !== version) return\n this.replaceDiagnostics(active, version, diagnostics)\n }\n clearDiagnostics(): void {\n const active = this.document\n this.diagnosticItems = []\n this.presenter.clear()\n if (active) this.presenter.publishSummary(active.uri, active.lspVersion, [], 'reset')\n }\n\n private descriptor(snapshot: LanguageServerDocumentSnapshot): DocumentDescriptor | null {\n const projection = this.pendingUriProjection\n const uri = documentUri(snapshot, this.options)\n if (\n projection &&\n uri === projection.fromUri &&\n (snapshot.documentSyncPoint.segment === projection.segment ||\n snapshot.documentSyncPoint.segment === projection.previousSegment)\n )\n return documentDescriptor(snapshot, this.options, projection.toUri)\n this.pendingUriProjection = null\n return documentDescriptor(snapshot, this.options)\n }\n private bind(\n source: LanguageServerSourceOwner,\n connection: LanguageServerSourceConnection,\n descriptor: DocumentDescriptor,\n ): Binding | null {\n const previous = this.binding\n if (\n previous &&\n sameOwner(previous.source, source) &&\n previous.connection === connection &&\n previous.uri === descriptor.uri &&\n previous.languageId === descriptor.languageId\n )\n return previous\n this.detach()\n const lease = retainLanguageServerSource({\n ...source,\n workspace: this.workspace,\n uri: descriptor.uri,\n languageId: descriptor.languageId,\n logicalRevisionScope: this.options.logicalRevisionScope,\n connection,\n })\n this.binding = lease\n ? { source, connection, uri: descriptor.uri, languageId: descriptor.languageId, lease }\n : null\n return this.binding\n }\n private detach(): void {\n const binding = this.binding\n this.binding = null\n try {\n binding?.lease.dispose()\n } finally {\n this.clearDocument()\n }\n }\n private clearDocument(): void {\n const active = this.document\n this.document = null\n this.diagnosticItems = []\n this.options.onDocumentClosed()\n this.presenter.clear()\n if (active) this.presenter.publishSummary(active.uri, active.lspVersion, [], 'reset')\n }\n private readonly adoptPublication = (publication: LanguageServerSourcePublication): void => {\n if (publication.runtimeSessionId !== this.binding?.lease.runtimeSessionId) return\n const next = publication.document\n if (!next) {\n this.clearDocument()\n return\n }\n const previous = this.document\n if (\n previous?.sourceRevision === next.sourceRevision &&\n previous.sourceSegment === next.sourceSegment &&\n previous.lspVersion === next.version\n )\n return\n if (previous && previous.textSnapshot !== next.textSnapshot) {\n this.diagnosticItems = projectDiagnosticsInSnapshot(this.diagnosticItems, {\n previousDocument: previous,\n nextDocument: next,\n change: publication.edits ? { edits: publication.edits } : null,\n })\n }\n this.document = {\n ...next,\n textVersion: publication.point?.textVersion ?? 0,\n lspVersion: next.version,\n }\n this.presenter.render(this.document, this.diagnosticItems)\n this.options.onDocumentChanged()\n }\n private replaceDiagnostics(\n active: ActiveDocument,\n version: number | null,\n diagnostics: readonly lsp.Diagnostic[],\n ): void {\n this.diagnosticItems = diagnostics\n this.presenter.render(active, diagnostics)\n this.presenter.publishSummary(active.uri, version, diagnostics, 'result')\n }\n}\n\nfunction sameOwner(left: LanguageServerSourceOwner, right: LanguageServerSourceOwner): boolean {\n if ('buffer' in left && 'buffer' in right) return left.buffer === right.buffer\n if ('contributions' in left && 'contributions' in right)\n return left.contributions === right.contributions\n return false\n}\n\nfunction activeDocument(descriptor: DocumentDescriptor, lspVersion: number): ActiveDocument {\n return {\n uri: descriptor.uri,\n languageId: descriptor.languageId,\n textSnapshot: descriptor.textSnapshot,\n lineStarts: descriptor.lineStarts,\n textVersion: descriptor.textVersion,\n lspVersion,\n sourceRevision: descriptor.sourceRevision,\n sourceSegment: descriptor.sourceSegment,\n }\n}\n\nfunction documentUri(\n snapshot: LanguageServerDocumentSnapshot,\n options: LanguageServerDocumentSyncOptions,\n): lsp.DocumentUri | null {\n if (options.uriForDocument) return options.uriForDocument(snapshot)\n return snapshot.documentId ? pathOrUriToDocumentUri(snapshot.documentId) : null\n}\n\nfunction documentDescriptor(\n snapshot: LanguageServerDocumentSnapshot,\n options: LanguageServerDocumentSyncOptions,\n projectedUri?: lsp.DocumentUri,\n): DocumentDescriptor | null {\n if (!snapshot.languageId) return null\n if (options.shouldSyncLanguageId?.(snapshot.languageId, snapshot) === false) return null\n\n const resolvedUri = documentUri(snapshot, options)\n if (resolvedUri === null) return null\n const uri = projectedUri ?? resolvedUri\n if (options.shouldSyncUri?.(uri, snapshot) === false) return null\n\n const document = viewDocumentSnapshot(snapshot)\n return {\n uri,\n // `shouldSyncLanguageId` above still filters on the view's id, not this one.\n languageId: options.languageIdForDocument?.(snapshot.languageId, uri) ?? snapshot.languageId,\n textSnapshot: document.textSnapshot,\n lineStarts: document.lineStarts,\n textVersion: snapshot.textVersion,\n sourceRevision: snapshot.documentSyncPoint.revision,\n sourceSegment: snapshot.documentSyncPoint.segment,\n }\n}\n\nexport function activeDocumentForSnapshot(\n snapshot: LanguageServerDocumentSnapshot,\n options: LanguageServerDocumentSyncOptions,\n): ActiveDocument | null {\n const descriptor = documentDescriptor(snapshot, options)\n return descriptor ? activeDocument(descriptor, 0) : null\n}\n\nfunction publishDiagnosticsParams(params: unknown): {\n readonly uri: lsp.DocumentUri\n readonly version: number | null\n readonly diagnostics: readonly lsp.Diagnostic[]\n} | null {\n if (!isRecord(params)) return null\n if (typeof params.uri !== 'string') return null\n if (!Array.isArray(params.diagnostics)) return null\n\n return {\n uri: params.uri,\n version: typeof params.version === 'number' ? params.version : null,\n diagnostics: params.diagnostics as lsp.Diagnostic[],\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n"],"mappings":";;;;;AAuDA,IAAa,eAAb,MAA0B;CAQL;CACA;CACA;CATnB,UAAkC;CAClC,WAA0C;CAC1C,kBAAqD,CAAC;CACtD,uBAAqD;C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Ae,SAAS,kBAAkB;CAC5C;AACF;AAEA,SAAgB,0BACd,UACA,SACuB;CACvB,MAAM,aAAa,mBAAmB,UAAU,OAAO;CACvD,OAAO,aAAa,eAAe,YAAY,CAAC,IAAI;AACtD;AAEA,SAAS,yBAAyB,QAIzB;CACP,IAAI,CAAC,SAAS,MAAM,GAAG,OAAO;CAC9B,IAAI,OAAO,OAAO,QAAQ,UAAU,OAAO;CAC3C,IAAI,CAAC,MAAM,QAAQ,OAAO,WAAW,GAAG,OAAO;CAE/C,OAAO;EACL,KAAK,OAAO;EACZ,SAAS,OAAO,OAAO,YAAY,WAAW,OAAO,UAAU;EAC/D,aAAa,OAAO;CACtB;AACF;AAEA,IAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK"}
@@ -1 +1 @@
1
- {"version":3,"file":"documentSyncController.js","names":[],"sources":["../src/documentSyncController.ts"],"sourcesContent":["import type { LanguageServerDocumentSnapshot } from './types'\nimport type { DocumentSyncPoint } from '@singapore-editor/core/document'\nimport type { EditorDisposable } from '@singapore-editor/core/extensions'\nimport type * as lsp from 'vscode-languageserver-protocol'\n\nimport type { DocumentSync } from './documentSync'\n\nexport type LanguageServerDocumentUriTransition = {\n readonly fromUri: lsp.DocumentUri\n readonly toUri: lsp.DocumentUri\n readonly previousSyncPoint: DocumentSyncPoint\n readonly syncPoint: DocumentSyncPoint\n}\n\nexport type LanguageServerDocumentSyncControllerRegistration = {\n readonly getSnapshot: () => LanguageServerDocumentSnapshot\n readonly sync: DocumentSync\n}\n\n/**\n * Projects a live document identity change through every mounted language-server lane immediately.\n */\nexport class LanguageServerDocumentSyncController {\n private readonly registrations = new Set<LanguageServerDocumentSyncControllerRegistration>()\n\n public register(\n registration: LanguageServerDocumentSyncControllerRegistration,\n ): EditorDisposable {\n this.registrations.add(registration)\n return {\n dispose: () => this.registrations.delete(registration),\n }\n }\n\n public transitionDocumentUri(transition: LanguageServerDocumentUriTransition): void {\n for (const registration of this.registrations) {\n registration.sync.transitionDocumentUri(registration.getSnapshot(), transition)\n }\n }\n}\n"],"mappings":";;;;AAsBA,IAAa,uCAAb,MAAkD;CAChD,gCAAiC,IAAI,IAAsD;CAE3F,SACE,cACkB;EAClB,KAAK,cAAc,IAAI,YAAY;EACnC,OAAO,EACL,eAAe,KAAK,cAAc,OAAO,YAAY,EACvD;CACF;CAEA,sBAA6B,YAAuD;EAClF,KAAK,MAAM,gBAAgB,KAAK,eAC9B,aAAa,KAAK,sBAAsB,aAAa,YAAY,GAAG,UAAU;CAElF;AACF"}
1
+ {"version":3,"file":"documentSyncController.js","names":[],"sources":["../src/documentSyncController.ts"],"mappings":";;;;AAsBA,IAAa,uCAAb,MAAkD;CAChD,gCAAiC,IAAI,IAAsD;CAE3F,SACE,cACkB;EAClB,KAAK,cAAc,IAAI,YAAY;EACnC,OAAO,EACL,eAAe,KAAK,cAAc,OAAO,YAAY,EACvD;CACF;CAEA,sBAA6B,YAAuD;EAClF,KAAK,MAAM,gBAAgB,KAAK,eAC9B,aAAa,KAAK,sBAAsB,aAAa,YAAY,GAAG,UAAU;CAElF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"formatOnType.js","names":[],"sources":["../src/formatOnType.ts"],"sourcesContent":["import type { TextEdit } from '@singapore-editor/core/document'\nimport {\n type EditorContributionChange,\n editorLanguageConfiguration,\n reindentEditsForRanges,\n type EditorCapabilityToken,\n type EditorLanguageConfiguration,\n type EditorViewContributionContext,\n type EditorViewContributionUpdateKind,\n type EditorViewSnapshot,\n} from '@singapore-editor/core/extensions'\n\nimport type { LanguageServerCompletionEditFeature } from './completion'\n\n/**\n * Putting the row the caret is on back at the level its own text asks for, on the keystroke that\n * changed which level that is.\n *\n * A closing delimiter is typed at the depth of the block it ends, one level in from where it\n * belongs, and nothing afterwards moves it — every closed block is left a level too deep until\n * somebody reindents the region by hand. The question \"where does this row belong\" is the one the\n * reindent commands ask of the language's indentation rules, so it is asked of them here too\n * rather than answered again beside them.\n *\n * Two narrow gates keep it from being a formatter that runs on every keystroke: which characters\n * are watched at all, and whether the answer is still about the document by the time it is written.\n * The second is a gate rather than a certainty because the edit is handed over a turn after it is\n * computed — a row cannot be rewritten from inside the announcement of the keystroke that produced\n * it.\n */\n\nexport type FormatOnTypeControllerOptions = {\n readonly context: EditorViewContributionContext\n readonly editFeature: EditorCapabilityToken<LanguageServerCompletionEditFeature>\n}\n\n/** An edit, and the document it was measured against. */\ntype PendingFormatOnType = {\n readonly caretOffset: number\n readonly edit: TextEdit\n readonly textVersion: number\n}\n\n/**\n * The text one row's level is decided from, and where it sits in the document.\n *\n * A row belongs one level in from the row above it, unless either of them is inside a string or a\n * comment — and which literals are open is only settled by reading from wherever they were opened.\n * Reading from the top of the document scans the whole file on a keystroke and goes on growing with\n * it; reading back a fixed distance costs the same in a file of any size, and the only text the two\n * answer differently for is a literal left open for longer than that distance.\n */\ntype FormatOnTypeWindow = {\n readonly text: string\n /** Where `text` starts, always at a row start so the rows inside it are the document's rows. */\n readonly start: number\n /** The caret, in the window's own offsets. */\n readonly caretOffset: number\n}\n\nconst FORMAT_ON_TYPE_WINDOW = 4096\n\nexport class FormatOnTypeController {\n private pending: PendingFormatOnType | null = null\n private scheduled = false\n private disposed = false\n\n public constructor(private readonly options: FormatOnTypeControllerOptions) {}\n\n public update(\n snapshot: EditorViewSnapshot,\n kind: EditorViewContributionUpdateKind,\n change: EditorContributionChange | null,\n ): void {\n if (kind === 'document' || kind === 'clear') {\n this.pending = null\n return\n }\n if (kind !== 'content') return\n\n this.carryPendingForward(snapshot, change)\n const caretOffset = formatOnTypeCaret(snapshot, change)\n if (caretOffset === null) return\n\n const pending = pendingFormatOnType(snapshot, caretOffset)\n if (!pending) return\n\n this.pending = pending\n this.schedule()\n }\n\n public dispose(): void {\n this.disposed = true\n this.pending = null\n }\n\n /**\n * Moves an edit onto the document an announced change has just produced, or drops it.\n *\n * Its range is a pair of offsets into one document. An edit arriving at or before the caret moves\n * them, and replacing what now sits there would take a bite out of text the reader wrote in the\n * meantime. An edit past the caret cannot reach the row's leading whitespace, so the answer still\n * holds — and re-stamping is how it goes on holding for a document that has legitimately moved on.\n */\n private carryPendingForward(\n snapshot: EditorViewSnapshot,\n change: EditorContributionChange | null,\n ): void {\n const pending = this.pending\n if (!pending || !change) return\n if (change.edits.some((edit) => edit.from <= pending.caretOffset)) {\n this.pending = null\n return\n }\n\n this.pending = { ...pending, textVersion: snapshot.textVersion }\n }\n\n private schedule(): void {\n if (this.scheduled) return\n\n this.scheduled = true\n /**\n * @justification Coalesces the re-indents a single keystroke can queue into one pass at the end\n * of the turn, so the edit lands before the frame the character was typed in is painted;\n * `scheduled` is what makes a second call in that turn a no-op rather than a second pass.\n */\n queueMicrotask(() => {\n this.scheduled = false\n this.applyPending()\n })\n }\n\n private applyPending(): void {\n const pending = this.pending\n this.pending = null\n if (!pending || this.disposed) return\n\n const snapshot = this.options.context.getSnapshot()\n // A pass opened from inside another one is not announced a second time, so the guard above\n // cannot have seen every edit. Reading the range back would only say that some whitespace still\n // sits at those numbers, which an unannounced edit shifting the buffer leaves true of a row the\n // reader never touched; the version is the one reading that counts every edit either way.\n if (snapshot.textVersion !== pending.textVersion) return\n\n const feature = this.options.context.getFeature(this.options.editFeature)\n if (!feature) return\n\n const head =\n pending.caretOffset + pending.edit.text.length - (pending.edit.to - pending.edit.from)\n feature.applyCompletion({ edits: [pending.edit], selection: { anchor: head, head } })\n }\n}\n\n/**\n * Where the caret sits after a keystroke that can have changed its row's level, or null for one\n * that cannot have.\n *\n * Several carets, or a caret with a selection behind it, describe an edit whose shape this cannot\n * read, so they ask for nothing.\n */\nfunction formatOnTypeCaret(\n snapshot: EditorViewSnapshot,\n change: EditorContributionChange | null,\n): number | null {\n if (!change || change.kind !== 'edit') return null\n if (change.edits.length !== 1) return null\n\n const edit = change.edits[0]\n if (!edit || edit.text.length !== 1) return null\n\n const configuration = ruledConfiguration(snapshot.languageId)\n if (!configuration) return null\n if (!triggerCharacters(configuration).has(edit.text)) return null\n\n if (snapshot.selections.length !== 1) return null\n const selection = snapshot.selections[0]\n if (!selection || selection.startOffset !== selection.endOffset) return null\n\n const caretOffset = selection.headOffset\n\n return caretOffset === edit.from + edit.text.length ? caretOffset : null\n}\n\n/** The rules for a language whose rows have levels at all; without them there is nothing to say. */\nfunction ruledConfiguration(languageId: string | null): EditorLanguageConfiguration | null {\n const configuration = editorLanguageConfiguration(languageId)\n\n return configuration?.indentationRules ? configuration : null\n}\n\nconst triggerCharactersByConfiguration = new WeakMap<\n EditorLanguageConfiguration,\n ReadonlySet<string>\n>()\n\n/**\n * The characters whose arrival can put a row at a different level than the one it was typed on.\n *\n * A row drops a level by holding the delimiter that closes a block, so the closers the language\n * describes are the whole set — which is also what keeps prose, which describes none, out of this\n * without a list of exemptions. The last character is what finishes a closer, so blocks that end in\n * a word are watched by the keystroke completing the word rather than the one starting it.\n *\n * Every other keystroke stops here, on one lookup, rather than going on to read the row. The set is\n * kept against the record it was read from and not against the language's name, so a host replacing\n * a language's rules gets a set built from the rules it replaced them with; there is no moment at\n * which a stale set can answer.\n */\nfunction triggerCharacters(configuration: EditorLanguageConfiguration): ReadonlySet<string> {\n const cached = triggerCharactersByConfiguration.get(configuration)\n if (cached) return cached\n\n const characters = new Set<string>()\n for (const pair of configuration.brackets) {\n const last = pair.close.at(-1)\n if (last !== undefined) characters.add(last)\n }\n\n triggerCharactersByConfiguration.set(configuration, characters)\n return characters\n}\n\n/**\n * Whether the closer ending at the caret is the whole of what its row holds.\n *\n * A closer that follows anything else was written to end an expression the row is carrying, not the\n * block the row sits in; moving the row would take that expression somewhere it was not put. Which\n * closer it is has to be decided here rather than from the single character typed, because a\n * multi-character delimiter is only itself once the whole of it is on the row.\n */\nfunction closesItsOwnRow(\n configuration: EditorLanguageConfiguration,\n window: FormatOnTypeWindow,\n): boolean {\n const rowStart = window.text.lastIndexOf('\\n', window.caretOffset - 1) + 1\n const before = window.text.slice(rowStart, window.caretOffset)\n\n return configuration.brackets.some(\n (pair) =>\n before.endsWith(pair.close) && isBlank(before.slice(0, before.length - pair.close.length)),\n )\n}\n\nfunction isBlank(text: string): boolean {\n return !/[^\\t ]/u.test(text)\n}\n\nfunction pendingFormatOnType(\n snapshot: EditorViewSnapshot,\n caretOffset: number,\n): PendingFormatOnType | null {\n const configuration = ruledConfiguration(snapshot.languageId)\n if (!configuration) return null\n\n const window = formatOnTypeWindow(snapshot, caretOffset)\n if (!window || !closesItsOwnRow(configuration, window)) return null\n\n const [edit] = reindentEditsForRanges(\n window.text,\n [{ end: window.caretOffset, start: window.caretOffset }],\n { languageId: snapshot.languageId, tabSize: snapshot.tabSize },\n )\n if (!edit) return null\n\n return {\n caretOffset,\n edit: { from: edit.from + window.start, text: edit.text, to: edit.to + window.start },\n textVersion: snapshot.textVersion,\n }\n}\n\n/**\n * Whole rows back to the bound, and the caret's own row through to its end.\n *\n * The row is read to its end rather than to the caret because a language's rules are patterns over\n * the whole of it, and a closer with anything behind it on the row is a row that describes something\n * other than the block it sits in. A caret standing further than the bound from a row start has\n * nothing above it this can read, and says so rather than measuring against half a row.\n */\nfunction formatOnTypeWindow(\n snapshot: EditorViewSnapshot,\n caretOffset: number,\n): FormatOnTypeWindow | null {\n const source = snapshot.textSnapshot\n const length = source.length\n const read = (start: number, end: number): string => source.readRange(start, end)\n\n const from = Math.max(0, caretOffset - FORMAT_ON_TYPE_WINDOW)\n const before = read(from, caretOffset)\n const firstBreak = before.indexOf('\\n')\n if (from > 0 && firstBreak === -1) return null\n\n const start = from === 0 ? 0 : from + firstBreak + 1\n const after = read(caretOffset, Math.min(length, caretOffset + FORMAT_ON_TYPE_WINDOW))\n const rowEnd = after.indexOf('\\n')\n\n return {\n text: before.slice(start - from) + (rowEnd === -1 ? after : after.slice(0, rowEnd)),\n start,\n caretOffset: caretOffset - start,\n }\n}\n"],"mappings":";;AA4DA,IAAM,wBAAwB;AAE9B,IAAa,yBAAb,MAAoC;CAKE;CAJpC,UAA8C;CAC9C,YAAoB;CACp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S,KAAK,MAAM,WAAW;CACrC,MAAM,aAAa,OAAO,QAAQ,IAAI;CACtC,IAAI,OAAO,KAAK,eAAe,IAAI,OAAO;CAE1C,MAAM,QAAQ,SAAS,IAAI,IAAI,OAAO,aAAa;CACnD,MAAM,QAAQ,KAAK,aAAa,KAAK,IAAI,QAAQ,cAAc,qBAAqB,CAAC;CACrF,MAAM,SAAS,MAAM,QAAQ,IAAI;CAEjC,OAAO;EACL,MAAM,OAAO,MAAM,QAAQ,IAAI,KAAK,WAAW,KAAK,QAAQ,MAAM,MAAM,GAAG,MAAM;EACjF;EACA,aAAa,cAAc;CAC7B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"formatting.js","names":[],"sources":["../src/formatting.ts"],"sourcesContent":["import type * as lsp from 'vscode-languageserver-protocol'\n\nimport type { TextEdit } from '@singapore-editor/core'\nimport {\n lspPositionToOffsetInSnapshot,\n type LspTextDocumentSnapshot,\n type LspTextSnapshot,\n} from '@singapore-editor/lsp'\n\nimport { minimalReplacementEdits, REDIFF_LENGTH_LIMIT } from './minimalEdits'\n\n/**\n * Converts server formatting edits into buffer edits.\n *\n * Returned in descending order and with overlaps dropped, because the batch applicator rejects\n * overlapping edits outright — a formatter that returns a whole-document edit plus a nested one\n * would otherwise throw rather than format.\n *\n * What survives is re-diffed against the text it replaces, so a reply that rewrites the document to\n * change one line touches only that line.\n */\nexport function prepareFormattingEdits(\n document: LspTextDocumentSnapshot,\n edits: readonly lsp.TextEdit[] | null,\n): TextEdit[] {\n if (!edits || edits.length === 0) return []\n\n const converted = edits\n .map((edit) => ({\n from: lspPositionToOffsetInSnapshot(document, edit.range.start),\n text: edit.newText,\n to: lspPositionToOffsetInSnapshot(document, edit.range.end),\n }))\n .filter((edit) => edit.from <= edit.to)\n // Earliest first, and the longest of any that start together: when a formatter sends a\n // whole-document edit alongside a nested one, the outer edit is the real answer and keeping the\n // fragment instead would rewrite a slice of the file with a slice of the result.\n .sort((left, right) => left.from - right.from || right.to - left.to)\n\n const applied: TextEdit[] = []\n let keptThrough = Number.NEGATIVE_INFINITY\n for (const edit of converted) {\n if (edit.from < keptThrough) continue\n\n const previous = applied[applied.length - 1]\n // Edits that meet are joined first: two fragments that cancel each other out are invisible\n // while they are compared apart. Joining stops at the length past which the comparison is\n // skipped anyway, where a wider span would only buy a wider rewrite.\n if (previous && previous.to === edit.from && joinFitsRediff(previous, edit)) {\n applied[applied.length - 1] = {\n from: previous.from,\n text: previous.text + edit.text,\n to: edit.to,\n }\n } else {\n applied.push(edit)\n }\n keptThrough = edit.to\n }\n\n const minimal = applied.flatMap((edit) =>\n minimalReplacementEdits(\n document.textSnapshot.readRange(edit.from, edit.to),\n edit.text,\n edit.from,\n ),\n )\n\n // Descending, so applying them in order cannot shift the offsets of the ones still to come.\n return minimal.reverse()\n}\n\nfunction joinFitsRediff(left: TextEdit, right: TextEdit): boolean {\n const joined = Math.max(right.to - left.from, left.text.length + right.text.length)\n return joined <= REDIFF_LENGTH_LIMIT\n}\n\n/** Whether the edits would leave the document unchanged, so a no-op formatter records no change. */\nexport function formattingChangesText(text: LspTextSnapshot, edits: readonly TextEdit[]): boolean {\n return edits.some((edit) => text.readRange(edit.from, edit.to) !== edit.text)\n}\n\nexport function formattingOptions(tabSize: number): lsp.FormattingOptions {\n return {\n insertSpaces: true,\n tabSize: Math.max(1, tabSize),\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAqBA,SAAgB,uBACd,UACA,OACY;CACZ,IAAI,CAAC,SAAS,MAAM,WAAW,GAAG,OAAO,CAAC;CAE1C,MAAM,YAAY,MACf,KAAK,UAAU;EACd,MAAM,8BAA8B,UAAU,KAAK,MAAM,KAAK;EAC9D,MAAM,KAAK;EACX,IAAI,8BAA8B,UAAU,KAAK,MAAM,GAAG;CAC5D,EAAE,CAAC,CACF,QAAQ,SAAS,KAAK,QAAQ,KAAK,EAAE,CAAC,CAItC,MAAM,MAAM,UAAU,KAAK,OAAO,MAAM,QAAQ,MAAM,KAAK,KAAK,EAAE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AC,CAItC,MAAM,MAAM,UAAU,KAAK,OAAO,MAAM,QAAQ,MAAM,KAAK,KAAK,EAAE;CAErE,MAAM,UAAsB,CAAC;CAC7B,IAAI,cAAc,OAAO;CACzB,KAAK,MAAM,QAAQ,WAAW;EAC5B,IAAI,KAAK,OAAO,aAAa;EAE7B,MAAM,WAAW,QAAQ,QAAQ,SAAS;EAI1C,IAAI,YAAY,SAAS,OAAO,KAAK,QAAQ,eAAe,UAAU,IAAI,GACxE,QAAQ,QAAQ,SAAS,KAAK;GAC5B,MAAM,SAAS;GACf,MAAM,SAAS,OAAO,KAAK;GAC3B,IAAI,KAAK;EACX;OAEA,QAAQ,KAAK,IAAI;EAEnB,cAAc,KAAK;CACrB;CAWA,OATgB,QAAQ,SAAS,SAC/B,wBACE,SAAS,aAAa,UAAU,KAAK,MAAM,KAAK,EAAE,GAClD,KAAK,MACL,KAAK,IACP,CAIK,CAAA,CAAQ,QAAQ;AACzB;AAEA,SAAS,eAAe,MAAgB,OAA0B;CAEhE,OADe,KAAK,IAAI,MAAM,KAAK,KAAK,MAAM,KAAK,KAAK,SAAS,MAAM,KAAK,MACrE,KAAU;AACnB;;AAGA,SAAgB,sBAAsB,MAAuB,OAAqC;CAChG,OAAO,MAAM,MAAM,SAAS,KAAK,UAAU,KAAK,MAAM,KAAK,EAAE,MAAM,KAAK,IAAI;AAC9E;AAEA,SAAgB,kBAAkB,SAAwC;CACxE,OAAO;EACL,cAAc;EACd,SAAS,KAAK,IAAI,GAAG,OAAO;CAC9B;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"fuzzyMatch.js","names":[],"sources":["../src/fuzzyMatch.ts"],"sourcesContent":["/*\n * Fuzzy matching of the word being typed against one candidate string.\n *\n * Two things come back from a match rather than one: how well it matched, and where. The positions\n * are what lets a list mark the characters an entry owes its place to, so the ranking can be read off\n * the screen instead of taken on trust.\n *\n * Scoring is a table walk, and its cost is bounded on both axes. Strings are matched up to a fixed\n * length, so a minified bundle arriving as one enormous label costs what any other label costs. And\n * each row only visits the positions its character could possibly match at — no earlier than a\n * forward subsequence scan reaches it, no later than a backward one does — which on a long candidate\n * is a narrow band rather than the whole string.\n */\n\nexport type FuzzyMatch = {\n readonly score: number\n /** Indices into the candidate that the pattern matched, ascending. */\n readonly positions: readonly number[]\n}\n\nconst MAX_PATTERN_LENGTH = 64\nconst MAX_CANDIDATE_LENGTH = 128\n/** How many leading pattern characters a loose match may give up before it stops trying. */\nconst MAX_LOOSE_ATTEMPTS = 13\n\nconst NO_MATCH = Number.MIN_SAFE_INTEGER\n\n/** A character where the user's typing meets the candidate's own structure. */\nconst POSITION_PREFIX = 0\nconst POSITION_CAMEL = 1\nconst POSITION_SEPARATOR = 2\nconst POSITION_AFTER_SEPARATOR = 3\nconst POSITION_INSIDE_WORD = 4\n\nconst STEP_MATCH = 1\nconst STEP_SKIP_ONE = 2\nconst STEP_SKIP_TWO = 3\n\nconst TABLE_COLUMNS = MAX_CANDIDATE_LENGTH + 1\nconst TABLE_CELLS = (MAX_PATTERN_LENGTH + 1) * TABLE_COLUMNS\n\n/*\n * Every item of a list is scored on every keystroke, so the tables are reused across calls instead of\n * allocated per candidate. Row zero is never written, and every read of it is a boundary read that\n * wants the zero it was created with.\n */\nconst cellScores = new Int32Array(TABLE_CELLS)\nconst cellRunLengths = new Int32Array(TABLE_CELLS)\nconst cellSteps = new Uint8Array(TABLE_CELLS)\nconst earliestPositions = new Int32Array(MAX_PATTERN_LENGTH)\nconst latestPositions = new Int32Array(MAX_PATTERN_LENGTH)\n\n/** Where a candidate visibly breaks, and so where a match may resume without reading as scattered. */\nconst SEPARATORS = new Set('_-. /\\\\\\'\":$<>()[]{}#@')\n\n/**\n * The match of the whole pattern, or null when there is none.\n *\n * The first character has to land somewhere the candidate begins something — its start, a camel-case\n * hump, the far side of a separator. A pattern that only turns up in the middle of a word is a\n * coincidence rather than what the user was reaching for.\n */\nexport function fuzzyMatch(pattern: string, candidate: string): FuzzyMatch | null {\n return matchFrom(pattern, pattern.toLowerCase(), 0, candidate, candidate.toLowerCase(), false)\n}\n\n/**\n * The match of the pattern, or of what is left of it after dropping leading characters, at any\n * alignment at all.\n *\n * For a string the pattern was never ranked against there is no reason for all of it to be present,\n * and marking the part that is beats marking nothing.\n */\nexport function looseFuzzyMatch(pattern: string, candidate: string): FuzzyMatch | null {\n const patternLow = pattern.toLowerCase()\n const candidateLow = candidate.toLowerCase()\n const attempts = Math.min(pattern.length, MAX_LOOSE_ATTEMPTS)\n for (let start = 0; start < attempts; start += 1) {\n const match = matchFrom(pattern, patternLow, start, candidate, candidateLow, true)\n if (match) return match\n }\n\n return null\n}\n\nfunction matchFrom(\n pattern: string,\n patternLow: string,\n patternStart: number,\n candidate: string,\n candidateLow: string,\n allowWeakStart: boolean,\n): FuzzyMatch | null {\n const patternEnd = Math.min(pattern.length, MAX_PATTERN_LENGTH)\n const candidateEnd = Math.min(candidate.length, MAX_CANDIDATE_LENGTH)\n const patternLength = patternEnd - patternStart\n if (patternLength <= 0 || patternLength > candidateEnd) return null\n if (!fillEarliestPositions(patternLow, patternStart, patternEnd, candidateLow, candidateEnd)) {\n return null\n }\n\n fillLatestPositions(patternLow, patternStart, patternEnd, candidateLow, candidateEnd)\n\n let startsAtBoundary = false\n for (let patternPos = patternStart, row = 1; patternPos < patternEnd; patternPos += 1, row += 1) {\n const earliest = earliestPositions[patternPos] ?? 0\n const latest = latestPositions[patternPos] ?? 0\n // A row runs past its own last matchable position up to the next character's, because that is the\n // cell the next row reads to its left.\n const rowEnd =\n patternPos + 1 < patternEnd ? (latestPositions[patternPos + 1] ?? 0) : candidateEnd\n const isFirst = patternPos === patternStart\n\n for (let position = earliest; position < rowEnd; position += 1) {\n const cell = row * TABLE_COLUMNS + position + 1\n const diagonal = cell - TABLE_COLUMNS - 1\n\n let matched = NO_MATCH\n if (position <= latest && patternLow[patternPos] === candidateLow[position]) {\n const kind = positionKind(candidate, candidateLow, position, patternPos - patternStart)\n matched = characterScore(\n kind,\n isGapPosition(kind, candidate, candidateLow, position),\n pattern[patternPos] === candidate[position],\n isFirst,\n position,\n candidateEnd,\n (cellRunLengths[diagonal] ?? 0) === 0,\n )\n if (isFirst && kind !== POSITION_INSIDE_WORD) startsAtBoundary = true\n }\n\n const matchScore = matched === NO_MATCH ? 0 : matched + (cellScores[diagonal] ?? 0)\n const canSkipOne = position > earliest\n const skipOneScore = canSkipOne ? (cellScores[cell - 1] ?? 0) - gapStartPenalty(cell - 1) : 0\n const canSkipTwo = position > earliest + 1 && (cellRunLengths[cell - 1] ?? 0) > 0\n const skipTwoScore = canSkipTwo ? (cellScores[cell - 2] ?? 0) - gapStartPenalty(cell - 2) : 0\n\n // Skipping is preferred on a tie because it leaves the match earlier in the candidate, and\n // skipping over a run of matches is preferred over skipping one character for the same reason.\n if (\n canSkipTwo &&\n skipTwoScore >= skipOneScore &&\n (matched === NO_MATCH || skipTwoScore >= matchScore)\n ) {\n cellScores[cell] = skipTwoScore\n cellSteps[cell] = STEP_SKIP_TWO\n cellRunLengths[cell] = 0\n } else if (canSkipOne && (matched === NO_MATCH || skipOneScore >= matchScore)) {\n cellScores[cell] = skipOneScore\n cellSteps[cell] = STEP_SKIP_ONE\n cellRunLengths[cell] = 0\n } else {\n // The earliest position of a row is a match by construction, so a row always has a diagonal\n // to fall back on here.\n cellScores[cell] = matchScore\n cellSteps[cell] = STEP_MATCH\n cellRunLengths[cell] = (cellRunLengths[diagonal] ?? 0) + 1\n }\n }\n }\n\n if (!startsAtBoundary && !allowWeakStart) return null\n\n return traceMatch(patternLow, patternStart, patternEnd, candidate, candidateLow, candidateEnd)\n}\n\n/**\n * A score cannot say where a match landed, so the positions are recovered by walking the filled table\n * back from its last cell — and the score is settled here too, where the reach of the match is\n * finally known.\n */\nfunction traceMatch(\n patternLow: string,\n patternStart: number,\n patternEnd: number,\n candidate: string,\n candidateLow: string,\n candidateEnd: number,\n): FuzzyMatch {\n const positions: number[] = []\n let row = patternEnd - patternStart\n let column = candidateEnd\n let score = cellScores[row * TABLE_COLUMNS + column] ?? 0\n let runLength = 0\n let lastMatchColumn = 0\n\n while (row >= 1) {\n let matchColumn = column\n while (matchColumn >= 1) {\n const step = cellSteps[row * TABLE_COLUMNS + matchColumn]\n if (step === STEP_SKIP_TWO) matchColumn -= 2\n else if (step === STEP_SKIP_ONE) matchColumn -= 1\n else break\n }\n\n // The table was filled left to right and is being read right to left; where the two disagree, the\n // longer unbroken run of matched characters is the one a reader of the list will see.\n if (\n runLength > 1 &&\n patternLow[patternStart + row - 1] === candidateLow[column - 1] &&\n !isUpperCaseAt(candidate, candidateLow, matchColumn - 1) &&\n runLength + 1 > (cellRunLengths[row * TABLE_COLUMNS + matchColumn] ?? 0)\n ) {\n matchColumn = column\n }\n\n runLength = matchColumn === column ? runLength + 1 : 1\n if (lastMatchColumn === 0) lastMatchColumn = matchColumn\n row -= 1\n column = matchColumn - 1\n positions.push(column)\n }\n\n positions.reverse()\n const patternLength = patternEnd - patternStart\n // A candidate the pattern covers entirely is what the user typed, so it comes ahead of anything the\n // pattern is only part of; every candidate character the match stepped over costs it a point.\n if (candidateEnd === patternLength) score += 2\n score -= lastMatchColumn - patternLength\n return { positions, score }\n}\n\n/**\n * Records, per pattern character, the earliest candidate position it can match at, and reports\n * whether the pattern occurs in the candidate at all.\n *\n * A candidate the pattern is not a subsequence of cannot match however it is scored, and this is a\n * linear scan against a table walk.\n */\nfunction fillEarliestPositions(\n patternLow: string,\n patternStart: number,\n patternEnd: number,\n candidateLow: string,\n candidateEnd: number,\n): boolean {\n let patternPos = patternStart\n let position = 0\n while (patternPos < patternEnd && position < candidateEnd) {\n if (patternLow[patternPos] === candidateLow[position]) {\n earliestPositions[patternPos] = position\n patternPos += 1\n }\n position += 1\n }\n\n return patternPos === patternEnd\n}\n\n/** Records, per pattern character, the latest candidate position it can match at. */\nfunction fillLatestPositions(\n patternLow: string,\n patternStart: number,\n patternEnd: number,\n candidateLow: string,\n candidateEnd: number,\n): void {\n let patternPos = patternEnd - 1\n let position = candidateEnd - 1\n while (patternPos >= patternStart && position >= 0) {\n if (patternLow[patternPos] === candidateLow[position]) {\n latestPositions[patternPos] = position\n patternPos -= 1\n }\n position -= 1\n }\n}\n\nfunction positionKind(\n candidate: string,\n candidateLow: string,\n position: number,\n prefixPosition: number,\n): number {\n if (position === prefixPosition) return POSITION_PREFIX\n if (\n isUpperCaseAt(candidate, candidateLow, position) &&\n !isUpperCaseAt(candidate, candidateLow, position - 1)\n ) {\n return POSITION_CAMEL\n }\n if (isSeparatorAt(candidateLow, position) && !isSeparatorAt(candidateLow, position - 1)) {\n return POSITION_SEPARATOR\n }\n if (isSeparatorAt(candidateLow, position - 1) || isWhitespaceAt(candidateLow, position - 1)) {\n return POSITION_AFTER_SEPARATOR\n }\n\n return POSITION_INSIDE_WORD\n}\n\n/**\n * Whether a gap would be forgivable at this position: the reader's eye already breaks the candidate\n * here, so a match that resumes here does not read as scattered.\n */\nfunction isGapPosition(\n kind: number,\n candidate: string,\n candidateLow: string,\n position: number,\n): boolean {\n if (kind === POSITION_CAMEL || kind === POSITION_AFTER_SEPARATOR) return true\n\n return (\n isUpperCaseAt(candidate, candidateLow, position) ||\n isSeparatorAt(candidateLow, position - 1) ||\n isWhitespaceAt(candidateLow, position - 1)\n )\n}\n\n/**\n * What one matched character is worth, which is most of the signal in a score.\n *\n * A character matched where the candidate begins something counts for several times one matched in\n * the middle of a word, and matching the case it is written in counts for more again: both are\n * things the user could only have typed deliberately.\n */\nfunction characterScore(\n kind: number,\n isGap: boolean,\n sameCase: boolean,\n isFirst: boolean,\n position: number,\n candidateEnd: number,\n startsRun: boolean,\n): number {\n let score = 1\n if (kind === POSITION_PREFIX || kind === POSITION_CAMEL) score = sameCase ? 7 : 5\n else if (kind === POSITION_SEPARATOR || kind === POSITION_AFTER_SEPARATOR) score = 5\n\n if (isFirst) {\n // What sits between the start of the candidate and the first matched character is the distance\n // between what was typed and what is being offered.\n if (position > 0) score -= isGap ? 3 : 5\n } else if (startsRun) {\n score += isGap ? 2 : 0\n } else {\n score += isGap ? 0 : 1\n }\n // Gaps are penalized everywhere, which would otherwise hand a free advantage to a match that runs\n // to the end of the candidate and has no room left to leave one.\n if (position + 1 === candidateEnd) score -= isGap ? 3 : 5\n\n return score\n}\n\nfunction gapStartPenalty(cell: number): number {\n return (cellRunLengths[cell] ?? 0) > 0 ? 5 : 0\n}\n\nfunction isUpperCaseAt(candidate: string, candidateLow: string, position: number): boolean {\n if (position < 0 || position >= candidate.length) return false\n\n return candidate[position] !== candidateLow[position]\n}\n\nfunction isSeparatorAt(candidateLow: string, position: number): boolean {\n if (position < 0 || position >= candidateLow.length) return false\n\n return SEPARATORS.has(candidateLow[position] ?? '')\n}\n\nfunction isWhitespaceAt(candidateLow: string, position: number): boolean {\n if (position < 0 || position >= candidateLow.length) return false\n\n const character = candidateLow[position]\n return character === ' ' || character === '\\t'\n}\n"],"mappings":";AAoBA,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;;AAE7B,IAAM,qBAAqB;AAE3B,IAAM,WAAW,OAAO;;AAGxB,IAAM,kBAAkB;AACxB,IAAM,iBAAiB;AACvB,IAAM,qBAAqB;AAC3B,IAAM,2BAA2B;AACjC,IAAM,uBAAuB;AAE7B,IAAM,aAAa;AACnB,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AAEtB,IAAM,gBAAgB;AACtB,IAAM,cAAA;AAON,IAAM,aAAa,IAAI,WAAW,WAAW;AAC7C,IAAM,iBAAiB,IAAI,WAAW,WAAW;AACjD,IAAM,YAAY,IAAI,WAAW,WAAW;AAC5C,IAAM,oBAAoB,IAAI,WAAW,kBAAkB;AAC3D,IAAM,kBAAkB,IAAI,WAAW,kBAAkB;;AAGzD,IAAM,6BAAa,IAAI,IAAI,wBAAwB;;;;;;;;AASnD,SAAgB,WAAW,SAAiB,WAAsC;CAChF,OAAO,UAAU,SAAS,QAAQ,YAAY,GAAG,GAAG,WAAW,UAAU,YAAY,GAAG,KAAK;AAC/F;;;;;;;;AASA,SAAgB,gBAAgB,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AAU,QAAQ,OAAO;CAEzD,OAAO,UAAU,cAAc,aAAa;AAC9C;AAEA,SAAS,cAAc,cAAsB,UAA2B;CACtE,IAAI,WAAW,KAAK,YAAY,aAAa,QAAQ,OAAO;CAE5D,OAAO,WAAW,IAAI,aAAa,aAAa,EAAE;AACpD;AAEA,SAAS,eAAe,cAAsB,UAA2B;CACvE,IAAI,WAAW,KAAK,YAAY,aAAa,QAAQ,OAAO;CAE5D,MAAM,YAAY,aAAa;CAC/B,OAAO,cAAc,OAAO,cAAc;AAC5C"}
@@ -1 +1 @@
1
- {"version":3,"file":"hoverParticipant.js","names":[],"sources":["../src/hoverParticipant.ts"],"sourcesContent":["import type { LanguageServerDiagnosticActions } from './types'\nimport type { TooltipAction } from '@singapore-editor/plugin-ui/tooltip'\nimport {\n lspPositionToOffsetInSnapshot,\n offsetToLspPositionInSnapshot,\n type LspRequestOptions,\n} from '@singapore-editor/lsp'\nimport type {\n EditorHoverParticipant,\n HoverPart,\n HoverRequest,\n} from '@singapore-editor/plugin-ui/hover-participant'\nimport type * as lsp from 'vscode-languageserver-protocol'\n\nimport { diagnosticNotes, type OpenLocation } from './diagnosticNotes'\nimport {\n diagnosticsAtOffset,\n indexDiagnosticOffsets,\n type DiagnosticOffsetIndex,\n} from './diagnosticProjection'\nimport type { ActiveDocument } from './pluginTypes'\nimport type { LanguageServerFeatureRouter, LanguageServerHoverUpdate } from './serverSet'\n\n/** Diagnostics above the server's prose, the way VS Code orders its marker and Markdown hovers. */\nconst DIAGNOSTIC_ORDINAL = 1\nconst HOVER_TEXT_ORDINAL = 3\n\nexport type LanguageServerHoverParticipantOptions = {\n readonly router: LanguageServerFeatureRouter\n requestHover(\n params: lsp.TextDocumentPositionParams,\n options: LspRequestOptions,\n onUpdate: (update: LanguageServerHoverUpdate) => void,\n ): Promise<lsp.Hover | null>\n getActiveDocument(): ActiveDocument | null\n getDiagnostics(): readonly lsp.Diagnostic[]\n readonly getDiagnosticActions?: LanguageServerDiagnosticActions\n /** Follows a diagnostic's related-information link. */\n openLocation?: OpenLocation\n onRequestSuccess?(): void\n onRequestError(error: unknown): void\n}\n\n/**\n * What the language server has to say at a position: its hover answer, progressively as each lane\n * replies, and the diagnostics published for that offset.\n */\nexport function createLanguageServerHoverParticipant(\n options: LanguageServerHoverParticipantOptions,\n): EditorHoverParticipant {\n let diagnosticIndex: { index: DiagnosticOffsetIndex; textVersion: number } | null = null\n // Outlives the tooltip, so reopening a hover joins a run instead of starting a second one.\n const runningActions = new Map<string, Promise<void>>()\n\n // Keyed on the published array and the text it was projected onto, so a pointer move pays for\n // the index only when either changes.\n const diagnosticIndexFor = (active: ActiveDocument): DiagnosticOffsetIndex => {\n const diagnostics = options.getDiagnostics()\n const cached = diagnosticIndex\n if (\n cached &&\n cached.index.diagnostics === diagnostics &&\n cached.textVersion === active.textVersion\n ) {\n return cached.index\n }\n\n const index = indexDiagnosticOffsets(active, diagnostics)\n diagnosticIndex = { index, textVersion: active.textVersion }\n return index\n }\n\n return {\n computeSync: (request) => {\n const active = options.getActiveDocument()\n if (!active) return []\n\n const diagnostics = diagnosticsAtOffset(diagnosticIndexFor(active), request.anchor.offset)\n if (diagnostics.length === 0) return []\n\n return [\n {\n ordinal: DIAGNOSTIC_ORDINAL,\n range: request.anchor.range,\n notes: diagnosticNotes(\n diagnostics,\n options.openLocation ?? (() => undefined),\n (diagnostic) => diagnosticActions(options, runningActions, active, diagnostic),\n ),\n },\n ]\n },\n computeAsync: async (request, emit) => {\n const active = options.getActiveDocument()\n if (!active || !options.router.hasReady('hover', 'textDocument/hover')) return\n\n const publish = (hovers: readonly lsp.Hover[]): void =>\n emit(hovers.flatMap((hover) => hoverParts(active, request, hover)))\n try {\n const hover = await options.requestHover(\n {\n textDocument: { uri: active.uri },\n position: offsetToLspPositionInSnapshot(active, request.anchor.offset),\n },\n { signal: request.signal },\n (update) => publish(update.hovers),\n )\n if (request.signal.aborted) return\n options.onRequestSuccess?.()\n if (hover) publish([hover])\n } catch (error) {\n if (!isAbortError(error)) options.onRequestError(error)\n }\n },\n }\n}\n\nfunction diagnosticActions(\n options: LanguageServerHoverParticipantOptions,\n runningActions: Map<string, Promise<void>>,\n active: ActiveDocument,\n diagnostic: lsp.Diagnostic,\n): readonly TooltipAction[] {\n try {\n const actions =\n options.getDiagnosticActions?.({\n documentUri: active.uri,\n textVersion: active.textVersion,\n diagnostic,\n }) ?? []\n return actions.map((action) => ({\n ...action,\n run: () => runDiagnosticAction(options, runningActions, active, diagnostic, action),\n }))\n } catch (error) {\n options.onRequestError(error)\n return []\n }\n}\n\nfunction runDiagnosticAction(\n options: LanguageServerHoverParticipantOptions,\n runningActions: Map<string, Promise<void>>,\n active: ActiveDocument,\n diagnostic: lsp.Diagnostic,\n action: TooltipAction,\n): void | Promise<void> {\n const key = diagnosticKey(diagnostic)\n const current = options.getActiveDocument()\n if (\n !current ||\n current.uri !== active.uri ||\n current.textVersion !== active.textVersion ||\n !options.getDiagnostics().some((candidate) => diagnosticKey(candidate) === key)\n )\n throw new Error('The diagnostic changed. Reopen its hover.')\n\n const runKey = JSON.stringify([active.uri, active.textVersion, key, action.label])\n const running = runningActions.get(runKey)\n if (running) return running\n\n const result = reportActionFailure(options, action)\n if (!result) return\n const run = result.finally(() => runningActions.delete(runKey))\n runningActions.set(runKey, run)\n return run\n}\n\n// The tooltip may be gone by the time a slow action fails, so the host always hears about it.\nfunction reportActionFailure(\n options: LanguageServerHoverParticipantOptions,\n action: TooltipAction,\n): void | Promise<void> {\n const report = (error: unknown): never => {\n options.onRequestError(error)\n throw error\n }\n let result: void | Promise<void>\n try {\n result = action.run()\n } catch (error) {\n return report(error)\n }\n return result ? result.catch(report) : undefined\n}\n\n// A republish replaces the diagnostic objects, so staleness compares what the user was shown.\nfunction diagnosticKey(diagnostic: lsp.Diagnostic): string {\n const { range, severity, code, source, message } = diagnostic\n return JSON.stringify([\n range.start.line,\n range.start.character,\n range.end.line,\n range.end.character,\n severity,\n code,\n source,\n typeof message === 'string' ? message : message.value,\n ])\n}\n\nfunction hoverParts(\n active: ActiveDocument,\n request: HoverRequest,\n hover: lsp.Hover,\n): readonly HoverPart[] {\n const markdown = hoverContentsText(hover.contents).trim()\n if (!markdown) return []\n\n return [\n {\n ordinal: HOVER_TEXT_ORDINAL,\n range: hoverRangeOffsets(active, hover) ?? request.anchor.range,\n markdown,\n },\n ]\n}\n\nfunction hoverContentsText(contents: lsp.Hover['contents']): string {\n if (typeof contents === 'string') return contents\n if (Array.isArray(contents)) return contents.map(markedStringText).join('\\n\\n')\n if ('kind' in contents) return contents.value\n return markedStringText(contents)\n}\n\nfunction markedStringText(value: lsp.MarkedString): string {\n if (typeof value === 'string') return value\n return ['```' + value.language, value.value, '```'].join('\\n')\n}\n\nfunction hoverRangeOffsets(\n active: ActiveDocument,\n hover: lsp.Hover,\n): { readonly start: number; readonly end: number } | null {\n if (!hover.range) return null\n\n const start = lspPositionToOffsetInSnapshot(active, hover.range.start)\n const end = lspPositionToOffsetInSnapshot(active, hover.range.end)\n if (end > start) return { start, end }\n return null\n}\n\nfunction isAbortError(error: unknown): boolean {\n if (error instanceof DOMException && error.name === 'AbortError') return true\n if (typeof error !== 'object' || error === null) return false\n return 'name' in error && error.name === 'LspRequestCancelledError'\n}\n"],"mappings":";;;;;AAwBA,IAAM,qBAAqB;AAC3B,IAAM,qBAAqB;;;;;AAsB3B,SAAgB,qCACd,SACwB;CACxB,IAAI,kBAAgF;CAEpF,MAAM,iCAAiB,IAAI,IAA2B;CAItD,MAAM,sBAAsB,WAAkD;EAC5E,MAAM,cAAc,QAAQ,eAAe;EAC3C,MAAM,SAAS;EACf,IACE,UACA,OAAO,MAAM,gBAAgB,eAC7B,OAAO,gBAAgB,OAAO,aAE9B,OAAO,OAAO;EAGhB,MAAM,QAAQ,uBAAuB,QAAQ,WAAW;EACxD,kBAAkB;GAAE;GAAO,aAAa,OAAO;EAAY;EAC3D,OAAO;CACT;CAEA,OAAO;EACL,cAAc,YAAY;GACxB,MAAM,SAAS,QAAQ,kB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AO,YAAY,WAAW,UAAU,QAAQ;CAClD,CAAC;AACH;AAEA,SAAS,WACP,QACA,SACA,OACsB;CACtB,MAAM,WAAW,kBAAkB,MAAM,QAAQ,CAAC,CAAC,KAAK;CACxD,IAAI,CAAC,UAAU,OAAO,CAAC;CAEvB,OAAO,CACL;EACE,SAAS;EACT,OAAO,kBAAkB,QAAQ,KAAK,KAAK,QAAQ,OAAO;EAC1D;CACF,CACF;AACF;AAEA,SAAS,kBAAkB,UAAyC;CAClE,IAAI,OAAO,aAAa,UAAU,OAAO;CACzC,IAAI,MAAM,QAAQ,QAAQ,GAAG,OAAO,SAAS,IAAI,gBAAgB,CAAC,CAAC,KAAK,MAAM;CAC9E,IAAI,UAAU,UAAU,OAAO,SAAS;CACxC,OAAO,iBAAiB,QAAQ;AAClC;AAEA,SAAS,iBAAiB,OAAiC;CACzD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO;EAAC,QAAQ,MAAM;EAAU,MAAM;EAAO;CAAK,CAAC,CAAC,KAAK,IAAI;AAC/D;AAEA,SAAS,kBACP,QACA,OACyD;CACzD,IAAI,CAAC,MAAM,OAAO,OAAO;CAEzB,MAAM,QAAQ,8BAA8B,QAAQ,MAAM,MAAM,KAAK;CACrE,MAAM,MAAM,8BAA8B,QAAQ,MAAM,MAAM,GAAG;CACjE,IAAI,MAAM,OAAO,OAAO;EAAE;EAAO;CAAI;CACrC,OAAO;AACT;AAEA,SAAS,aAAa,OAAyB;CAC7C,IAAI,iBAAiB,gBAAgB,MAAM,SAAS,cAAc,OAAO;CACzE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAO,UAAU,SAAS,MAAM,SAAS;AAC3C"}
@@ -1 +1 @@
1
- {"version":3,"file":"keyCommands.js","names":[],"sources":["../src/keyCommands.ts"],"sourcesContent":["import type { EditorCommandId } from '@singapore-editor/core/editor'\n\nexport type CompletionKeyCommand =\n | 'trigger'\n | 'next'\n | 'previous'\n | 'nextPage'\n | 'previousPage'\n | 'accept'\n | 'hide'\n\nexport type SignatureHelpKeyCommand = 'close' | 'next' | 'previous'\n\n/** The editor commands the keymap binds to the completion list; see the core's suggest pack. */\nexport const COMPLETION_KEY_COMMANDS = {\n trigger: 'editor.action.triggerSuggest',\n next: 'selectNextSuggestion',\n previous: 'selectPrevSuggestion',\n nextPage: 'selectNextPageSuggestion',\n previousPage: 'selectPrevPageSuggestion',\n accept: 'acceptSelectedSuggestion',\n hide: 'hideSuggestWidget',\n} as const satisfies Record<CompletionKeyCommand, EditorCommandId>\n\n/** Kept apart from the controller, which loads on the first `(`, so naming them costs nothing. */\nexport const SIGNATURE_HELP_KEY_COMMANDS = {\n close: 'closeParameterHints',\n next: 'showNextParameterHint',\n previous: 'showPrevParameterHint',\n} as const satisfies Record<SignatureHelpKeyCommand, EditorCommandId>\n"],"mappings":";;AAcA,IAAa,0BAA0B;CACrC,SAAS;CACT,MAAM;CACN,UAAU;CACV,UAAU;CACV,cAAc;CACd,QAAQ;CACR,MAAM;AACR;;AAGA,IAAa,8BAA8B;CACzC,OAAO;CACP,MAAM;CACN,UAAU;AACZ"}
1
+ {"version":3,"file":"keyCommands.js","names":[],"sources":["../src/keyCommands.ts"],"mappings":";;AAcA,IAAa,0BAA0B;CACrC,SAAS;CACT,MAAM;CACN,UAAU;CACV,UAAU;CACV,cAAc;CACd,QAAQ;CACR,MAAM;AACR;;AAGA,IAAa,8BAA8B;CACzC,OAAO;CACP,MAAM;CACN,UAAU;AACZ"}
package/dist/lane.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lane.js","names":[],"sources":["../src/lane.ts"],"sourcesContent":["import {\n createDocumentLogicalRevisionScope,\n type DocumentLogicalRevisionScope,\n} from '@singapore-editor/core/document'\nimport {\n composeWorkspaceEditClientCapabilities,\n type LspClient,\n type LspWorkspace,\n} from '@singapore-editor/lsp'\n\nimport {\n createWebSocketLspTransportFactory,\n LspConnection,\n type LspConnectionCallbacks,\n type LspConnectionLease,\n type LspConnectionOptions,\n type LspConnectionTransportFactory,\n} from './lspConnection'\nimport type {\n LanguageServerConnectionContext,\n LanguageServerLaneOptions,\n LanguageServerStatus,\n} from './types'\n\nconst DEFAULT_TIMEOUT_MS = 15_000\nconst logicalRevisionScopes = new WeakMap<LspWorkspace, DocumentLogicalRevisionScope>()\n\nexport type AcquiredLanguageServerLane = {\n readonly id: string\n readonly client: LspClient\n readonly logicalRevisionScope: DocumentLogicalRevisionScope\n readonly workspace: LspWorkspace\n readonly ready: Promise<LanguageServerConnectionContext>\n isReady(): boolean\n release(): void\n}\n\nexport type LanguageServerLaneCallbacks = {\n onDiagnosticRefresh?(): void\n onReconnecting?(): void\n onPublishDiagnostics?(params: unknown): void\n beforeReady?(): void | Promise<void>\n onReady?(): void\n onUnavailable?(): void\n}\n\nexport type LanguageServerResolvedLaneOptions = Omit<\n LanguageServerLaneOptions,\n 'webSocketRoute' | 'webSocketTransportOptions'\n> & {\n createTransport: LspConnectionTransportFactory\n}\n\ntype ReadyPromise = {\n readonly promise: Promise<LanguageServerConnectionContext>\n resolve(context: LanguageServerConnectionContext): void\n reject(error: unknown): void\n}\n\nexport function acquireLanguageServerLane(\n options: LanguageServerLaneOptions,\n callbacks: LanguageServerLaneCallbacks = {},\n): AcquiredLanguageServerLane {\n return acquireResolvedLanguageServerLane(resolveLanguageServerLaneOptions(options), callbacks)\n}\n\nexport function acquireResolvedLanguageServerLane(\n options: LanguageServerResolvedLaneOptions,\n callbacks: LanguageServerLaneCallbacks = {},\n): AcquiredLanguageServerLane {\n const connectionOptions = resolveConnectionOptions(options)\n const ready = readyPromise()\n let connectionLease: LspConnectionLease | null = null\n let connection: LspConnection\n let registration: { dispose(): void } | null = null\n let released = false\n let usable = false\n\n const connectionCallbacks: LspConnectionCallbacks = {\n onConnected: () => {\n void finishConnection()\n },\n onDiagnosticRefresh: () => callbacks.onDiagnosticRefresh?.(),\n onReconnecting: () => {\n usable = false\n callbacks.onReconnecting?.()\n },\n onUnavailable: () => {\n usable = false\n callbacks.onUnavailable?.()\n },\n onPublishDiagnostics: (params) => callbacks.onPublishDiagnostics?.(params),\n onStatusChange: (status) => reportTransportStatus(options, status, released),\n onError: (error) => {\n options.onError?.(error)\n ready.reject(error)\n },\n }\n\n connectionLease =\n options.connectionProvider?.acquire(connectionOptions, connectionCallbacks) ?? null\n connection =\n connectionLease?.connection ?? new LspConnection(connectionOptions, connectionCallbacks)\n const context = connectionContext(connection)\n const logicalRevisionScope = logicalRevisionScopeFor(connection.workspace)\n registration = options.onConnectionCreated?.(context) ?? null\n if (!connectionLease) connection.connect()\n\n return {\n id: options.id,\n client: connection.client,\n logicalRevisionScope,\n workspace: connection.workspace,\n ready: ready.promise,\n isReady: () => usable && !released,\n release: () => {\n if (released) return\n\n released = true\n usable = false\n ready.reject(new Error(`Language-server lane \"${options.id}\" was released before readiness.`))\n registration?.dispose()\n registration = null\n if (connectionLease) connectionLease.release()\n else connection.dispose()\n },\n }\n\n async function finishConnection(): Promise<void> {\n if (released) return\n const initialization = connection.client.initialization\n\n try {\n for (const notification of options.readyNotifications ?? []) {\n await connection.client.notify(notification.method, notification.params)\n if (released || connection.client.initialization !== initialization) return\n }\n\n await callbacks.beforeReady?.()\n if (released || connection.client.initialization !== initialization) return\n usable = true\n options.onStatusChange?.('ready')\n callbacks.onReady?.()\n options.onConnected?.(context)\n ready.resolve(context)\n } catch (error) {\n if (released || connection.client.initialization !== initialization) return\n\n usable = false\n options.onStatusChange?.('error')\n options.onError?.(error)\n ready.reject(error)\n }\n }\n}\n\nexport function resolveLanguageServerLaneOptions(\n options: LanguageServerLaneOptions,\n): LanguageServerResolvedLaneOptions {\n return {\n ...options,\n rootUri: options.rootUri ?? 'file:///',\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n capabilities: composeWorkspaceEditClientCapabilities(\n options.capabilities,\n options.onApplyWorkspaceEdit !== undefined,\n ),\n createTransport: createWebSocketLspTransportFactory(\n options.webSocketRoute,\n options.webSocketTransportOptions,\n ),\n }\n}\n\nfunction resolveConnectionOptions(\n options: LanguageServerResolvedLaneOptions,\n): LspConnectionOptions {\n return {\n rootUri: options.rootUri ?? 'file:///',\n initializationOptions: options.initializationOptions,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n capabilities: composeWorkspaceEditClientCapabilities(\n options.capabilities,\n options.onApplyWorkspaceEdit !== undefined,\n ),\n clientInfo: options.clientInfo,\n notificationHandlers: options.notificationHandlers,\n serverRequestHandlers: options.serverRequestHandlers,\n reconnect: options.reconnect,\n createTransport: options.createTransport,\n }\n}\n\nfunction logicalRevisionScopeFor(workspace: LspWorkspace): DocumentLogicalRevisionScope {\n const current = logicalRevisionScopes.get(workspace)\n if (current) return current\n\n const created = createDocumentLogicalRevisionScope()\n logicalRevisionScopes.set(workspace, created)\n return created\n}\n\nfunction reportTransportStatus(\n options: LanguageServerResolvedLaneOptions,\n status: LanguageServerStatus,\n released: boolean,\n): void {\n if (released) return\n if (status === 'ready') return\n\n options.onStatusChange?.(status)\n}\n\nfunction connectionContext(connection: LspConnection): LanguageServerConnectionContext {\n return {\n client: connection.client,\n workspace: connection.workspace,\n }\n}\n\nfunction readyPromise(): ReadyPromise {\n let resolve!: ReadyPromise['resolve']\n let reject!: ReadyPromise['reject']\n const promise = new Promise<LanguageServerConnectionContext>((resolveReady, rejectReady) => {\n resolve = resolveReady\n reject = rejectReady\n })\n\n return { promise, resolve, reject }\n}\n"],"mappings":";;;;AAwBA,IAAM,qBAAqB;AAC3B,IAAM,wCAAwB,IAAI,QAAoD;AAkCtF,SAAgB,0BACd,SACA,YAAyC,CAAC,GACd;CAC5B,OAAO,kCAAkC,iCAAiC,OAAO,GAAG,SAAS;AAC/F;AAEA,SAAgB,kCACd,SACA,YAAyC,CAAC,GACd;CAC5B,MAAM,oBAAoB,yBAAyB,OAAO;CAC1D,MAAM,QAAQ,aAAa;CAC3B,IAAI,kBAA6C;CACjD,IAAI;CACJ,IAAI,eAA2C;CAC/C,IAAI,W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YAAY,QAAQ;EACpB,sBAAsB,QAAQ;EAC9B,uBAAuB,QAAQ;EAC/B,WAAW,QAAQ;EACnB,iBAAiB,QAAQ;CAC3B;AACF;AAEA,SAAS,wBAAwB,WAAuD;CACtF,MAAM,UAAU,sBAAsB,IAAI,SAAS;CACnD,IAAI,SAAS,OAAO;CAEpB,MAAM,UAAU,mCAAmC;CACnD,sBAAsB,IAAI,WAAW,OAAO;CAC5C,OAAO;AACT;AAEA,SAAS,sBACP,SACA,QACA,UACM;CACN,IAAI,UAAU;CACd,IAAI,WAAW,SAAS;CAExB,QAAQ,iBAAiB,MAAM;AACjC;AAEA,SAAS,kBAAkB,YAA4D;CACrF,OAAO;EACL,QAAQ,WAAW;EACnB,WAAW,WAAW;CACxB;AACF;AAEA,SAAS,eAA6B;CACpC,IAAI;CACJ,IAAI;CAMJ,OAAO;EAAE,SAAA,IALW,SAA0C,cAAc,gBAAgB;GAC1F,UAAU;GACV,SAAS;EACX,CAES;EAAS;EAAS;CAAO;AACpC"}
@@ -1 +1 @@
1
- {"version":3,"file":"lspConnection.js","names":[],"sources":["../src/lspConnection.ts"],"sourcesContent":["import {\n createWebSocketLspTransport,\n createWorkerLspTransport,\n LSP_SERVER_EXITED,\n LspClient,\n LspServerExitedError,\n LspWorkspace,\n type LspServerExitedParams,\n type LspManagedTransport,\n type LspNotificationHandler,\n type LspServerRequestHandler,\n type LspWebSocketTransportOptions,\n type LspWorkerLike,\n} from '@singapore-editor/lsp'\nimport type * as lsp from 'vscode-languageserver-protocol'\n\nimport type { LanguageServerStatus } from './types'\n\nconst DIAGNOSTIC_REFRESH_METHOD = 'workspace/diagnostic/refresh'\n/** A connection that stayed up this long ended a crash streak; its next loss starts a new one. */\nconst STABLE_CONNECTION_MS = 60_000\n\nexport type LspReconnectOptions = {\n /** One delay per attempt; when they run out the connection gives up and reports unavailable. */\n readonly delaysMs: readonly number[]\n}\n\nexport type LspConnectionTransportFactory = () => LspManagedTransport | Promise<LspManagedTransport>\n\nexport type LspConnectionOptions = {\n readonly rootUri: lsp.DocumentUri | null\n readonly initializationOptions: unknown\n readonly timeoutMs: number\n /**\n * Merged over `defaultClientCapabilities()` by the client itself, so a host declares only what it\n * adds. This is how a host turns on a feature the defaults deliberately leave off —\n * `textDocument.semanticTokens` among them, which no server sends without being asked.\n */\n readonly capabilities?: lsp.ClientCapabilities\n /**\n * Load-bearing rather than cosmetic: at least one real server branches on the client name and\n * withholds a request from clients it does not recognise. The value is the host's to pick.\n */\n readonly clientInfo?: lsp.InitializeParams['clientInfo']\n /**\n * Merged around the connection's own handlers rather than replacing them. See createClient.\n */\n readonly notificationHandlers?: Readonly<Record<string, LspNotificationHandler<LspClient>>>\n /** Answers the server's requests; the connection's own `workspace/diagnostic/refresh` stays its. */\n readonly serverRequestHandlers?: Readonly<Record<string, LspServerRequestHandler<LspClient>>>\n /** Reconnects a transport that closed or failed on its own. Absent, the first loss is final. */\n readonly reconnect?: LspReconnectOptions\n createTransport(): LspManagedTransport | Promise<LspManagedTransport>\n}\n\nexport type LspConnectionCallbacks = {\n /** Also called again after a reconnect: the client re-initialized and re-opened its documents. */\n onConnected(): void\n onDiagnosticRefresh?(): void\n /** The transport is gone and another is on its way; what the server said so far is stale. */\n onReconnecting?(error: unknown): void\n onUnavailable(): void\n onPublishDiagnostics(params: unknown): void\n onStatusChange?: (status: LanguageServerStatus) => void\n onError?: (error: unknown) => void\n}\n\n/** A connection a view borrows. `release` ends its interest; closing is the provider's call. */\nexport type LspConnectionLease = {\n readonly connection: LspConnection\n release(): void\n}\n\n/**\n * Supplies connections that outlive one view, so a file switch does not pay a handshake and an\n * `initialize` round trip. `options` is the connection the plugin would have built: build from it on\n * a new key, ignore it on a known one.\n *\n * **`callbacks.onConnected` must never fire synchronously from `acquire`** — the caller is\n * mid-construction. Replay it on a microtask.\n */\nexport type LspConnectionProvider = {\n acquire(options: LspConnectionOptions, callbacks: LspConnectionCallbacks): LspConnectionLease\n}\n\nexport class LspConnection {\n public readonly workspace = new LspWorkspace()\n public readonly client: LspClient\n\n private transport: LspManagedTransport | null = null\n private removeTransportCloseListener: (() => void) | null = null\n private disposed = false\n private status: LanguageServerStatus = 'idle'\n private reconnectAttempts = 0\n private readyAt: number | null = null\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null\n /** Why the server said it is going, reported as the reason for the close that follows. */\n private exit: LspServerExitedParams | null = null\n\n public constructor(\n private readonly options: LspConnectionOptions,\n private readonly callbacks: LspConnectionCallbacks,\n ) {\n this.client = this.createClient()\n }\n\n public connect(): void {\n this.setStatus('loading')\n this.connectTransport()\n }\n\n public dispose(): void {\n if (this.disposed) return\n\n this.disposed = true\n if (this.reconnectTimer !== null) clearTimeout(this.reconnectTimer)\n this.reconnectTimer = null\n this.removeTransportCloseListener?.()\n this.removeTransportCloseListener = null\n this.client.disconnect()\n this.transport?.close()\n this.transport = null\n this.setStatus('idle')\n }\n\n private createClient(): LspClient {\n const hostHandlers = this.options.notificationHandlers\n return new LspClient({\n rootUri: this.options.rootUri,\n workspaceFolders: null,\n workspace: this.workspace,\n timeoutMs: this.options.timeoutMs,\n initializationOptions: this.options.initializationOptions,\n capabilities: this.options.capabilities,\n clientInfo: this.options.clientInfo,\n // Host handlers are merged *around* the connection's own rather than replacing them: the\n // whole diagnostics feature hangs off publishDiagnostics, so a host that happens to want that\n // notification too must not be able to take it away. Its handler runs after ours.\n notificationHandlers: {\n ...hostHandlers,\n [DIAGNOSTIC_REFRESH_METHOD]: (client, params, message) => {\n this.callbacks.onDiagnosticRefresh?.()\n hostHandlers?.[DIAGNOSTIC_REFRESH_METHOD]?.(client, params, message)\n return true\n },\n [LSP_SERVER_EXITED]: (client, params, message) => {\n this.exit = serverExitedParams(params)\n hostHandlers?.[LSP_SERVER_EXITED]?.(client, params, message)\n return true\n },\n 'textDocument/publishDiagnostics': (client, params, message) => {\n this.callbacks.onPublishDiagnostics(params)\n hostHandlers?.['textDocument/publishDiagnostics']?.(client, params, message)\n return true\n },\n },\n serverRequestHandlers: {\n ...this.options.serverRequestHandlers,\n [DIAGNOSTIC_REFRESH_METHOD]: () => {\n this.callbacks.onDiagnosticRefresh?.()\n return null\n },\n },\n })\n }\n\n private connectTransport(): void {\n try {\n const transport = this.options.createTransport()\n if (isTransportPromise(transport)) {\n void transport\n .then((value) => this.connectManagedTransport(value))\n .catch((error) => {\n this.handleConnectError(error)\n })\n return\n }\n\n this.connectManagedTransport(transport)\n } catch (error) {\n this.handleConnectError(error)\n }\n }\n\n private connectManagedTransport(transport: LspManagedTransport): void {\n if (this.disposed) {\n transport.close()\n return\n }\n\n this.transport = transport\n this.exit = null\n this.removeTransportCloseListener = transport.onDidClose((error) =>\n this.handleTransportClose(error),\n )\n transport.subscribe(this.forgetExitOnLaterMessage)\n // Only while this transport is still the connection's: a close that already detached it made\n // the report, and the initialize it rejected on the way out must not make a second one.\n void this.client\n .connect(transport)\n .then(() => {\n if (this.transport === transport) this.handleConnected()\n })\n .catch((error: unknown) => {\n if (this.transport === transport) this.handleConnectError(error)\n })\n }\n\n /** A server that says anything after announcing its exit did not exit; a later close is its own. */\n private readonly forgetExitOnLaterMessage = (message: string): void => {\n if (this.exit && !message.includes(LSP_SERVER_EXITED)) this.exit = null\n }\n\n private handleConnected(): void {\n if (this.disposed) return\n\n this.readyAt = now()\n this.setStatus('ready')\n this.callbacks.onConnected()\n }\n\n private handleConnectError(error: unknown): void {\n if (this.disposed) return\n\n this.detachTransport()\n this.giveUpOrReconnect(error)\n }\n\n private handleTransportClose(error?: unknown): void {\n if (this.disposed) return\n\n const exit = this.exit\n this.exit = null\n this.detachTransport()\n if (exit) {\n this.giveUpOrReconnect(new LspServerExitedError(exit))\n return\n }\n this.giveUpOrReconnect(error ?? new Error('LSP transport closed'))\n }\n\n private detachTransport(): void {\n this.removeTransportCloseListener?.()\n this.removeTransportCloseListener = null\n this.transport?.unsubscribe(this.forgetExitOnLaterMessage)\n this.client.disconnect()\n this.transport?.close()\n this.transport = null\n }\n\n private giveUpOrReconnect(error: unknown): void {\n if (this.scheduleReconnect(error)) return\n\n this.setStatus('error')\n this.callbacks.onUnavailable()\n this.handleError(error)\n }\n\n private scheduleReconnect(error: unknown): boolean {\n if (this.readyAt !== null && now() - this.readyAt >= STABLE_CONNECTION_MS) {\n this.reconnectAttempts = 0\n }\n this.readyAt = null\n const delay = this.options.reconnect?.delaysMs[this.reconnectAttempts]\n if (delay === undefined) return false\n\n this.reconnectAttempts += 1\n this.setStatus('loading')\n this.callbacks.onReconnecting?.(error)\n // @justification A reconnect backoff, not rendering work: the handle is kept, cleared on dispose,\n // and a disposed connection ignores it.\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = null\n if (!this.disposed) this.connectTransport()\n }, delay)\n return true\n }\n\n private setStatus(status: LanguageServerStatus): void {\n if (this.status === status) return\n\n this.status = status\n this.callbacks.onStatusChange?.(status)\n }\n\n private handleError(error: unknown): void {\n this.callbacks.onError?.(error)\n }\n}\n\nexport function createWebSocketLspTransportFactory(\n route: string | URL,\n options?: LspWebSocketTransportOptions,\n): LspConnectionTransportFactory {\n return () =>\n createWebSocketLspTransport(route, {\n protocols: options?.protocols,\n WebSocketCtor: options?.WebSocketCtor,\n })\n}\n\nexport function createWorkerLspTransportFactory(\n workerFactory: () => LspWorkerLike,\n): LspConnectionTransportFactory {\n return () =>\n createWorkerLspTransport(workerFactory(), {\n messageFormat: 'json',\n terminateOnClose: true,\n })\n}\n\nfunction now(): number {\n return typeof performance === 'undefined' ? Date.now() : performance.now()\n}\n\nfunction isTransportPromise(\n value: LspManagedTransport | Promise<LspManagedTransport>,\n): value is Promise<LspManagedTransport> {\n return typeof (value as Promise<LspManagedTransport>).then === 'function'\n}\n\nfunction serverExitedParams(params: unknown): LspServerExitedParams | null {\n if (typeof params !== 'object' || params === null) return null\n const outcome = (params as { outcome?: unknown }).outcome\n return typeof outcome === 'string' ? (params as LspServerExitedParams) : null\n}\n"],"mappings":";;AAkBA,IAAM,4BAA4B;;AAElC,IAAM,uBAAuB;AAiE7B,IAAa,gBA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AiB;GACrC,KAAK,iBAAiB;GACtB,IAAI,CAAC,KAAK,UAAU,KAAK,iBAAiB;EAC5C,GAAG,KAAK;EACR,OAAO;CACT;CAEA,UAAkB,QAAoC;EACpD,IAAI,KAAK,WAAW,QAAQ;EAE5B,KAAK,SAAS;EACd,KAAK,UAAU,iBAAiB,MAAM;CACxC;CAEA,YAAoB,OAAsB;EACxC,KAAK,UAAU,UAAU,KAAK;CAChC;AACF;AAEA,SAAgB,mCACd,OACA,SAC+B;CAC/B,aACE,4BAA4B,OAAO;EACjC,WAAW,SAAS;EACpB,eAAe,SAAS;CAC1B,CAAC;AACL;AAEA,SAAgB,gCACd,eAC+B;CAC/B,aACE,yBAAyB,cAAc,GAAG;EACxC,eAAe;EACf,kBAAkB;CACpB,CAAC;AACL;AAEA,SAAS,MAAc;CACrB,OAAO,OAAO,gBAAgB,cAAc,KAAK,IAAI,IAAI,YAAY,IAAI;AAC3E;AAEA,SAAS,mBACP,OACuC;CACvC,OAAO,OAAQ,MAAuC,SAAS;AACjE;AAEA,SAAS,mBAAmB,QAA+C;CACzE,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO;CAE1D,OAAO,OADU,OAAiC,YACxB,WAAY,SAAmC;AAC3E"}
@@ -1 +1 @@
1
- {"version":3,"file":"lspConnectionPool.js","names":[],"sources":["../src/lspConnectionPool.ts"],"sourcesContent":["import type {\n LspClient,\n LspNotificationHandler,\n LspServerRequestHandler,\n} from '@singapore-editor/lsp'\n\nimport {\n LspConnection,\n type LspConnectionCallbacks,\n type LspConnectionLease,\n type LspConnectionOptions,\n type LspConnectionProvider,\n} from './lspConnection'\nimport type { LanguageServerStatus } from './types'\n\n/**\n * How long a connection with no borrowers is kept. A file switch drops the lease count to zero for a\n * tick or two on its way from one view to the next; the cost of holding on is one idle socket, the\n * cost of letting go early is another handshake against a server that may still be indexing.\n */\nconst DEFAULT_IDLE_GRACE_MS = 30_000\n\n/** What a pooled connection just did, for a host that wants to log it. */\nexport type LspConnectionPoolEvent = {\n readonly kind:\n | 'created'\n | 'reused'\n | 'ready'\n | 'released'\n | 'closed'\n | 'retired'\n | 'reconnecting'\n | 'error'\n | 'handler_ignored'\n readonly key: string\n readonly leaseCount: number\n readonly status: LanguageServerStatus\n /** Time to `initialize` for `ready`; the connection's life so far for `closed`, `retired` and `error`. */\n readonly durationMs?: number\n readonly reachedReady?: boolean\n readonly error?: unknown\n /** Methods a late borrower declared that this connection cannot dispatch. */\n readonly methods?: readonly string[]\n}\n\nexport type LspConnectionPoolOptions = {\n readonly idleGraceMs?: number\n readonly onEvent?: (event: LspConnectionPoolEvent) => void\n}\n\ntype NotificationHandlers = Readonly<Record<string, LspNotificationHandler<LspClient>>>\ntype ServerRequestHandlers = Readonly<Record<string, LspServerRequestHandler<LspClient>>>\n\n/** Handlers are per borrower: the first one's are bound to a view the reader may have left. */\ntype ConnectionLease = {\n readonly callbacks: LspConnectionCallbacks\n readonly notificationHandlers: NotificationHandlers\n readonly serverRequestHandlers: ServerRequestHandlers\n}\n\ntype PooledConnection = {\n readonly initializationContract: ImmutableInitializationContract\n readonly key: string\n readonly leases: Set<ConnectionLease>\n readonly createdAt: number\n /** Fixed at construction, when the client reads the record. A later borrower outside it is a defect. */\n readonly notificationMethods: ReadonlySet<string>\n connection: LspConnection\n status: LanguageServerStatus\n connected: boolean\n readyAt: number | null\n idleTimer: ReturnType<typeof setTimeout> | null\n}\n\ntype ImmutableInitializationContract = {\n readonly capabilities: unknown\n readonly clientInfo: unknown\n readonly initializationOptions: unknown\n readonly rootUri: string | null\n}\n\n/**\n * One connection per key, outliving the views that borrow it. A view contribution is rebuilt on\n * every file switch, and a connection it owns dies with it — thirteen handshakes in twenty-two\n * seconds, measured. The key is opaque: how a server session is named is the host's vocabulary.\n */\nexport class LspConnectionPool {\n readonly #entries = new Map<string, PooledConnection>()\n readonly #idleGraceMs: number\n readonly #onEvent?: (event: LspConnectionPoolEvent) => void\n\n public constructor(options: LspConnectionPoolOptions = {}) {\n this.#idleGraceMs = options.idleGraceMs ?? DEFAULT_IDLE_GRACE_MS\n this.#onEvent = options.onEvent\n }\n\n /** A provider bound to one key, in the shape the plugin takes. */\n public provider(key: string): LspConnectionProvider {\n return { acquire: (options, callbacks) => this.acquire(key, options, callbacks) }\n }\n\n public acquire(\n key: string,\n options: LspConnectionOptions,\n callbacks: LspConnectionCallbacks,\n ): LspConnectionLease {\n const existing = this.#entries.get(key)\n if (existing) this.#assertCompatible(existing, options)\n\n const entry = existing ?? this.#create(key, options)\n if (entry.idleTimer !== null) {\n clearTimeout(entry.idleTimer)\n entry.idleTimer = null\n }\n\n const lease: ConnectionLease = {\n callbacks,\n notificationHandlers: options.notificationHandlers ?? {},\n serverRequestHandlers: options.serverRequestHandlers ?? {},\n }\n this.#reportUndispatchable(entry, lease)\n entry.leases.add(lease)\n this.#emit(entry, existing ? 'reused' : 'created')\n this.#replayTo(entry, lease)\n\n return {\n connection: entry.connection,\n release: () => this.#release(entry, lease),\n }\n }\n\n /** Closes every connection. For teardown and for tests, not for routine use. */\n public dispose(): void {\n for (const entry of this.#entries.values()) {\n if (entry.idleTimer !== null) clearTimeout(entry.idleTimer)\n entry.connection.dispose()\n }\n this.#entries.clear()\n }\n\n #create(key: string, options: LspConnectionOptions): PooledConnection {\n const notificationMethods = new Set(Object.keys(options.notificationHandlers ?? {}))\n const entry: PooledConnection = {\n connected: false,\n connection: null as unknown as LspConnection,\n createdAt: now(),\n idleTimer: null,\n initializationContract: initializationContract(options),\n key,\n leases: new Set(),\n notificationMethods,\n readyAt: null,\n status: 'idle',\n }\n // Assigned after the record exists because the callbacks close over it: the\n // connection reports `loading` from inside `connect()`, which is before any\n // `new LspConnection(...)` expression could have returned.\n entry.connection = new LspConnection(\n {\n ...options,\n notificationHandlers: this.#dispatchers(entry, notificationMethods),\n serverRequestHandlers: requestDispatchers(entry, options.serverRequestHandlers ?? {}),\n },\n this.#fanOut(entry),\n )\n this.#entries.set(key, entry)\n entry.connection.connect()\n\n return entry\n }\n\n #assertCompatible(entry: PooledConnection, options: LspConnectionOptions): void {\n const incoming = initializationContract(options)\n if (structurallyEqual(entry.initializationContract, incoming)) return\n\n throw new Error(\n `LSP connection pool key \"${entry.key}\" already has a different initialization contract.`,\n )\n }\n\n /** Handled is the disjunction: one view claiming a notification must not hide it from another. */\n #dispatchers(entry: PooledConnection, methods: ReadonlySet<string>): NotificationHandlers {\n const handlers: Record<string, LspNotificationHandler<LspClient>> = {}\n for (const method of methods) {\n handlers[method] = (client, params, message) => {\n let handled = false\n for (const lease of leasesOf(entry))\n handled =\n (lease.notificationHandlers[method]?.(client, params, message) ?? false) || handled\n\n return handled\n }\n }\n\n return handlers\n }\n\n /** Diagnostics broadcast rather than routed: `DocumentSync` already drops uris it does not hold. */\n #fanOut(entry: PooledConnection): LspConnectionCallbacks {\n return {\n onConnected: () => {\n entry.connected = true\n entry.readyAt = now()\n this.#emit(entry, 'ready', { durationMs: Math.round(entry.readyAt - entry.createdAt) })\n for (const lease of leasesOf(entry)) lease.callbacks.onConnected()\n },\n onDiagnosticRefresh: () => {\n for (const lease of leasesOf(entry)) lease.callbacks.onDiagnosticRefresh?.()\n },\n onReconnecting: (error) => {\n entry.connected = false\n this.#emit(entry, 'reconnecting', {\n durationMs: Math.round(now() - entry.createdAt),\n error,\n reachedReady: entry.readyAt !== null,\n })\n for (const lease of leasesOf(entry)) lease.callbacks.onReconnecting?.(error)\n },\n onUnavailable: () => {\n entry.connected = false\n this.#retire(entry)\n for (const lease of leasesOf(entry)) lease.callbacks.onUnavailable()\n },\n onPublishDiagnostics: (params) => {\n for (const lease of leasesOf(entry)) lease.callbacks.onPublishDiagnostics(params)\n },\n onStatusChange: (status) => {\n entry.status = status\n for (const lease of leasesOf(entry)) lease.callbacks.onStatusChange?.(status)\n },\n onError: (error) => {\n this.#emit(entry, 'error', {\n durationMs: Math.round(now() - entry.createdAt),\n error,\n reachedReady: entry.readyAt !== null,\n })\n for (const lease of leasesOf(entry)) lease.callbacks.onError?.(error)\n },\n }\n }\n\n /** A microtask, not a straight call: `acquire` runs inside the contribution's constructor. */\n #replayTo(entry: PooledConnection, lease: ConnectionLease): void {\n if (entry.status === 'idle') return\n\n const status = entry.status\n const connected = entry.connected\n queueMicrotask(() => {\n if (!entry.leases.has(lease)) return\n\n lease.callbacks.onStatusChange?.(status)\n if (connected) lease.callbacks.onConnected()\n })\n }\n\n #release(entry: PooledConnection, lease: ConnectionLease): void {\n if (!entry.leases.delete(lease)) return\n\n this.#emit(entry, 'released')\n if (entry.leases.size > 0) return\n if (this.#entries.get(entry.key) !== entry) return\n\n entry.idleTimer = setTimeout(() => this.#closeIdle(entry), this.#idleGraceMs)\n }\n\n #closeIdle(entry: PooledConnection): void {\n entry.idleTimer = null\n if (entry.leases.size > 0) return\n if (this.#entries.get(entry.key) !== entry) return\n\n this.#entries.delete(entry.key)\n entry.connection.dispose()\n this.#emit(entry, 'closed', {\n durationMs: Math.round(now() - entry.createdAt),\n reachedReady: entry.readyAt !== null,\n })\n }\n\n #retire(entry: PooledConnection): void {\n if (entry.idleTimer !== null) clearTimeout(entry.idleTimer)\n entry.idleTimer = null\n if (this.#entries.get(entry.key) === entry) this.#entries.delete(entry.key)\n entry.connection.dispose()\n this.#emit(entry, 'retired', {\n durationMs: Math.round(now() - entry.createdAt),\n reachedReady: entry.readyAt !== null,\n })\n }\n\n #reportUndispatchable(entry: PooledConnection, lease: ConnectionLease): void {\n const methods = Object.keys(lease.notificationHandlers).filter(\n (method) => !entry.notificationMethods.has(method),\n )\n if (methods.length === 0) return\n\n this.#emit(entry, 'handler_ignored', { methods })\n }\n\n #emit(\n entry: PooledConnection,\n kind: LspConnectionPoolEvent['kind'],\n extra: Omit<LspConnectionPoolEvent, 'kind' | 'key' | 'leaseCount' | 'status'> = {},\n ): void {\n this.#onEvent?.({\n key: entry.key,\n kind,\n leaseCount: entry.leases.size,\n status: entry.status,\n ...extra,\n })\n }\n}\n\n/** Snapshotted: a callback can release its own lease mid-iteration. */\nfunction leasesOf(entry: PooledConnection): readonly ConnectionLease[] {\n return Array.from(entry.leases)\n}\n\nfunction now(): number {\n return typeof performance === 'undefined' ? Date.now() : performance.now()\n}\n\nfunction initializationContract(options: LspConnectionOptions): ImmutableInitializationContract {\n return {\n capabilities: normalizeComparable(options.capabilities),\n clientInfo: normalizeComparable(options.clientInfo),\n initializationOptions: normalizeComparable(options.initializationOptions),\n rootUri: options.rootUri,\n }\n}\n\nfunction normalizeComparable(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(normalizeComparable)\n if (!isRecord(value)) return value\n\n const normalized: Record<string, unknown> = {}\n const keys = Object.keys(value)\n .filter((key) => value[key] !== undefined)\n .sort()\n for (const key of keys) normalized[key] = normalizeComparable(value[key])\n return normalized\n}\n\nfunction structurallyEqual(left: unknown, right: unknown): boolean {\n if (Object.is(left, right)) return true\n if (Array.isArray(left) || Array.isArray(right)) return equalArrays(left, right)\n if (!isRecord(left) || !isRecord(right)) return false\n return equalRecords(left, right)\n}\n\nfunction equalArrays(left: unknown, right: unknown): boolean {\n if (!Array.isArray(left) || !Array.isArray(right)) return false\n if (left.length !== right.length) return false\n\n for (let index = 0; index < left.length; index += 1) {\n if (!structurallyEqual(left[index], right[index])) return false\n }\n return true\n}\n\nfunction equalRecords(left: Record<string, unknown>, right: Record<string, unknown>): boolean {\n const leftKeys = Object.keys(left)\n const rightKeys = Object.keys(right)\n if (leftKeys.length !== rightKeys.length) return false\n\n for (const key of leftKeys) {\n if (!(key in right)) return false\n if (!structurallyEqual(left[key], right[key])) return false\n }\n return true\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * A request has one answer, so the first borrower that handles the method gives it; the methods\n * are fixed by the first borrower, like the notification methods.\n */\nfunction requestDispatchers(\n entry: PooledConnection,\n initial: ServerRequestHandlers,\n): ServerRequestHandlers {\n const handlers: Record<string, LspServerRequestHandler<LspClient>> = {}\n for (const method of Object.keys(initial)) {\n handlers[method] = (client, params, message) => {\n const handler = leasesOf(entry).find((lease) => lease.serverRequestHandlers[method])\n ?.serverRequestHandlers[method]\n // An answer the server can mistake for an empty one is worse than an error it can report.\n if (!handler) throw new Error(`No editor on this connection answers ${method}`)\n return handler(client, params, message)\n }\n }\n return handlers\n}\n"],"mappings":";;;;;;;AAoBA,IAAM,wBAAwB;;;;;;AAkE9B,IAAa,oBAAb,MAA+B;CAC7B,2BAAoB,IAAI,IAA8B;CACtD;CACA;CAEA,YAAmB,UAAoC,CAAC,GAAG;EACzD,KAAK,eAAe,QAAQ,eAAe;EAC3C,KAAK,WAAW,QAAQ;CAC1B;;CAGA,SAAgB,KAAoC;EAClD,OAAO,EAAE,UAAU,SAAS,cAAc,KAAK,QAAQ,KAAK,SAAS,SAAS,EAAE;CAClF;CAEA,QACE,KACA,SACA,WACoB;EACpB,MAAM,WAAW,KAAK,SAAS,IAAI,GAAG;EACtC,IAAI,UAAU,KAAK,kBAAkB,UAAU,OAAO;EAEtD,MAAM,QAAQ,YAAY,KAAK,QAAQ,KAAK,OAAO;EACnD,IAAI,MAAM,cAAc,MAAM;GAC5B,aAAa,MAAM,SAAS;GAC5B,MAAM,YAAY;EACpB;EAEA,MAAM,QAAyB;GAC7B;GACA,sBAAsB,QAAQ,wBAAwB,CAAC;GACvD,uBAAuB,QAAQ,yBAAyB,CAAC;EAC3D;EACA,KAAK,sBAAsB,OAAO,KAAK;EACvC,MAAM,OAAO,IAAI,KAAK;EACtB,KAAK,MAAM,OAAO,WAAW,WAAW,SAAS;EACjD,KAAK,UAAU,OAAO,KAAK;EAE3B,OAAO;GACL,YAAY,MAAM;GAClB,eAAe,KAAK,SAAS,OAAO,KAAK;EAC3C;CACF;;CAGA,UAAuB;EACrB,KAAK,MAAM,SAAS,KAAK,SAAS,OAAO,GAAG;GAC1C,IAAI,MAAM,cAAc,MAAM,aAAa,MAAM,SAAS;GAC1D,MAAM,WAAW,QAAQ;EAC3B;EACA,KAAK,SAAS,MAAM;CACtB;CAEA,Q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,QAAQ,QAAQ,OAAO;CACxC;CAEF,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"minimalEdits.js","names":[],"sources":["../src/minimalEdits.ts"],"sourcesContent":["import type { TextEdit } from '@singapore-editor/core'\n\n/**\n * The longest replacement still worth re-diffing.\n *\n * Past this the comparison costs more than it saves: a reply that rewrites this much has left\n * almost no anchor, decoration or fold inside the span to preserve, and the diff itself becomes the\n * expensive part of formatting.\n */\nexport const REDIFF_LENGTH_LIMIT = 100_000\n\n/**\n * How far apart the two texts may be before the alignment is abandoned.\n *\n * One endpoint band per step is kept so the alignment can be walked back, so the memory held grows\n * with the square of this number. A reply differing by more than this is a rewrite rather than a\n * reformat, and is cheaper to apply whole.\n */\nconst REDIFF_STEP_LIMIT = 400\n\ntype LineRegion = {\n originalStart: number\n originalEnd: number\n replacementStart: number\n replacementEnd: number\n}\n\n/**\n * Splits a replacement into edits covering only what differs from the text it overwrites.\n *\n * A formatter answers with the whole document, or a whole line, even when three characters moved.\n * Applying that verbatim rewrites text that did not change, and every anchor, decoration, fold and\n * selection inside the rewritten span dies with it — so the reply is compared against the buffer\n * first and only the differences are handed on.\n *\n * `offset` is where `original` starts in the document, so the returned edits address the buffer.\n */\nexport function minimalReplacementEdits(\n original: string,\n replacement: string,\n offset: number,\n): TextEdit[] {\n if (original === replacement) return []\n if (Math.max(original.length, replacement.length) > REDIFF_LENGTH_LIMIT) {\n return [wholeReplacement(original, replacement, offset)]\n }\n\n const originalLines = splitAfterLineBreaks(original)\n const replacementLines = splitAfterLineBreaks(replacement)\n const regions = changedLineRegions(originalLines, replacementLines)\n if (!regions) return [wholeReplacement(original, replacement, offset)]\n\n const originalStarts = lineStartOffsets(originalLines)\n const replacementStarts = lineStartOffsets(replacementLines)\n\n const edits: TextEdit[] = []\n for (const region of regions) {\n const edit = narrowToDifference(\n original,\n originalStarts[region.originalStart] ?? 0,\n originalStarts[region.originalEnd] ?? original.length,\n replacement.slice(\n replacementStarts[region.replacementStart] ?? 0,\n replacementStarts[region.replacementEnd] ?? replacement.length,\n ),\n offset,\n )\n if (edit.from !== edit.to || edit.text.length > 0) edits.push(edit)\n }\n return edits\n}\n\nfunction wholeReplacement(original: string, replacement: string, offset: number): TextEdit {\n return { from: offset, text: replacement, to: offset + original.length }\n}\n\n/**\n * Shrinks one region to the characters inside it that differ.\n *\n * Line alignment hands back the whole line an indentation change sits in; dropping what the two\n * sides still share turns that into the handful of characters the formatter actually touched. A\n * boundary steps back off a surrogate pair, because half a code point is not something the rest of\n * the editor can anchor to.\n */\nfunction narrowToDifference(\n original: string,\n from: number,\n to: number,\n text: string,\n offset: number,\n): TextEdit {\n const shared = Math.min(to - from, text.length)\n\n let prefix = 0\n while (prefix < shared && original.charCodeAt(from + prefix) === text.charCodeAt(prefix)) {\n prefix += 1\n }\n if (prefix > 0 && isHighSurrogate(text.charCodeAt(prefix - 1))) prefix -= 1\n\n let suffix = 0\n while (\n suffix < shared - prefix &&\n original.charCodeAt(to - 1 - suffix) === text.charCodeAt(text.length - 1 - suffix)\n ) {\n suffix += 1\n }\n if (suffix > 0 && isLowSurrogate(text.charCodeAt(text.length - suffix))) suffix -= 1\n\n return {\n from: offset + from + prefix,\n text: text.slice(prefix, text.length - suffix),\n to: offset + to - suffix,\n }\n}\n\nfunction isHighSurrogate(code: number): boolean {\n return code >= 0xd800 && code <= 0xdbff\n}\n\nfunction isLowSurrogate(code: number): boolean {\n return code >= 0xdc00 && code <= 0xdfff\n}\n\n/** Lines keep their terminator, so concatenating them back gives the text they came from. */\nfunction splitAfterLineBreaks(text: string): string[] {\n const lines: string[] = []\n let start = 0\n for (let index = 0; index < text.length; index += 1) {\n if (text.charCodeAt(index) !== 10) continue\n\n lines.push(text.slice(start, index + 1))\n start = index + 1\n }\n lines.push(text.slice(start))\n return lines\n}\n\nfunction lineStartOffsets(lines: readonly string[]): number[] {\n const starts = [0]\n let offset = 0\n for (const line of lines) {\n offset += line.length\n starts.push(offset)\n }\n return starts\n}\n\n/**\n * Aligns two line sequences and returns the runs that do not correspond, or null when they lie\n * further apart than the step limit allows.\n *\n * The alignment is the shortest path that deletes original lines and inserts replacement ones,\n * taking equal lines for free; each step's furthest reach per diagonal is recorded so the path can\n * be walked back once the end is reached.\n *\n * Lines rather than characters, because a formatter's changes are line-shaped and aligning by line\n * costs a fraction of what aligning by character would; `narrowToDifference` recovers the\n * character-level precision afterwards, as a linear scan of one region.\n */\nfunction changedLineRegions(\n original: readonly string[],\n replacement: readonly string[],\n): LineRegion[] | null {\n const originalCount = original.length\n const replacementCount = replacement.length\n const stepLimit = Math.min(originalCount + replacementCount, REDIFF_STEP_LIMIT)\n // A diagonal is reachable only after as many steps as it is far from the origin, so the band of\n // live endpoints never widens past the step limit.\n const band = stepLimit + 1\n const endpoints = new Int32Array(2 * band + 1)\n const trace: Int32Array[] = []\n\n for (let step = 0; step <= stepLimit; step += 1) {\n trace.push(endpoints.slice(band - step, band + step + 1))\n\n for (let diagonal = -step; diagonal <= step; diagonal += 2) {\n const afterInsert = endpoints[band + diagonal + 1] ?? 0\n const afterDelete = endpoints[band + diagonal - 1] ?? 0\n const inserts = diagonal === -step || (diagonal !== step && afterDelete < afterInsert)\n let x = inserts ? afterInsert : afterDelete + 1\n let y = x - diagonal\n while (x < originalCount && y < replacementCount && original[x] === replacement[y]) {\n x += 1\n y += 1\n }\n endpoints[band + diagonal] = x\n\n if (x >= originalCount && y >= replacementCount) {\n return regionsFromTrace(trace, originalCount, replacementCount)\n }\n }\n }\n\n return null\n}\n\n/**\n * Walks the recorded alignment back from the end, collecting every step that was not a match.\n *\n * Consecutive non-matching steps belong to one region: they are separated only once a run of equal\n * lines has been walked back over, which moves both cursors away from the region being built.\n */\nfunction regionsFromTrace(\n trace: readonly Int32Array[],\n originalCount: number,\n replacementCount: number,\n): LineRegion[] {\n const regions: LineRegion[] = []\n let open: LineRegion | null = null\n let x = originalCount\n let y = replacementCount\n\n for (let step = trace.length - 1; step > 0; step -= 1) {\n const endpoints = trace[step]\n if (!endpoints) break\n\n const diagonal = x - y\n const afterInsert = endpoints[diagonal + 1 + step] ?? 0\n const afterDelete = endpoints[diagonal - 1 + step] ?? 0\n const inserts = diagonal === -step || (diagonal !== step && afterDelete < afterInsert)\n const previousDiagonal = inserts ? diagonal + 1 : diagonal - 1\n const previousX = inserts ? afterInsert : afterDelete\n const previousY = previousX - previousDiagonal\n\n while (x > previousX && y > previousY) {\n x -= 1\n y -= 1\n }\n\n if (open && open.originalStart === x && open.replacementStart === y) {\n open.originalStart = previousX\n open.replacementStart = previousY\n } else {\n open = {\n originalEnd: x,\n originalStart: previousX,\n replacementEnd: y,\n replacementStart: previousY,\n }\n regions.push(open)\n }\n\n x = previousX\n y = previousY\n }\n\n return regions.reverse()\n}\n"],"mappings":";;;;;;;;AASA,IAAa,sBAAsB;;;;;;;;AASnC,IAAM,oBAAoB;;;;;;;;;;;AAmB1B,SAAgB,wBACd,UACA,aACA,QACY;CACZ,IAAI,aAAa,aAAa,OAAO,CAAC;CACtC,IAAI,KAAK,IAAI,SAAS,QAAQ,YAAY,MAAM,IAAA,KAC9C,OAAO,CAAC,iBAAiB,UAAU,aAAa,MAAM,CAAC;CAGzD,MAAM,gBAAgB,qBAAqB,QAAQ;CACnD,MAAM,mBAAmB,qBAAqB,WAAW;CACzD,MAAM,UAAU,mBAAmB,eAAe,gBAAgB;CAClE,IAAI,CAAC,SAAS,OAAO,CAAC,iBAAiB,UAAU,aAAa,MAAM,CAAC;CAErE,MAAM,iBAAiB,iBAAiB,aAAa;CACrD,MAAM,oBAAoB,iBAAiB,gBAAgB;CAE3D,MAAM,QAAoB,CAAC;CAC3B,KAAK,MAAM,UAAU,SAAS;EAC5B,MAAM,OAAO,mBACX,UACA,eAAe,OAAO,kBAAkB,GACxC,eAAe,OAAO,gBAAgB,SAAS,QAC/C,YAAY,MACV,kBAAkB,OAAO,qBAAqB,GAC9C,kBAAkB,OAAO,mBAAmB,YAAY,MAC1D,GACA,MACF;EACA,IAAI,KAAK,SAAS,KAA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AO,eAAe,gBAAgB;EAElE;CACF;CAEA,OAAO;AACT;;;;;;;AAQA,SAAS,iBACP,OACA,eACA,kBACc;CACd,MAAM,UAAwB,CAAC;CAC/B,IAAI,OAA0B;CAC9B,IAAI,IAAI;CACR,IAAI,IAAI;CAER,KAAK,IAAI,OAAO,MAAM,SAAS,GAAG,OAAO,GAAG,QAAQ,GAAG;EACrD,MAAM,YAAY,MAAM;EACxB,IAAI,CAAC,WAAW;EAEhB,MAAM,WAAW,IAAI;EACrB,MAAM,cAAc,UAAU,WAAW,IAAI,SAAS;EACtD,MAAM,cAAc,UAAU,WAAW,IAAI,SAAS;EACtD,MAAM,UAAU,aAAa,CAAC,QAAS,aAAa,QAAQ,cAAc;EAC1E,MAAM,mBAAmB,UAAU,WAAW,IAAI,WAAW;EAC7D,MAAM,YAAY,UAAU,cAAc;EAC1C,MAAM,YAAY,YAAY;EAE9B,OAAO,IAAI,aAAa,IAAI,WAAW;GACrC,KAAK;GACL,KAAK;EACP;EAEA,IAAI,QAAQ,KAAK,kBAAkB,KAAK,KAAK,qBAAqB,GAAG;GACnE,KAAK,gBAAgB;GACrB,KAAK,mBAAmB;EAC1B,OAAO;GACL,OAAO;IACL,aAAa;IACb,eAAe;IACf,gBAAgB;IAChB,kBAAkB;GACpB;GACA,QAAQ,KAAK,IAAI;EACnB;EAEA,IAAI;EACJ,IAAI;CACN;CAEA,OAAO,QAAQ,QAAQ;AACzB"}
package/dist/paths.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"paths.js","names":[],"sources":["../src/paths.ts"],"sourcesContent":["import type * as lsp from 'vscode-languageserver-protocol'\n\nexport function sourcePathToFileName(path: string): string {\n if (hasUriScheme(path)) return documentUriToFileName(path) ?? normalizeFileNamePath(path)\n return normalizeFileNamePath(path)\n}\n\nexport function pathOrUriToDocumentUri(pathOrUri: string): lsp.DocumentUri {\n if (!hasUriScheme(pathOrUri)) return fileNameToDocumentUri(sourcePathToFileName(pathOrUri))\n\n const fileName = documentUriToFileName(pathOrUri)\n if (!fileName) return pathOrUri\n return fileNameToDocumentUri(fileName)\n}\n\nexport function fileNameToDocumentUri(fileName: string): lsp.DocumentUri {\n const normalized = normalizeFileNamePath(fileName)\n return `file://${encodePathname(normalized)}`\n}\n\nexport function documentUriToFileName(uri: string): string | null {\n try {\n const url = new URL(uri)\n if (url.protocol !== 'file:') return null\n return normalizeFileNamePath(decodeURIComponent(url.pathname))\n } catch {\n return null\n }\n}\n\nfunction normalizeFileNamePath(path: string): string {\n const normalized = path.replaceAll('\\\\', '/').replace(/^\\/+/, '')\n if (!normalized) return '/'\n return `/${normalized}`\n}\n\nfunction encodePathname(pathname: string): string {\n return pathname\n .split('/')\n .map((part, index) => (index === 0 && part === '' ? '' : encodeURIComponent(part)))\n .join('/')\n}\n\nfunction hasUriScheme(value: string): boolean {\n return /^[A-Za-z][A-Za-z0-9+.-]*:/.test(value)\n}\n"],"mappings":";AAEA,SAAgB,qBAAqB,MAAsB;CACzD,IAAI,aAAa,IAAI,GAAG,OAAO,sBAAsB,IAAI,KAAK,sBAAsB,IAAI;CACxF,OAAO,sBAAsB,IAAI;AACnC;AAEA,SAAgB,uBAAuB,WAAoC;CACzE,IAAI,CAAC,aAAa,SAAS,GAAG,OAAO,sBAAsB,qBAAqB,SAAS,CAAC;CAE1F,MAAM,WAAW,sBAAsB,SAAS;CAChD,IAAI,CAAC,UAAU,OAAO;CACtB,OAAO,sBAAsB,QAAQ;AACvC;AAEA,SAAgB,sBAAsB,UAAmC;CAEvE,OAAO,UAAU,eADE,sBAAsB,QACT,CAAU;AAC5C;AAEA,SAAgB,sBAAsB,KAA4B;CAChE,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,GAAG;EACvB,IAAI,IAAI,aAAa,SAAS,OAAO;EACrC,OAAO,sBAAsB,mBAAmB,IAAI,QAAQ,CAAC;CAC/D,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,sBAAsB,MAAsB;CACnD,MAAM,aAAa,KAAK,WAAW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