@hydranium/data-server 1.0.0-next.17 → 1.0.0-next.174

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.
@@ -6,13 +6,52 @@
6
6
  *
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
- import { DisposableCollection, ReferenceSource, type CloseModelArgs, type Disposable, type ElementSource, type FindNextNameArgs, type LatencyCollector, type LatencyReport, type OpenModelArgs, type Project, type ReferenceCandidate, type ReferenceContext, type ReferenceRequest, type ReferenceTarget, type Tracer, type TransferDiagnostic, type TransferDocument, type TransferElement } from '@hydranium/protocol';
10
- import { type DataClientProtocol, type DataServerDiagnosticsProtocol, type DataServerProtocol, type DumpServerStateArgs, type StartProfilingArgs, type StopProfilingArgs, type WriteServerHeapSnapshotArgs, type GetModelDocumentArgs, type GetProjectForUriArgs, type TransferSaveDocumentArgs, type WatchModelDocumentArgs, type TransferDocumentUpdatedEvent, type TransferUpdateDocumentArgs } from '@hydranium/protocol/data';
9
+ import { DisposableCollection, ReferenceSource, type CloseModelArgs, type HydraniumMessageData, type HydraniumResponseError, type Disposable, type ElementSource, type FindNextNameArgs, type LatencyCollector, type LatencyReport, type OpenModelArgs, type Project, type ReferenceCandidate, type ReferenceContext, type ReferenceRequest, type ReferenceTarget, type Tracer, type TransferDiagnostic, TransferDocument, type TransferElement } from '@hydranium/protocol';
10
+ import { type DataClientProtocol, type DataServerDiagnosticsProtocol, type DataServerProtocol, type DumpServerStateArgs, type StartProfilingArgs, type StopProfilingArgs, type WriteServerHeapSnapshotArgs, type CloseSessionArgs, type CreateModelDocumentArgs, type CreateSessionArgs, type GetModelDocumentArgs, type GetProjectForUriArgs, type TransferSaveDocumentArgs, type WatchModelDocumentArgs, type TransferUpdateDocumentArgs, type TransferUpdateDocumentsArgs } from '@hydranium/protocol/data';
11
+ /**
12
+ * Raised when a profiling command arrives with no capture running.
13
+ *
14
+ * A `ResponseError` rather than a plain `Error` so the identity survives to the
15
+ * response boundary, which is where the message is rendered. An unwrapped throw
16
+ * reaches the client as a generic internal error instead: no code for a caller
17
+ * to switch on, and nothing for the boundary to render from.
18
+ */
19
+ export declare const NO_ACTIVE_PROFILE: import("@hydranium/protocol").MessageDefinition<"No profiling capture is active; call startProfiling first.">;
20
+ /**
21
+ * The JSON-RPC code, unrelated to the catalogue code above: this one is numeric,
22
+ * survives reconstruction and is what a caller switches on.
23
+ */
24
+ export declare const NO_ACTIVE_PROFILE_CODE: 42002;
25
+ export declare const noActiveProfileError: () => HydraniumResponseError;
26
+ /**
27
+ * Raised when a reference question's wait for the build exceeds
28
+ * {@link DataServerOptions.referenceSettleTimeoutMs}.
29
+ *
30
+ * A `ResponseError` because a class name does not cross RPC: without the code a
31
+ * wire client cannot tell a wedged build from a reference that resolves to
32
+ * nothing, which is the distinction the wait exists to keep.
33
+ */
34
+ export declare const REFERENCE_SETTLE_TIMEOUT: import("@hydranium/protocol").MessageDefinition<"The model is still being processed; try again in a moment.">;
35
+ /** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */
36
+ export declare const REFERENCE_SETTLE_TIMEOUT_CODE: 42003;
37
+ /** The wait's length rides in `data` as `elapsedMs`, for the code that reacts rather than the reader. */
38
+ export declare const referenceSettleTimeoutError: (elapsedMs: number) => ResponseError<HydraniumMessageData & {
39
+ readonly elapsedMs: number;
40
+ }>;
11
41
  import type { DataServerDiagnosticsProvider, DataServerProfileCapture } from './diagnostics-provider.js';
12
- import type { ClientTextDocumentChangeEvent, HydraniumLanguageServices, LogNameOptions, ModelService, ProjectChangeEvent, ServerSharedServices, TransferEncoder } from '@hydranium/core';
42
+ import type { ClientSession, ClientSessionWriteArgs, ClientTextDocumentChangeEvent, DocumentDirtyChangedEvent, HydraniumLanguageServices, LogNameOptions, AstDiagnostic, AstDocument, ModelService, ProjectChangeEvent, ServerSharedServices, SessionEndCause, TransferEncoder } from '@hydranium/core';
13
43
  import type { TextDocument } from 'vscode-languageserver-textdocument';
14
44
  import { type AstNode, DocumentState, type LangiumDocument, type URI } from '@hydranium/langium';
15
- import type { CancellationToken, MessageConnection } from 'vscode-jsonrpc';
45
+ import { type CancellationToken, type MessageConnection, ResponseError } from 'vscode-jsonrpc';
46
+ /**
47
+ * A session a data connection registered with a resume token, and how to end
48
+ * it from another connection. See {@link DataServer.resumableSessions}.
49
+ */
50
+ export interface ResumableSession {
51
+ readonly token: string;
52
+ /** End the session as its connection closing would. */
53
+ readonly end: () => void;
54
+ }
16
55
  /**
17
56
  * Which observable state {@link DataServer.computeDocumentFingerprint} hashes to
18
57
  * de-dup `onDocumentUpdated` emissions.
@@ -39,12 +78,13 @@ export interface DataServerOptions extends LogNameOptions {
39
78
  * (`DataClientProtocol.onDocumentUpdated`).
40
79
  *
41
80
  * **Subscription dispatch only** — distinct from the synchronous RPC
42
- * response phase. The lifecycle reads/writes (`getModelDocument` /
43
- * `updateModelDocument` / `saveModelDocument`) settle at the
44
- * integrity-settled landmark (`IntegrityService.SettledState`); a
45
- * read additionally upgrades to `Validated` per call when
46
- * {@link GetModelDocumentArgs.includeDiagnostics} is set. This option
47
- * controls only the async notification phase.
81
+ * response phase. A read (`getModelDocument`) settles at the
82
+ * integrity-settled landmark (`IntegrityService.SettledState`), or at
83
+ * `Validated` when {@link GetModelDocumentArgs.includeDiagnostics} is set.
84
+ * A write (`updateModelDocument` / `updateModelDocuments` /
85
+ * `saveModelDocument`) answers once its document is validated, as a
86
+ * session's write does. This option controls only the async notification
87
+ * phase.
48
88
  *
49
89
  * Default: `DocumentState.Validated` — validation is the last builder
50
90
  * phase and produces the full diagnostic set, so subscription events fired
@@ -82,6 +122,21 @@ export interface DataServerOptions extends LogNameOptions {
82
122
  * state included). See {@link FingerprintStrategy}.
83
123
  */
84
124
  readonly fingerprintStrategy?: FingerprintStrategy;
125
+ /**
126
+ * How long a reference question waits for the build to reach `Linked` before
127
+ * failing with {@link REFERENCE_SETTLE_TIMEOUT_CODE}. Bounded because the
128
+ * wait resolves off a build-phase notification, so a build cancelled below
129
+ * `Linked` with nothing after it leaves the request unanswered for the life
130
+ * of the server.
131
+ *
132
+ * Expiry rejects rather than reading the index anyway: the unsettled index
133
+ * is what the wait keeps the caller away from, so falling through to it on a
134
+ * slow build reinstates the fault — and on a name proposal persists it.
135
+ *
136
+ * Default {@link DataServer.DEFAULT_OPTIONS}, sized for a cold workspace
137
+ * still reaching `Linked` for the first time.
138
+ */
139
+ readonly referenceSettleTimeoutMs?: number;
85
140
  /**
86
141
  * Wire-method namespace for both inbound request handlers and the
87
142
  * outbound notification client proxy. Defaults to
@@ -136,14 +191,19 @@ export interface DataServerOptions extends LogNameOptions {
136
191
  * When supplied, every inbound data-server RPC is timed into this collector
137
192
  * (via the `createRpcProxy` binding) and exposed through
138
193
  * {@link DataServerDiagnosticsProtocol.getLatency}. A head that also runs an
139
- * LSP connection can pass the SAME collector to
140
- * `instrumentLspConnection(connection, latency)` so one report covers both
141
- * heads. Absent by default (no timing overhead).
194
+ * LSP connection can pass the SAME collector through `lspLatencyOptions` to
195
+ * that connection, so one report covers both heads. Absent by default (no
196
+ * timing overhead).
142
197
  */
143
198
  readonly latency?: LatencyCollector;
144
199
  }
145
- /** Fully-resolved variant — every field set, used internally after merging defaults. */
146
- interface ResolvedDataServerOptions {
200
+ /**
201
+ * Fully-resolved variant of {@link DataServerOptions} — every field set, after
202
+ * merging defaults. Returned by the `protected`
203
+ * {@link DataServer.resolveOptions} and held on {@link DataServer.options}, so
204
+ * an adopter changing how defaults resolve has to name it.
205
+ */
206
+ export interface ResolvedDataServerOptions {
147
207
  readonly subscriptionPhase: DocumentState;
148
208
  readonly fingerprintStrategy: FingerprintStrategy;
149
209
  readonly methodNamespace: string;
@@ -151,6 +211,33 @@ interface ResolvedDataServerOptions {
151
211
  readonly excludedMethods: readonly string[];
152
212
  /** Always resolved — to the caller's, or to the platform default. */
153
213
  readonly diagnostics: DataServerDiagnosticsProvider;
214
+ readonly referenceSettleTimeoutMs: number;
215
+ }
216
+ /**
217
+ * What a {@link DataServer} keeps per canonical URI, in the `protected`
218
+ * {@link DataServer.uriWatchRecords}. A record lives while it has a watcher
219
+ * or a revert mark; {@link DataServer.pruneUriWatchRecord} enforces that on
220
+ * every path that removes either, so a record with no watcher has a revert
221
+ * pending. Test the size of {@link DataServerUriWatchRecord.watchers}, not the
222
+ * record's presence, for "watched".
223
+ */
224
+ export interface DataServerUriWatchRecord {
225
+ /** The client ids watching the URI; save, dirty and phase events go out only while it is non-empty, a pending revert aside. */
226
+ readonly watchers: Set<string>;
227
+ /** Digest of the last emitted state, or of the state a first watch found; see {@link DataServer.dispatchPhaseEvent} for why it de-duplicates, {@link DataServer.computeDocumentFingerprint} for its inputs. */
228
+ fingerprint?: string;
229
+ /** Set by {@link DataServer.subscribeToTextDocumentCloses}; the next phase event broadcasts even without a watcher. */
230
+ revertPending?: boolean;
231
+ /**
232
+ * The version of an open document the last event sent was built at. The
233
+ * version sent again goes out as `'rebuilt'` from no client: the manager
234
+ * counts a version delivered only once its `Validated` listeners ran, so a
235
+ * build cancelled after the subscription phase would send it as a change
236
+ * twice. Only while the store has the document open: without it, a
237
+ * document can keep one version through changes of its file, so its events
238
+ * keep the manager's attribution.
239
+ */
240
+ sentVersion?: number;
154
241
  }
155
242
  /**
156
243
  * Typed-RPC protocol head for the hydranium framework. The data-server
@@ -177,9 +264,11 @@ interface ResolvedDataServerOptions {
177
264
  * any names supplied via {@link DataServerOptions.additionalMethods}) and
178
265
  * builds the {@link DataClientProtocol} notification proxy on the same
179
266
  * connection in one {@link createRpcProxy} call (binding `this` as its
180
- * `localTarget`) under the configured namespace, and subscribes one
181
- * `DocumentBuilder.onDocumentPhase` listener per configured phase that
182
- * dispatches subscription events via `clientProxy.onDocumentUpdated`.
267
+ * `localTarget`) under the configured namespace, and subscribes two listeners
268
+ * at the configured phase: a `DocumentBuilder.onDocumentPhase` one dispatching
269
+ * per-document `clientProxy.onDocumentUpdated` for watched URIs, and a
270
+ * `DocumentBuilder.onBuildPhase` one dispatching a single
271
+ * `clientProxy.onDocumentsBuilt` naming the batch's unwatched documents.
183
272
  *
184
273
  * The data-server requires the full {@link ServerSharedServices}
185
274
  * shape — `HydraniumTextDocuments` for client-attributed updates,
@@ -198,92 +287,28 @@ interface ResolvedDataServerOptions {
198
287
  */
199
288
  export declare class DataServer<TTransfer extends TransferElement, TDiagnostic extends TransferDiagnostic = TransferDiagnostic, TProject extends Project = Project> implements DataServerProtocol<TTransfer, TDiagnostic, TProject>, DataServerDiagnosticsProtocol, Disposable {
200
289
  protected readonly connection: MessageConnection;
201
- protected readonly services: ServerSharedServices<TProject>;
290
+ protected readonly services: ServerSharedServices<TProject, TDiagnostic>;
202
291
  /**
203
292
  * Framework defaults, exposed so an adopter can spread them when
204
293
  * extending rather than restate a value the framework may change.
205
294
  */
206
- static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase'>>;
295
+ static readonly DEFAULT_OPTIONS: Required<Pick<DataServerOptions, 'subscriptionPhase' | 'referenceSettleTimeoutMs'>>;
207
296
  protected readonly options: ResolvedDataServerOptions;
208
- /** Subscription bookkeeping: URI → set of clientIds that subscribed for that URI. */
209
- protected readonly subscriptions: Map<string, Set<string>>;
297
+ /** This connection's {@link DataServerUriWatchRecord} per canonical URI; see there for when a record lives. */
298
+ protected readonly uriWatchRecords: Map<string, DataServerUriWatchRecord>;
210
299
  /**
211
- * Open-document bookkeeping: URI → set of clientIds that opened it over THIS
212
- * connection.
300
+ * The client sessions this connection registered, by client id. A document
301
+ * request carrying one of these ids acts as that session; one carrying any
302
+ * other id fails.
213
303
  *
214
- * Kept because the document store releases a client's hold only from an
215
- * explicit close, and a client that dies without closing would otherwise keep
216
- * the document open forever — resident, and with its last-close revert
217
- * suppressed. The store has no notion of which connection a clientId reached
218
- * it over, so the connection-scoped set has to live here; teaching it a client
219
- * identity is the more robust and much larger alternative.
304
+ * Entries stay after {@link dispose} has ended their sessions, so a request
305
+ * still running from before the connection closed reaches the ended handle
306
+ * and fails with the session's own error.
220
307
  */
221
- protected readonly openedDocuments: Map<string, Set<string>>;
308
+ protected readonly clientSessions: Map<string, ClientSession<AstNode, AstDiagnostic, TTransfer, object>>;
222
309
  /** Typed client proxy — sends `data-server/on*` notifications back over the same wire. */
223
310
  protected readonly clientProxy: DataClientProtocol<TTransfer, TDiagnostic, TProject>;
224
311
  protected readonly disposables: DisposableCollection;
225
- /**
226
- * Snapshot of the most recent `DocumentBuilder.onUpdate` event. Drives
227
- * `reason` discrimination on outbound `onDocumentUpdated` notifications:
228
- * a URI in the `changed` list emits `'changed'`, in `deleted` emits
229
- * `'deleted'`, otherwise `'rebuilt'` (cascade rebuild from a dependent
230
- * URI's change). The same mechanism `AstDocumentManager.onUpdate` uses on
231
- * the LSP side, so reason fidelity stays consistent between heads.
232
- */
233
- protected lastBuildUpdate?: {
234
- changed: readonly URI[];
235
- deleted: readonly URI[];
236
- };
237
- /**
238
- * Per-URI hash of the last emitted (text + diagnostics) state,
239
- * used by {@link dispatchPhaseEvent} to suppress duplicate
240
- * `onDocumentUpdated` notifications for rebuilds that produce no
241
- * observable change since the last emit.
242
- *
243
- * Two scenarios routinely produce such rebuilds:
244
- * 1. **Refresh-triggered rebuilds.** When a second client attaches to a
245
- * document already open in another client,
246
- * `HydraniumTextDocuments.refreshContent` fires `onDidChangeContent`
247
- * purely to re-trigger the build pipeline — the text and diagnostics
248
- * are identical to the prior emit.
249
- * 2. **Cascade rebuilds with no diagnostic delta.** Langium rebuilds a
250
- * document when a dependency changes; if the rebuild produces the
251
- * same diagnostics, there is nothing new to communicate to subscribers.
252
- *
253
- * Without this filter, both scenarios reach subscribers as wire-side
254
- * `'changed'` events. A subscriber that interprets `'changed'` as
255
- * "another client wrote new content" and resets its in-memory root to
256
- * the server view then misreads the spurious event as a concurrent
257
- * third-party write and loses the user's edits.
258
- *
259
- * Initialised on {@link watchModelDocument} to the current
260
- * document fingerprint so the FIRST phase event after a fresh
261
- * subscription is also de-duplicated against the state subscribers
262
- * obtained via `getModelDocument` — they do not need a redundant phase
263
- * notification for the state they just fetched.
264
- *
265
- * Cleared in {@link unwatchModelDocument} when the last
266
- * subscriber for a URI leaves so memory does not accumulate.
267
- *
268
- * Stored as a cyrb53 hex digest (16 chars per URI) rather than the raw
269
- * text + diagnostics serialisation so the memory cost is constant in
270
- * document size. See {@link computeDocumentFingerprint} for the inputs.
271
- */
272
- protected readonly lastEmittedFingerprint: Map<string, string>;
273
- /**
274
- * URIs whose LAST client just closed. The update handler rebuilds such a
275
- * document from its disk content (discarding unsaved in-session edits),
276
- * but {@link dispatchPhaseEvent} gates on the subscription map — and the
277
- * last close typically also removed the last watcher, so consumers that
278
- * only ever fetch via `getModelDocument` would keep showing the
279
- * discarded state forever. Marked on the last-close transition (see
280
- * {@link subscribeToTextDocumentCloses}) and consumed by
281
- * {@link dispatchPhaseEvent}, which broadcasts the following rebuild's
282
- * phase event even without a subscription — de-duplicated against
283
- * {@link lastEmittedFingerprint} where an entry survives, so a close
284
- * whose disk state equals the last emitted state stays silent.
285
- */
286
- protected readonly pendingRevertBroadcasts: Set<string>;
287
312
  protected readonly tracer: Tracer;
288
313
  /** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */
289
314
  protected activeProfile?: DataServerProfileCapture;
@@ -292,55 +317,83 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
292
317
  /** Per-method RPC latency collector, when the head opted in via {@link DataServerOptions.latency}. */
293
318
  protected readonly latency?: LatencyCollector;
294
319
  /** Encoder pulled from DI. Adopters rebind `services.model.TransferEncoder` to a typed-overlay subclass. */
295
- protected readonly encoder: TransferEncoder<unknown, TDiagnostic>;
320
+ protected readonly encoder: TransferEncoder<TDiagnostic>;
296
321
  /**
297
322
  * In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through.
298
- * The facade's AstDocument diagnostic shape is intentionally typed `unknown` here: adopters
299
- * carry LSP-shape diagnostics in their AstDocument (e.g. an adopter's LSP-shape diagnostic type)
300
- * while the wire shape stays `TDiagnostic extends TransferDiagnostic`. The encoder's
301
- * `astDocumentToTransferDocument` accepts both shapes (wire-shape or LSP-shape) and projects
302
- * to wire shape on the return — see `TransferEncoder.astDocumentToTransferDocument`.
323
+ * Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`:
324
+ * {@link encoder} converts one into the other on the way out.
303
325
  */
304
- protected readonly modelService: ModelService<AstNode, unknown, TTransfer>;
305
- constructor(connection: MessageConnection, services: ServerSharedServices<TProject>, options?: DataServerOptions);
326
+ protected readonly modelService: ModelService<AstNode, AstDiagnostic, TTransfer>;
327
+ constructor(connection: MessageConnection, services: ServerSharedServices<TProject, TDiagnostic>, options?: DataServerOptions);
306
328
  /**
307
329
  * Release everything the constructor wired up — the bound protocol
308
- * handlers and every listener — and clear the subscription map and the
309
- * per-URI emission-fingerprint cache, so a long-lived shared services
310
- * bundle does not retain per-connection memory after the connection
311
- * closes. Also closes every document still open over this connection (see
312
- * {@link closeOpenDocuments}), which is the SHARED store's state rather than
313
- * this server's and so outlives the connection unless released here.
314
- *
315
- * Idempotent: subsequent calls are no-ops. Self-fires on
316
- * `connection.onClose` so adopters who don't hold a reference still
317
- * get per-connection cleanup; adopters that DO hold a reference may
318
- * call `dispose()` directly for early teardown.
319
- */
320
- dispose(): void;
321
- openModelDocument(args: OpenModelArgs): Promise<TransferDocument<TTransfer, TDiagnostic>>;
330
+ * handlers and every listener — and clear {@link uriWatchRecords}, so a
331
+ * long-lived shared services bundle does not retain per-connection memory
332
+ * after the connection closes. Also ends every session this connection registered, which closes
333
+ * every document it has open: the SHARED store's state rather than this
334
+ * server's, which outlives the connection unless released here.
335
+ *
336
+ * Idempotent: subsequent calls are no-ops. Runs by itself when the
337
+ * connection closes, so adopters who don't hold a reference still get
338
+ * per-connection cleanup; adopters that DO hold a reference may call
339
+ * `dispose()` directly for early teardown. The sessions end with `cause`:
340
+ * `'closed'` reverts every document whose last open they close at once,
341
+ * and `'lost'`, the connection's own close, lets each wait out the revert
342
+ * grace.
343
+ */
344
+ dispose(cause?: SessionEndCause): void;
345
+ createSession(args: CreateSessionArgs): Promise<void>;
346
+ /**
347
+ * End a session this connection registered. The ended handle stays in
348
+ * {@link clientSessions}, as it does after {@link dispose}, so a request for
349
+ * the id still arriving fails with the ended session's own error.
350
+ */
351
+ closeSession(args: CloseSessionArgs): Promise<void>;
352
+ /** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */
353
+ protected endSession(clientId: string, session: ClientSession<AstNode, AstDiagnostic, TTransfer>, cause?: SessionEndCause): void;
354
+ /**
355
+ * The resumable sessions of this services tree, by client id, across all of
356
+ * its data connections: a client resumes on another connection than the one
357
+ * that registered it. An entry leaves when its session ends, by any path, so
358
+ * it keeps no ended connection alive.
359
+ *
360
+ * A takeover by resume token ends the old session even when its connection
361
+ * is still alive, so two clients that shared an id and its token would end
362
+ * each other's sessions. And the token is a guard against colliding with a
363
+ * session the server has not yet seen end, not a secret: the wire carries no
364
+ * authentication, and a peer that learns the token can end the session.
365
+ */
366
+ protected resumableSessions(): Map<string, ResumableSession>;
367
+ createModelDocument(args: CreateModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>>;
368
+ updateModelDocuments(args: TransferUpdateDocumentsArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>[]>;
369
+ /**
370
+ * The session write a wire write request carries. Only the fields a session
371
+ * takes: a field an adopter adds to a request reaches the session only
372
+ * through an override of this.
373
+ */
374
+ protected toSessionWrite(request: Omit<TransferUpdateDocumentArgs<TTransfer>, 'clientId'>): ClientSessionWriteArgs<TTransfer>;
375
+ /**
376
+ * The session this connection registered under `clientId`, which every
377
+ * document request acts as. An id that is not one fails with the
378
+ * closed-session code: opening or writing under it would leave an open that
379
+ * no session end ever closes.
380
+ */
381
+ protected requireSession(clientId: string): ClientSession<AstNode, AstDiagnostic, TTransfer>;
382
+ openModelDocument(args: Pick<OpenModelArgs, 'uri' | 'clientId' | 'options'>): Promise<TransferDocument<TTransfer, TDiagnostic>>;
383
+ /**
384
+ * The snapshot a session's open or create answers with. When the read
385
+ * fails, `rollback` undoes the open this call made before the failure is
386
+ * rethrown: the caller sees no open, so nothing on its side would ever close
387
+ * it.
388
+ *
389
+ * Versioned with the store's shared version rather than the snapshot's own:
390
+ * the built document's `textDocument.version` lags the store's whenever the
391
+ * store assigned the version, and the store's is what a write's `basedOn` is
392
+ * compared against, so reporting the snapshot's would make the caller's
393
+ * first based-on write conflict with itself.
394
+ */
395
+ protected openedSnapshot(uri: string, rollback?: () => Promise<void>): Promise<TransferDocument<TTransfer, TDiagnostic>>;
322
396
  closeModelDocument(args: CloseModelArgs): Promise<void>;
323
- /**
324
- * Drop the recorded hold for `(uri, clientId)` so {@link dispose} does not
325
- * close it a second time. Idempotent.
326
- */
327
- protected forgetOpenDocument(uri: string, clientId: string): void;
328
- /**
329
- * Close every document still open over this connection, for the clients that
330
- * opened it here.
331
- *
332
- * The document store releases a per-URI hold only from an explicit close, so
333
- * without this a client that dies mid-session keeps its documents open for the
334
- * lifetime of the process: `isOpenInAnyClient` stays true, the document stays
335
- * resident, and the last-close revert never runs. A long-lived multi-client
336
- * head is the configuration where a dead client is normal rather than
337
- * exceptional, so the leak accumulates there.
338
- *
339
- * Runs from {@link dispose}, which is synchronous, so each close is fired and
340
- * its failure swallowed — a teardown must not reject, and a URI whose close
341
- * fails is no worse off than it was before this drain existed.
342
- */
343
- protected closeOpenDocuments(): void;
344
397
  getModelDocument(args: GetModelDocumentArgs): Promise<TransferDocument<TTransfer, TDiagnostic>>;
345
398
  updateModelDocument(args: TransferUpdateDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>>;
346
399
  saveModelDocument(args: TransferSaveDocumentArgs<TTransfer>): Promise<TransferDocument<TTransfer, TDiagnostic>>;
@@ -349,31 +402,36 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
349
402
  * fan out to the wired `clientProxy.onDocumentUpdated`. The
350
403
  * bidirectional pattern means the event channel is the client
351
404
  * notification surface, not a returned handle — this method only
352
- * registers the URI in the dispatch table.
405
+ * registers the watcher in {@link uriWatchRecords}.
353
406
  *
354
- * Also baselines the per-URI emission fingerprint (see
355
- * {@link lastEmittedFingerprint}) to the document's current state when
356
- * the first watcher for the URI registers. This guarantees that any
357
- * phase event firing immediately after the watch with no observable
358
- * change is suppressed — watchers obtain initial state via
359
- * `getModelDocument` (or {@link openModelDocument}) and do not need a
360
- * redundant phase notification for that same state.
407
+ * Also baselines the URI's emission fingerprint (see
408
+ * {@link dispatchPhaseEvent}) to the document's current state when the
409
+ * first watcher for the URI registers. This guarantees that any phase event firing immediately after
410
+ * the watch with no observable change is suppressed — watchers obtain
411
+ * initial state via `getModelDocument` (or {@link openModelDocument}) and
412
+ * do not need a redundant phase notification for that same state.
361
413
  */
362
414
  watchModelDocument(args: WatchModelDocumentArgs): Promise<void>;
363
415
  /**
364
416
  * Remove a watch for `(uri, clientId)` previously created by
365
417
  * {@link watchModelDocument}. Idempotent — unwatching twice is a no-op.
366
- * Dispatch for `uri` stops once no watchers remain, at which point the
367
- * per-URI emission fingerprint is also cleared so the next first-watch
368
- * re-baselines against the then-current document state rather than a
369
- * stale snapshot from the previous watch.
418
+ * Dispatch for `uri` stops once no watchers remain, and the emission
419
+ * fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}).
370
420
  */
371
421
  unwatchModelDocument(args: WatchModelDocumentArgs): Promise<void>;
372
422
  /**
373
- * Canonicalise a URI string for use as a subscription / fingerprint
374
- * map key, via the shared `DocumentUriPolicy`. Callers may send
375
- * non-canonical URIs (drive-letter casing, percent-encoding differences,
376
- * or a symlink path) over the wire; the dispatch side keys by
423
+ * Drop what `uri` no longer needs: the
424
+ * {@link DataServerUriWatchRecord.fingerprint} once no client watches it,
425
+ * and the whole record once it holds no
426
+ * {@link DataServerUriWatchRecord.revertPending} mark either. Every path
427
+ * that removes a watcher or consumes a mark ends here.
428
+ */
429
+ protected pruneUriWatchRecord(uri: string): void;
430
+ /**
431
+ * Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the
432
+ * shared `DocumentUriPolicy`. Callers may send non-canonical URIs
433
+ * (drive-letter casing, percent-encoding differences, or a symlink path)
434
+ * over the wire; the dispatch side keys by
377
435
  * `document.uri.toString()` from `LangiumDocuments`, so writer keys must
378
436
  * canonicalise to the same form or events silently fail to deliver.
379
437
  * Routing through the seam (rather than a bare `UriUtils.normalize`)
@@ -395,6 +453,23 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
395
453
  * subclass.
396
454
  */
397
455
  waitForReady(): Promise<void>;
456
+ /**
457
+ * Settle the build before a reference question is answered from the index.
458
+ *
459
+ * A query issued right after a model update otherwise races the rebuild and
460
+ * reads an index missing the symbols it asks about. The cost is not confined
461
+ * to this call: a scope built inside that window is cached, and the build's
462
+ * remaining documents link against it.
463
+ *
464
+ * Waits the source document specifically, but ONLY when one is loaded at
465
+ * that URI: a synthetic source can address a URI with no document (a
466
+ * directory URI, typically), where a per-URI `waitUntil` throws "No document
467
+ * found". Falls back to a global settle, matching the id-based
468
+ * `ElementSource` path.
469
+ *
470
+ * Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}.
471
+ */
472
+ protected awaitReferencesLinked(source: ReferenceSource): Promise<void>;
398
473
  findReferenceCandidates(ctx: ReferenceContext): Promise<ReferenceCandidate[]>;
399
474
  resolveReference(ref: ReferenceRequest): Promise<ReferenceTarget<TTransfer> | undefined>;
400
475
  findNextName(args: FindNextNameArgs): Promise<string>;
@@ -409,6 +484,9 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
409
484
  /**
410
485
  * Pick the language that owns a reference source, in order:
411
486
  *
487
+ * 0. A {@link isSyntheticSource} naming its own `language` routes there.
488
+ * First because every step below infers, and an inference must not
489
+ * override a caller that has said which grammar it means.
412
490
  * 1. A URI-bearing source ({@link isDocumentSource}/{@link isSyntheticSource})
413
491
  * whose URI resolves to a registered language routes by URI.
414
492
  * 2. A single-language workspace always routes to that one language — so
@@ -469,6 +547,15 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
469
547
  * to.
470
548
  */
471
549
  protected fallbackReferenceLanguage(_source: ReferenceSource): HydraniumLanguageServices | undefined;
550
+ /**
551
+ * Whether `error`, from waiting on `uri`'s document, means that `uri` has
552
+ * no document: a URI with neither a file nor text builds nothing, and
553
+ * Langium's wait after the build rejects for want of one, with a
554
+ * `ServerCancelled` response error. Any other failure, such as a read
555
+ * that fails before a document is registered, a cancelled wait or a
556
+ * `ReentrantWriteLockError`, is the caller's to see.
557
+ */
558
+ protected isMissingDocument(error: unknown, uri: string): boolean;
472
559
  /**
473
560
  * Build a {@link TransferDocument} envelope from the current document state,
474
561
  * delegating root + diagnostic encoding to {@link encoder} (see
@@ -482,6 +569,22 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
482
569
  * single boundary point rather than spread across the callers.
483
570
  */
484
571
  protected envelope(uri: URI): TransferDocument<TTransfer, TDiagnostic>;
572
+ /**
573
+ * The transfer document a request answers with for `astDocument`, the
574
+ * store's current `dirty` and `textHash` stamped on it by
575
+ * {@link withServerState}. Every document a request answers with goes
576
+ * through here, so none goes out without the stamp.
577
+ */
578
+ protected encodeDocument(astDocument: AstDocument<AstNode, AstDiagnostic>): TransferDocument<TTransfer, TDiagnostic>;
579
+ /**
580
+ * `document` with the store's current {@link TransferDocument.dirty} and
581
+ * the {@link TransferDocument.textHash} of the text the server holds for
582
+ * it: the store's text while a client has it open, the build's otherwise.
583
+ * Both are read when the document is sent rather than kept with the build:
584
+ * a save changes `dirty` without a rebuild, and the store's text moves on
585
+ * before the build that follows it.
586
+ */
587
+ protected withServerState(document: TransferDocument<TTransfer, TDiagnostic>): TransferDocument<TTransfer, TDiagnostic>;
485
588
  /**
486
589
  * Subscribe one listener at the configured {@link DataServerOptions.subscriptionPhase}.
487
590
  * The listener dispatches subscription events for every matching URI. A
@@ -489,6 +592,42 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
489
592
  * regardless of subscriber count.
490
593
  */
491
594
  protected subscribeToDocumentBuilder(): void;
595
+ /**
596
+ * Report the documents that reached {@link DataServerOptions.subscriptionPhase}
597
+ * and that NOBODY on this
598
+ * connection is watching — the ones a client was not told about through
599
+ * {@link dispatchPhaseEvent}, which is gated per URI.
600
+ *
601
+ * **The gap this closes is the one no other source can observe.** A document
602
+ * the client watches, it hears about already. A file changed on disk, the
603
+ * host's own filesystem watcher reports — and on a browser host, where the
604
+ * workspace lives behind this head, an external change cannot happen at all.
605
+ * What is left, and what nothing outside the server can see, is a document
606
+ * rebuilt because something it DEPENDS ON changed: its file never changed, so
607
+ * a filesystem watcher is silent by construction, and it has no subscriber, so
608
+ * the update channel is silent by design. A consumer displaying data derived
609
+ * from that document — a tree label, a decorator — otherwise goes stale with
610
+ * no signal from any source, and repairs itself the moment someone opens the
611
+ * file to investigate, which is what makes it expensive to diagnose later.
612
+ *
613
+ * Payload-free on purpose: URIs only, so a client re-reads what it displays
614
+ * rather than being handed transfer documents it did not ask for. That is the
615
+ * property the watcher gate protects, and it is preserved here by
616
+ * carrying no document rather than by gating the message.
617
+ *
618
+ * Quiet in the common case. Editing a document that an editor has open leaves
619
+ * that URI watched and therefore out of this set, so a build with no
620
+ * dependents produces nothing at all, and workspace initialisation produces
621
+ * nothing because it does not build to this phase. The ceiling is a
622
+ * whole-workspace rebuild at the subscription phase: one message, URIs only.
623
+ *
624
+ * The URI is canonicalised for the same reason {@link uriWatchRecords} is keyed
625
+ * that way, and is untested for the same reason as its twin in
626
+ * {@link dispatchDeleteEvents}: the builder reports URIs out of its own
627
+ * store, so a non-canonical one cannot be produced without a fixture
628
+ * asserting a shape the real system never emits.
629
+ */
630
+ protected dispatchBuiltEvent(built: readonly LangiumDocument[]): void;
492
631
  /**
493
632
  * Subscribe to the universal save event on `HydraniumTextDocuments` so a
494
633
  * single `onDocumentSaved` wire notification fires for ANY save of a
@@ -504,14 +643,73 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
504
643
  * clients, which never clear their dirty state.
505
644
  */
506
645
  protected subscribeToTextDocumentSaves(): void;
507
- /**
508
- * Mark the last-close transition per URI (see
509
- * {@link pendingRevertBroadcasts}). The listener consults
510
- * `isOpenInAnyClient` AFTER the store decremented the closing client's
511
- * hold, so a `false` answer means this close was the last one.
646
+ /** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */
647
+ protected subscribeToDirtyChanges(): void;
648
+ /**
649
+ * Send a dirty flip to the connection, gated on the URI's watchers as
650
+ * {@link dispatchSaveEvent} is: the answer at any one moment travels on
651
+ * every document sent, so a client that watches nothing reads it there.
652
+ */
653
+ protected dispatchDirtyEvent(event: DocumentDirtyChangedEvent): void;
654
+ /**
655
+ * Mark each document the store releases after its last close, so
656
+ * {@link dispatchPhaseEvent} broadcasts the following rebuild even without
657
+ * a watcher. The store rebuilds such a document from its disk content,
658
+ * discarding unsaved in-session edits, and the last close typically also
659
+ * removed the last watcher: without the broadcast, a consumer that only
660
+ * ever fetches via `getModelDocument` keeps showing the discarded state.
661
+ * The broadcast is de-duplicated against the fingerprint while a watcher
662
+ * holds one, so a close whose disk state equals the last emitted state
663
+ * stays silent; with no watcher there is no fingerprint, and every revert
664
+ * is sent.
665
+ *
666
+ * A release, not the close itself: a document whose last client lost its
667
+ * connection is released only once the revert grace runs out, or when
668
+ * another client opens it meanwhile, and not at all when a client lost
669
+ * from it opens it again within its own grace.
512
670
  */
513
671
  protected subscribeToTextDocumentCloses(): void;
514
- /** Fan out a save event for the document's URI, gated by the subscription map. */
672
+ /**
673
+ * Fan out a deletion for each removed URI, to EVERY client on the connection
674
+ * rather than only to the ones watching that URI.
675
+ *
676
+ * **Deliberately ungated, where {@link dispatchPhaseEvent} and
677
+ * {@link dispatchSaveEvent} are gated.** Those two carry a built document and
678
+ * fire on every build, so the watcher gate is what keeps bandwidth
679
+ * proportional to what a client asked for. A deletion is neither: it is one
680
+ * URI, it is rare, and it reports the workspace's STRUCTURE rather than a
681
+ * document's content. Gating it forces any consumer that displays the
682
+ * workspace — a model tree, a file decorator — to learn about disappearances
683
+ * from a filesystem watcher instead, which a client hosted in a browser has
684
+ * no way to run: its workspace lives behind the head. A client that does not
685
+ * care filters on the URI, which costs it a comparison.
686
+ *
687
+ * The precedent is the last-close revert broadcast (see
688
+ * {@link subscribeToTextDocumentCloses}), where the same judgement was already made
689
+ * in the other direction: a transition that matters enough is delivered
690
+ * without a subscription.
691
+ *
692
+ * Runs from the `DocumentBuilder.onUpdate` listener rather than from a phase
693
+ * listener, which is the only place a deletion is observable: `update`
694
+ * removes the document before deriving the rebuild set, so it is never built.
695
+ * That ordering also puts this notification ahead of the `'rebuilt'` events
696
+ * for the dependents whose references the deletion just broke.
697
+ *
698
+ * The `deleted` list arrives already expanded to concrete document URIs —
699
+ * `deleteDocuments` resolves a directory URI to the documents beneath it — so
700
+ * no caller has to handle a directory here.
701
+ *
702
+ * The URI's fingerprint and revert mark are dropped: they describe a
703
+ * document that no longer exists. A kept fingerprint is adopted as the
704
+ * baseline and suppresses the first emit after the file returns with its
705
+ * previous content.
706
+ *
707
+ * The watchers SURVIVE: a recreated file resumes delivering to them with no
708
+ * re-subscription, and a client that answers the deletion by closing
709
+ * releases the watch through `closeModelDocument` anyway.
710
+ */
711
+ protected dispatchDeleteEvents(deleted: readonly URI[]): void;
712
+ /** Fan out a save event for the document's URI, gated on the URI's watchers. */
515
713
  protected dispatchSaveEvent(event: ClientTextDocumentChangeEvent<TextDocument>): void;
516
714
  /**
517
715
  * Fan out a phase event for the document's URI by calling
@@ -522,13 +720,25 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
522
720
  * out to multiple local subscribers with an `Emitter<T>` — the
523
721
  * framework deliberately does NOT promise multi-listener semantics.
524
722
  *
525
- * The dispatch is guarded by two filters:
526
- * 1. **Subscription map**: events for URIs no subscriber registered for
527
- * are NOT sent over the wire (bandwidth scales with subscribed URIs,
528
- * not phase events).
529
- * 2. **Emission fingerprint**: events for rebuilds that produce no
530
- * observable change since the last emit are suppressed. See
531
- * {@link lastEmittedFingerprint} for the rationale.
723
+ * An event for a URI no client watches is NOT sent over the wire, so
724
+ * bandwidth scales with watched URIs rather than with phase events; a
725
+ * pending revert mark is the exception (see
726
+ * {@link subscribeToTextDocumentCloses}).
727
+ *
728
+ * An event for a rebuild with no observable change since the last emit is
729
+ * suppressed against the URI's fingerprint. Such rebuilds are routine: a
730
+ * second client attaching to an open document makes
731
+ * `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely
732
+ * to re-trigger the build, and Langium rebuilds a document when a
733
+ * dependency changes even if its diagnostics come out the same. Sent at a
734
+ * version this head has not sent, they reach watchers as `'changed'`, and a
735
+ * watcher that reads `'changed'` as another client's write and resets its
736
+ * root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the
737
+ * fingerprint, so the first event after a watch is de-duplicated against
738
+ * the state the watcher just fetched; it goes with the last watcher, so the
739
+ * next first watch re-baselines rather than adopting a stale digest. A
740
+ * digest keeps its memory constant in document size; see
741
+ * {@link computeDocumentFingerprint} for the inputs.
532
742
  */
533
743
  protected dispatchPhaseEvent(document: LangiumDocument, cancelToken: CancellationToken): void;
534
744
  /**
@@ -553,21 +763,6 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
553
763
  * JSON-serialisable.
554
764
  */
555
765
  protected additionalFingerprintInputs(_document: LangiumDocument): readonly unknown[];
556
- /**
557
- * Discriminate the reason for a phase-event-driven update notification.
558
- * Uses the most recent `DocumentBuilder.onUpdate` snapshot:
559
- * - URI in the `deleted` list → `'deleted'`
560
- * - URI in the `changed` list → `'changed'` (the URI was passed to
561
- * `documentBuilder.update(changed, deleted)`, which spans `didChange`
562
- * text-document events and programmatic `update([uri], [])` calls).
563
- * - Otherwise → `'rebuilt'` (cascade re-derivation: this URI was rebuilt
564
- * because something it depends on changed; its own text wasn't flagged).
565
- *
566
- * `'saved'` is NOT emitted from this code path — saves take the dedicated
567
- * `DataClientProtocol.onDocumentSaved` channel; adopters that want a
568
- * unified update stream synthesise `'saved'` in their bridge layer.
569
- */
570
- protected resolveUpdateReason(uri: URI): TransferDocumentUpdatedEvent<TTransfer, TDiagnostic>['reason'];
571
766
  /**
572
767
  * Subscribe to the project tier's change channel and re-fan registry
573
768
  * diffs into per-project wire notifications. The internal
@@ -591,16 +786,6 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
591
786
  * snapshot needed for the `'removed'` wire payload.
592
787
  */
593
788
  protected dispatchProjectChangeEvent(event: ProjectChangeEvent<TProject>): void;
594
- /**
595
- * Resolve the wire-level `sourceClientId` for `document`'s events — the client
596
- * that authored its current version, from the version-author history on
597
- * `HydraniumTextDocuments`. The protocol-level counterpart of the internal
598
- * `AstDocumentManager.getAuthor`: a framework-internal rebuild has no author,
599
- * so this surfaces the {@link UNKNOWN_CLIENT_ID} presentation default. Adopters
600
- * that rebuild through non-text-document channels override to derive a
601
- * source id of their own.
602
- */
603
- protected resolveSourceClientId(document: LangiumDocument): string;
604
789
  dumpServerState(args: DumpServerStateArgs): Promise<string>;
605
790
  writeHeapSnapshot(args: WriteServerHeapSnapshotArgs): Promise<string>;
606
791
  dumpPodMemory(): Promise<string>;
@@ -610,5 +795,4 @@ export declare class DataServer<TTransfer extends TransferElement, TDiagnostic e
610
795
  /** Resolve a partial options object into a fully-defaulted form. */
611
796
  protected resolveOptions(partial: DataServerOptions): ResolvedDataServerOptions;
612
797
  }
613
- export {};
614
798
  //# sourceMappingURL=data-server.d.ts.map