/******************************************************************************** * Copyright (c) 2026 CrossBreeze, EclipseSource and others. * * This program and the accompanying materials are made available under the * terms of the MIT License which is available in the project root. * * SPDX-License-Identifier: MIT ********************************************************************************/ import { DisposableCollection, ReferenceSource, type CloseModelArgs, type HydraniumMessageData, type HydraniumResponseError, type CanonicalUri, type Disposable, type ElementSource, type FindNextNameArgs, type LatencyCollector, type LatencyReport, type OpenModelArgs, type Project, type ReferenceCandidate, type ReferenceContext, type ReferenceRequest, type ReferenceTarget, type ModelVersion, type TextState, type Tracer, type TransferDiagnostic, TransferDocument, type TransferCreatedDocument, type TransferSavedDocument, type TransferWatchedDocument, type TransferElement } from '@hydranium/protocol'; 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 TransferDeleteDocumentArgs, type TransferPersistDocumentArgs, type TransferSaveDocumentArgs, type WatchModelDocumentArgs, type TransferUpdateDocumentArgs, type TransferUpdateDocumentsArgs } from '@hydranium/protocol/data'; /** * Raised when a profiling command arrives with no capture running. * * A `ResponseError` rather than a plain `Error` so the identity survives to the * response boundary, which is where the message is rendered. An unwrapped throw * reaches the client as a generic internal error instead: no code for a caller * to switch on, and nothing for the boundary to render from. */ export declare const NO_ACTIVE_PROFILE: import("@hydranium/protocol").MessageDefinition<"No profiling capture is active; call startProfiling first.">; /** * The JSON-RPC code, unrelated to the catalogue code above: this one is numeric, * survives reconstruction and is what a caller switches on. */ export declare const NO_ACTIVE_PROFILE_CODE: 42002; export declare const noActiveProfileError: () => HydraniumResponseError; /** * Raised when a reference question's wait for the build exceeds * {@link DataServerOptions.referenceSettleTimeoutMs}. * * A `ResponseError` because a class name does not cross RPC: without the code a * wire client cannot tell a wedged build from a reference that resolves to * nothing, which is the distinction the wait exists to keep. */ export declare const REFERENCE_SETTLE_TIMEOUT: import("@hydranium/protocol").MessageDefinition<"The model is still being processed; try again in a moment.">; /** See {@link NO_ACTIVE_PROFILE_CODE} for why this is separate from the catalogue code. */ export declare const REFERENCE_SETTLE_TIMEOUT_CODE: 42003; /** The wait's length rides in `data` as `elapsedMs`, for the code that reacts rather than the reader. */ export declare const referenceSettleTimeoutError: (elapsedMs: number) => ResponseError; import type { DataServerDiagnosticsProvider, DataServerProfileCapture } from './diagnostics-provider.js'; import type { ClientSession, ClientSessionWriteArgs, HydraniumLanguageServices, LogNameOptions, AstDiagnostic, AstDocument, AstDocumentSavedEvent, EncodedTransferDocument, ModelDeletedEvent, ModelDirtyChangedEvent, ModelService, ModelUpdatedEvent, ProjectChangeEvent, ServerSharedServices, SessionEndCause, TransferEncoder } from '@hydranium/core'; import { type AstNode, DocumentState, type URI } from '@hydranium/langium'; import { type MessageConnection, ResponseError } from 'vscode-jsonrpc'; /** * Which observable state {@link DataServer.computeDocumentFingerprint} hashes to * de-dup `onDocumentUpdated` emissions. * * - `'transfer-document'` (default) — the client-visible transfer root * (`TransferEncoder.toTransferDocument`) plus diagnostics. This is exactly the * payload `envelope` sends, so it changes whenever — and only when — the * client-visible model changes, INCLUDING cross-document derived state * folded in on a cascade rebuild that leaves the document's own text * untouched. Safe for any adopter whose AST extensions fold derived state * into the transfer projection (the framework norm). * - `'text-diagnostics'` — the cheaper parsed-text + diagnostics hash. An * opt-DOWN for adopters that fold no derived state and want to avoid * stringifying the transfer root per phase event. */ export type FingerprintStrategy = 'transfer-document' | 'text-diagnostics'; /** * Construction-time options for {@link DataServer}. Every field is * optional; values not supplied fall back to {@link DataServer.DEFAULT_OPTIONS}. */ export interface DataServerOptions extends LogNameOptions { /** * Document phase at which the data-server fires subscription events * (`DataClientProtocol.onDocumentUpdated`). * * **Subscription dispatch only** — distinct from the synchronous RPC * response phase. A read (`getModelDocument`) settles at the * integrity-settled landmark (`IntegrityService.SettledState`), or at * `Validated` when {@link GetModelDocumentArgs.includeDiagnostics} is set. * A write (`updateModelDocument` / `updateModelDocuments` / * `saveModelDocument`) answers once its document is validated, as a * session's write does, and then waits for * `ModelService.settleLanguageClient`. This option controls only the async * notification phase. * * Default: `DocumentState.Validated` — validation is the last builder * phase and produces the full diagnostic set, so subscription events fired * at validation surface the complete diagnostic picture. * * **Trade-off.** Validation can take seconds on a real workspace. Adopters * that publish validation diagnostics through a separate channel — * typically LSP `publishDiagnostics` — can fire subscription events earlier * (e.g. `IndexedReferences`) since clients observe validation diagnostics * asynchronously via that channel regardless of when the subscription * event lands. */ readonly subscriptionPhase?: DocumentState; /** * Runtime-specific implementation of the four diagnostics methods that need * a process to inspect — heap snapshot, profile capture, pod memory, server * state. * * **Defaulted per platform, so most hosts pass nothing.** On Node the default * is the real implementation; in a browser bundle `package.json`'s `browser` * field selects a twin whose methods reject, because there is no process to * inspect. Supply this only to override — a custom implementation, or to say * explicitly at the call site which one you mean. * * It is injected rather than reached for because a static * `@hydranium/core/node` import on this package's portable entry pulls * `node:fs`, `node:v8` and `node:perf_hooks` into any browser build, over * methods a browser cannot call anyway — which is what previously made the * head unbundleable. */ readonly diagnostics?: DataServerDiagnosticsProvider; /** * Which observable state the `onDocumentUpdated` de-dup fingerprint hashes. * Defaults to `'transfer-document'` (the client-visible payload, derived * state included). See {@link FingerprintStrategy}. */ readonly fingerprintStrategy?: FingerprintStrategy; /** * How long a reference question waits for the build to reach `Linked` before * failing with {@link REFERENCE_SETTLE_TIMEOUT_CODE}. Bounded because the * wait resolves off a build-phase notification, so a build cancelled below * `Linked` with nothing after it leaves the request unanswered for the life * of the server. * * Expiry rejects rather than reading the index anyway: the unsettled index * is what the wait keeps the caller away from, so falling through to it on a * slow build reinstates the fault — and on a name proposal persists it. * * Default {@link DataServer.DEFAULT_OPTIONS}, sized for a cold workspace * still reaching `Linked` for the first time. */ readonly referenceSettleTimeoutMs?: number; /** * Wire-method namespace for both inbound request handlers and the * outbound notification client proxy. Defaults to * {@link DATA_SERVER_WIRE_PREFIX} (`'data-server/'`). * * Adopters that combine the data-server head with their own protocol * head on one connection pass their own namespace, so the full wire * surface is partitioned under one prefix instead of two, the way LSP * itself partitions `textDocument/*` and `workspace/*`. The client side * (the `methodNamespace` option of its client `createRpcProxy`) MUST * agree. */ readonly methodNamespace?: string; /** * Additional protocol-method names to register as request handlers on * the same connection alongside the framework's * {@link DATA_SERVER_PROTOCOL_METHODS}. Used by `DataServer` subclasses * that implement an adopter-specific protocol — the subclass implements * the adopter methods on `this`, the names go here, and the * constructor's single `createRpcProxy` call (binding `this` as its * `localTarget`) registers framework + adopter handlers under one * namespace. * * Throws at construction time if any name overlaps with a built-in * framework method (would cause vscode-jsonrpc duplicate-handler * errors at registration). Notification-shaped (`on*`-prefixed) names * register as notification handlers; everything else as request * handlers — same `on*`-prefix heuristic the framework's * `bindRpcMethods` uses for `DataClientProtocol`. */ readonly additionalMethods?: readonly string[]; /** * Framework method names to NOT register on the wire. Used by adopters * that expose renamed domain-vocabulary equivalents of framework * methods and want to keep the wire surface free of the unused * framework names. * * Each name is filtered out of the combined `[framework + additional]` * set before the handlers are bound. The adopter typically pairs an * `excludedMethods` entry with an `additionalMethods` entry naming the * renamed equivalent on the same class — the subclass's renamed method * usually delegates to the inherited framework implementation via * `super.X()` so the behaviour stays identical. * * Names that are neither in `DATA_SERVER_PROTOCOL_METHODS` nor in * `additionalMethods` are simply no-ops — listing an unknown name does * not throw. The overlap-detection between `additionalMethods` and * built-in framework methods still fires for non-excluded names. */ readonly excludedMethods?: readonly string[]; /** * When supplied, every inbound data-server RPC is timed into this collector * (via the `createRpcProxy` binding) and exposed through * {@link DataServerDiagnosticsProtocol.getLatency}. A head that also runs an * LSP connection can pass the SAME collector through `lspLatencyOptions` to * that connection, so one report covers both heads. Absent by default (no * timing overhead). */ readonly latency?: LatencyCollector; } /** * Fully-resolved variant of {@link DataServerOptions} — every field set, after * merging defaults. Returned by the `protected` * {@link DataServer.resolveOptions} and held on {@link DataServer.options}, so * an adopter changing how defaults resolve has to name it. */ export interface ResolvedDataServerOptions { readonly subscriptionPhase: DocumentState; readonly fingerprintStrategy: FingerprintStrategy; readonly methodNamespace: string; readonly additionalMethods: readonly string[]; readonly excludedMethods: readonly string[]; /** Always resolved — to the caller's, or to the platform default. */ readonly diagnostics: DataServerDiagnosticsProvider; readonly referenceSettleTimeoutMs: number; } /** * What a {@link DataServer} keeps per canonical URI, in the `protected` * {@link DataServer.uriWatchRecords}. A record lives while it has a watcher * or a release mark; {@link DataServer.pruneUriWatchRecord} enforces that on * every path that removes either, so a record with no watcher has a release * broadcast pending. Test the size of {@link DataServerUriWatchRecord.watchers}, not the * record's presence, for "watched". */ export interface DataServerUriWatchRecord { /** The client ids watching the URI; save, dirty and phase events go out only while it is non-empty, a pending release mark aside. */ readonly watchers: Set; /** 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. */ fingerprint?: string; /** * The version {@link DataServerUriWatchRecord.fingerprint} was taken at; an * event goes out when either moves. Not {@link DataServerUriWatchRecord.sentVersion}: * a first watch sets this and sends nothing, so the next event at its * version still carries the manager's attribution. */ fingerprintVersion?: ModelVersion; /** Set by {@link DataServer.subscribeToModelReleases} once a release happened: its broadcast, the next phase event, goes out even without a watcher. */ releaseBroadcastPending?: boolean; /** * The version of an open document the last event sent was built at. The * version sent again goes out as `'rebuilt'` from no client: the manager * counts a version delivered only once its `Validated` listeners ran, so a * build cancelled after the subscription phase would send it as a change * twice. Only while the store has the document open: without it, a * document can keep one version through changes of its file, so its events * keep the manager's attribution. */ sentVersion?: number; } /** * Typed-RPC protocol head for the hydranium framework. The data-server * is a PEER of `@hydranium/core/lsp` and `@hydranium/glsp-server` — * all three heads coordinate through shared services in * `@hydranium/core` (multi-client text documents, self-save * registry, document-builder phases, project manager, ModelService * facade) and never depend on each other at the package level. * * **No abstract grammar hooks**. The data-server has no grammar-specific * abstract methods: `serialize` / `parseModel` live on * {@link ModelService} (the in-process facade), where the `update` / * `save` lifecycle owns the transfer-model round-trip. Adopters that want * to customise serialisation rebind `services.model.ModelService` with a * subclass; adopters that need a typed-overlay encoder rebind * `services.model.TransferEncoder` with a subclass exposing the typed * `TTransferMap`. * * **What still subclasses**. The data-server is concrete by default; * adopters subclass ONLY when they need to decorate wire returns or * notifications. The usual adoption path is DI rebinds alone. * * **`TTransfer` is not checked.** It declares the union of the transfer roots * the workspace's languages produce. Which root a document has is known only * at runtime, from its language, so a `TTransfer` missing a language compiles. * * Lifecycle: the constructor registers framework request handlers (plus * any names supplied via {@link DataServerOptions.additionalMethods}) and * builds the {@link DataClientProtocol} notification proxy on the same * connection in one {@link createRpcProxy} call (binding `this` as its * `localTarget`) under the configured namespace, and follows documents * through `ModelService`'s events: at the configured phase, `onModelUpdated` * dispatches per-document `clientProxy.onDocumentUpdated` for watched URIs and * `onModelsBuilt` a single `clientProxy.onDocumentsBuilt` naming the batch's * unwatched documents. * * The data-server requires the full {@link ServerSharedServices} * shape — `HydraniumTextDocuments` for client-attributed updates, * `WritableFileSystemProvider` for save, `SelfSaveRegistry` for * save-echo suppression, `ProjectManager` for project listing, * `ModelService` for the lifecycle delegate, `TransferEncoder` for * wire envelope construction — all of which the framework's * `createServerSharedModule` binds by default. * * **No per-head shared module.** The data-server head does not surface a * `createDataServerSharedModule` factory because it contributes no * shared-tier bindings: it reads exclusively from * {@link ServerSharedServices}. An empty factory would only mislead * adopters into composing it as though it were the canonical adoption * path. */ export declare class DataServer implements DataServerProtocol, DataServerDiagnosticsProtocol, Disposable { protected readonly connection: MessageConnection; protected readonly services: ServerSharedServices; /** * Framework defaults, exposed so an adopter can spread them when * extending rather than restate a value the framework may change. */ static readonly DEFAULT_OPTIONS: Required>; protected readonly options: ResolvedDataServerOptions; /** This connection's {@link DataServerUriWatchRecord} per canonical URI; see there for when a record lives. */ protected readonly uriWatchRecords: Map; /** * Per client id, the key each URI it watched resolved to when it watched. * An unwatch looks the key up here: once a file is gone, a symlink to it * no longer resolves to the key the watch is under. */ protected readonly watchKeys: Map>; /** * The position of the last update or deletion event sent, which each * such event carries, and a watch's answer carries as of the moment it * took whether its document exists: an event past it was sent after. */ protected eventSequence: number; /** * The live client sessions this connection registered, by client id. A * document request carrying one of these ids acts as that session; one * carrying any other id fails. A session leaves once it ends, so a * connection that registers many over its life does not accumulate them. */ protected readonly clientSessions: Map>; /** * Typed client proxy — sends `data-server/on*` notifications back over the same wire. * The proxy sends any `on[A-Z]*` name other than `onDidOpenConnection` and * `onDidCloseConnection`, for which it returns its own events, so a subclass * with notifications of its own narrows only the type: * `declare protected readonly clientProxy: TheirClient`. */ protected readonly clientProxy: DataClientProtocol; protected readonly disposables: DisposableCollection; protected readonly tracer: Tracer; /** The in-flight interactive profile capture, held between {@link startProfiling} and {@link stopProfiling}. */ protected activeProfile?: DataServerProfileCapture; /** Set once {@link dispose} has run, so a capture that starts after teardown is stopped instead of leaked. */ protected disposed: boolean; /** Per-method RPC latency collector, when the head opted in via {@link DataServerOptions.latency}. */ protected readonly latency?: LatencyCollector; /** Encoder pulled from DI. Adopters rebind `services.model.TransferEncoder` to a typed-overlay subclass. */ protected readonly encoder: TransferEncoder; /** * In-process workspace facade — the lifecycle delegate `get` / `update` / `save` go through. * Its documents carry the AST-layer {@link AstDiagnostic}, never the wire `TDiagnostic`: * {@link encoder} converts one into the other on the way out. */ protected readonly modelService: ModelService; constructor(connection: MessageConnection, services: ServerSharedServices, options?: DataServerOptions); /** * Release everything the constructor wired up — the bound protocol * handlers and every listener — and clear {@link uriWatchRecords}, so a * long-lived shared services bundle does not retain per-connection memory * after the connection closes. Also ends every session this connection registered, which closes * every document it has open: the SHARED store's state rather than this * server's, which outlives the connection unless released here. * * Idempotent: subsequent calls are no-ops. Runs by itself when the * connection closes, so adopters who don't hold a reference still get * per-connection cleanup; adopters that DO hold a reference may call * `dispose()` directly for early teardown. The sessions end with `cause`: * `'closed'` releases every document whose last open they close at once, * and `'lost'`, the connection's own close, lets each wait out the release * grace. */ dispose(cause?: SessionEndCause): void; createSession(args: CreateSessionArgs): Promise; /** End a session this connection registered. */ closeSession(args: CloseSessionArgs): Promise; /** End `session`, registered here under `clientId`, with `cause`, and drop its watches on this connection. */ protected endSession(clientId: string, session: ClientSession, cause?: SessionEndCause): void; protected dropWatches(clientId: string): void; createModelDocument(args: CreateModelDocumentArgs): Promise>; updateModelDocuments(args: TransferUpdateDocumentsArgs): Promise[]>; /** * The session write a wire write request carries. Only the fields a session * takes: a field an adopter adds to a request reaches the session only * through an override of this. */ protected toSessionWrite(request: Omit, 'clientId'>): ClientSessionWriteArgs; /** * The session this connection registered under `clientId`, which every * document request acts as. An id that is not one fails with the * closed-session code: opening or writing under it would leave an open that * no session end ever closes. */ protected requireSession(clientId: string): ClientSession; openModelDocument(args: Pick): Promise>; /** * The snapshot a session's open or create answers with. When the read * fails, `rollback` undoes the open this call made before the failure is * rethrown: the caller sees no open, so nothing on its side would ever close * it. */ protected openedSnapshot(uri: string, rollback?: () => Promise): Promise>; closeModelDocument(args: CloseModelArgs): Promise; getModelDocument(args: GetModelDocumentArgs): Promise>; updateModelDocument(args: TransferUpdateDocumentArgs): Promise>; saveModelDocument(args: TransferSaveDocumentArgs): Promise>; persistModelDocument(args: TransferPersistDocumentArgs): Promise>; /** * Delete the document through the session, then release the session's * watch of it, as {@link closeModelDocument} does. Released only after the * delete: one that fails leaves the session its open and its watch. Other * sessions' watches survive, as for any deletion. */ deleteModelDocument(args: TransferDeleteDocumentArgs): Promise; /** * Record a watch for `(uri, clientId)` in {@link uriWatchRecords}. * Subsequent phase events on `uri` fan out to the wired * `clientProxy.onDocumentUpdated`. The bidirectional pattern means the * event channel is the client notification surface, not a returned * handle. * * Also baselines the URI's emission fingerprint (see * {@link dispatchPhaseEvent}) to the document's current state when the * first watcher for the URI registers. This guarantees that any phase event firing immediately after * the watch with no observable change is suppressed — watchers obtain * initial state via `getModelDocument` (or {@link openModelDocument}) and * do not need a redundant phase notification for that same state. * * Answers once the document is loaded as a read loads it, with the key * events name it by and whether a document exists, taken after the watch * is in place and the load, so an event sent while it loads is older. */ watchModelDocument(args: WatchModelDocumentArgs): Promise; /** * Remove a watch for `(uri, clientId)` previously created by * {@link watchModelDocument}. Idempotent — unwatching twice is a no-op. * Dispatch for `uri` stops once no watchers remain, and the emission * fingerprint goes with the last watcher (see {@link pruneUriWatchRecord}). * * A URI the client watched is unwatched under the key it resolved to then, * from {@link watchKeys}, which still holds once its file is gone. */ unwatchModelDocument(args: WatchModelDocumentArgs): Promise; /** * Drop what `uri` no longer needs: the * {@link DataServerUriWatchRecord.fingerprint} once no client watches it, * and the whole record once it holds no * {@link DataServerUriWatchRecord.releaseBroadcastPending} mark either. * Every path that removes a watcher or consumes a mark ends here. */ protected pruneUriWatchRecord(uri: string): void; /** * Canonicalise a URI string for use as a {@link uriWatchRecords} key, via the * shared `DocumentUriPolicy`. Callers may send non-canonical URIs * (drive-letter casing, percent-encoding differences, or a symlink path) * over the wire; the dispatch side keys by * `document.uri.toString()` from `LangiumDocuments`, so writer keys must * canonicalise to the same form or events silently fail to deliver. * Routing through the seam (rather than a bare `UriUtils.normalize`) * means that when an adopter strengthens document identity — e.g. * real-path (symlink) resolution — the data-server head's keys track * it too, instead of carrying the same path-identity divergence the * LSP head resolves. * * Adopters can still override for head-specific URI policy by subclassing. * The result keys watches only; a document is looked up by its own URI. */ protected canonicalKey(uri: string): string; getProjects(): Promise; getProjectForUri(args: GetProjectForUriArgs): Promise; /** * Resolve once the data-server is ready to serve requests. Delegates * to {@link ModelService.ready} so adopters that warm-load services * (workspace indexing, etc.) override the `ModelService` slot in * their shared module rather than this method on a DataServer * subclass. */ waitForReady(): Promise; /** * Settle the build before a reference question is answered from the index. * * A query issued right after a model update otherwise races the rebuild and * reads an index missing the symbols it asks about. The cost is not confined * to this call: a scope built inside that window is cached, and the build's * remaining documents link against it. * * Waits the source document specifically, but ONLY when one is loaded at * that URI: a synthetic source can address a URI with no document (a * directory URI, typically), where a per-URI `waitUntil` throws "No document * found". Falls back to a global settle, matching the id-based * `ElementSource` path. * * Bounded by {@link DataServerOptions.referenceSettleTimeoutMs}. */ protected awaitReferencesLinked(source: ReferenceSource): Promise; findReferenceCandidates(ctx: ReferenceContext): Promise; resolveReference(ref: ReferenceRequest): Promise | undefined>; findNextName(args: FindNextNameArgs): Promise; /** * Resolve the per-language `references` services for a reference source. * Delegates the language choice to {@link resolveReferenceLanguage} and * throws when no language owns the source — the reference heads have no * meaningful empty answer (an empty candidate list reads to the client as * "nothing matches" and hides the misrouting). */ protected resolveReferenceServices(source: ReferenceSource): HydraniumLanguageServices['references']; /** * Pick the language that owns a reference source: the registry's * `getLanguageFor` over the source's declared language, URI and AST type, * with an {@link isElementSource} routed by the document that holds the * element (see {@link findElementDocumentUri}) before its type, and * {@link fallbackReferenceLanguage}, adopter policy, last. * * An unregistered declared language falls through rather than failing: the * id crosses the wire, so a client built against a head with one more * grammar would otherwise lose queries the other signals answer. */ protected resolveReferenceLanguage(source: ReferenceSource): HydraniumLanguageServices | undefined; /** * Locate the document that holds the element an {@link ElementSource} * addresses, via the index's O(1) name lookup — `name` is the qualified * name the `NameProvider` wrote into the index, and the optional `type` * disambiguates names that repeat across types (honouring grammar * subtyping through `AstReflection.isSubtype`). * * Only reached in a multi-language workspace, once the declared language * and the URI have abstained. * * Abstains when the name matches elements in more than one DOCUMENT — the * index spans every language and is filled in build order, so "the * first match" would be file-watch order rather than an answer. Routing * then falls through to the element's type, which abstains on ties in the * same way, and finally to adopter policy. */ protected findElementDocumentUri(source: ElementSource): URI | undefined; /** * Language to serve reference queries whose source names no language of * its own — a synthetic source addressing a URI with no (or an * unregistered) extension, or an element id absent from the index. * * Returns `undefined` by default, which makes * {@link resolveReferenceServices} throw. Only reachable in a * multi-language workspace, where choosing among the registered languages * is adopter policy: override and return the language such sources belong * to. */ protected fallbackReferenceLanguage(_source: ReferenceSource): HydraniumLanguageServices | undefined; /** * Whether `error`, from waiting on `uri`'s document, means that `uri` has * no document: a URI with neither a file nor text builds nothing, and * Langium's wait after the build rejects for want of one, with a * `ServerCancelled` response error. Any other failure, such as a read * that fails before a document is registered, a cancelled wait or a * `ReentrantWriteLockError`, is the caller's to see. */ protected isMissingDocument(error: unknown, uri: string): boolean; /** * Build a {@link TransferDocument} envelope from the current document state, * delegating root + diagnostic encoding to {@link encoder} (see * `TransferEncoder.toTransferDocument` for the walk). `fingerprint` is the * caller's {@link computeDocumentFingerprint} of that same state, which * spares hashing it twice. */ protected envelope(uri: URI, fingerprint?: string): TransferDocument; /** * The transfer document a request answers with for `astDocument`, its model * hashed and the text stamped on it by {@link withServerState}. Every * document a request answers with goes through here, so none goes out * without them. */ protected encodeDocument(astDocument: AstDocument): TransferDocument; /** * The project a client receives for `project`, unchanged by default. Every * project a request answers with or a change notification carries goes * through here, so a field derived for clients cannot miss one path. The * result crosses as JSON, so a value a client reads goes in a data field, * not a getter. */ protected encodeProject(project: TProject): TProject; /** * `encoded` with `hash` on its model and the text the server holds for it: * the store's while it holds the document, the build's otherwise. The text * is read when the document is sent rather than kept with the build: a save * changes `text.dirty` without a rebuild, and the store's text moves on before * the build that follows it. */ protected withServerState(encoded: EncodedTransferDocument, hash: string): TransferDocument; /** * The text the server holds for `uri`, as every envelope and a watch's * answer carry it: the store's while it holds the document, the build's * otherwise, and none for a document it has neither of. */ protected serverTextState(uri: string): TextState | undefined; /** * The text a build read for a document the store never held, which is * clean: the store holds every text a client gave it. */ protected builtTextState(uri: string): TextState | undefined; /** * Follow every document at the configured * {@link DataServerOptions.subscriptionPhase}, once per connection rather * than once per watch, so the cost stays flat in the number of watches. */ protected subscribeToModelUpdates(): void; /** * Report the documents that reached {@link DataServerOptions.subscriptionPhase} * and that NOBODY on this * connection is watching — the ones a client was not told about through * {@link dispatchPhaseEvent}, which is gated per URI. * * **The gap this closes is the one no other source can observe.** A document * the client watches, it hears about already. A file changed on disk, the * host's own filesystem watcher reports — and on a browser host, where the * workspace lives behind this head, an external change cannot happen at all. * What is left, and what nothing outside the server can see, is a document * rebuilt because something it DEPENDS ON changed: its file never changed, so * a filesystem watcher is silent by construction, and it has no subscriber, so * the update channel is silent by design. A consumer displaying data derived * from that document — a tree label, a decorator — otherwise goes stale with * no signal from any source, and repairs itself the moment someone opens the * file to investigate, which is what makes it expensive to diagnose later. * * Payload-free on purpose: URIs only, so a client re-reads what it displays * rather than being handed transfer documents it did not ask for. That is the * property the watcher gate protects, and it is preserved here by * carrying no document rather than by gating the message. * * Quiet in the common case. Editing a document that an editor has open leaves * that URI watched and therefore out of this set, so a build with no * dependents produces nothing at all, and workspace initialisation produces * nothing because it does not build to this phase. The ceiling is a * whole-workspace rebuild at the subscription phase: one message, URIs only. */ protected dispatchBuiltEvent(built: readonly CanonicalUri[]): void; /** * Follow every save so a single `onDocumentSaved` wire notification fires * for ANY save of a subscribed URI — regardless of whether the save * originated from the data-server's RPC `saveModelDocument`, the LSP head's * text-editor save, or any other client. * * Architectural symmetry with {@link subscribeToModelUpdates}: every * subscribed client sees every state change to documents they care about, * regardless of which client triggered it. Firing `onDocumentSaved` only * from the data-server's own RPC path is a bug, not an optimisation: an * LSP-driven save then lands on disk without notifying the subscribed * clients, which never clear their dirty state. */ protected subscribeToTextDocumentSaves(): void; /** Relay each change of a document's dirty state; see {@link dispatchDirtyEvent}. */ protected subscribeToDirtyChanges(): void; /** * Send a dirty flip to the connection, gated on the URI's watchers as * {@link dispatchSaveEvent} is: the answer at any one moment travels on * every document sent, so a client that watches nothing reads it there. */ protected dispatchDirtyEvent(event: ModelDirtyChangedEvent): void; /** * Mark each document the store releases, so {@link dispatchPhaseEvent} * broadcasts the build that follows even without a watcher. By default * that build reverts the document to its disk content, discarding unsaved * in-session edits, and the last close typically also * removed the last watcher: without the broadcast, a consumer that only * ever fetches via `getModelDocument` keeps showing the discarded state. * The broadcast is de-duplicated against the fingerprint while a watcher * holds one, so a close whose disk state equals the last emitted state * stays silent; with no watcher there is no fingerprint, and every release * build is sent. The first build after the release consumes the mark, and * goes out as the release unless it is stamped past the version a client * opened the document at again: a client's write or an integrity repair * that rides it keeps its author. * * A release, not the close itself: a document whose last client lost its * connection is released only once the release grace runs out, or when * another client opens it meanwhile, and not at all when a client lost * from it opens it again within its own grace. */ protected subscribeToModelReleases(): void; /** * Fan out a deletion for each removed URI, to EVERY client on the connection * rather than only to the ones watching that URI. * * **Deliberately ungated, where {@link dispatchPhaseEvent} and * {@link dispatchSaveEvent} are gated.** Those two carry a built document and * fire on every build, so the watcher gate is what keeps bandwidth * proportional to what a client asked for. A deletion is neither: it is one * URI, it is rare, and it reports the workspace's STRUCTURE rather than a * document's content. Gating it forces any consumer that displays the * workspace — a model tree, a file decorator — to learn about disappearances * from a filesystem watcher instead, which a client hosted in a browser has * no way to run: its workspace lives behind the head. A client that does not * care filters on the URI, which costs it a comparison. * * The precedent is the release broadcast (see * {@link subscribeToModelReleases}), where the same judgement was already made * in the other direction: a transition that matters enough is delivered * without a subscription. * * A deletion is announced before the build that follows it, so this goes * out ahead of the `'rebuilt'` events for the dependents whose references * the deletion just broke. * * The URI's fingerprint and release mark are dropped: they describe a * document that no longer exists. A kept fingerprint is adopted as the * baseline and suppresses the first emit after the file returns with its * previous content. * * The watchers SURVIVE: a recreated file resumes delivering to them with no * re-subscription, and a client that answers the deletion by closing * releases the watch through `closeModelDocument` anyway. A session that * deleted the document has its own released by {@link deleteModelDocument}. */ protected dispatchDeleteEvent(event: ModelDeletedEvent): void; /** Fan out a save event for the document's URI, gated on the URI's watchers. */ protected dispatchSaveEvent(event: AstDocumentSavedEvent): void; /** * Fan out a phase event for the document's URI by calling * `clientProxy.onDocumentUpdated`. The proxy lowers the call to a * `data-server/onDocumentUpdated` wire notification; the paired client * (bound via the client `createRpcProxy`'s `localTarget`/`localMethods`) * routes it to its handler. Adopters fan a single inbound onDocumentUpdated * out to multiple local subscribers with an `Emitter` — the * framework deliberately does NOT promise multi-listener semantics. * * An event for a URI no client watches is NOT sent over the wire, so * bandwidth scales with watched URIs rather than with phase events; a * pending release mark is the exception (see * {@link subscribeToModelReleases}). * * An event for a rebuild with no observable change since the last emit is * suppressed against the URI's fingerprint and the version it was taken at; * a new version with the same fingerprint goes out with the same * `model.hash`, so a watcher still learns the version. Such rebuilds are routine: a * second client attaching to an open document makes * `HydraniumTextDocuments.refreshContent` fire `onDidChangeContent` purely * to re-trigger the build, and Langium rebuilds a document when a * dependency changes even if its diagnostics come out the same. Sent at a * version this head has not sent, they reach watchers as `'changed'`, and a * watcher that reads `'changed'` as another client's write and resets its * root to the server view loses the user's edits. The first {@link watchModelDocument} baselines the * fingerprint, so the first event after a watch is de-duplicated against * the state the watcher just fetched; it goes with the last watcher, so the * next first watch re-baselines rather than adopting a stale digest. A * digest keeps its memory constant in document size; see * {@link computeDocumentFingerprint} for the inputs. */ protected dispatchPhaseEvent(event: ModelUpdatedEvent): void; /** * Fingerprint of the snapshot `root` and its encoding `encoded`, used to * de-dup `onDocumentUpdated` emissions and sent as every document's * `model.hash`, so it must not depend on the version or on live state. The * {@link FingerprintStrategy} option selects what is hashed (default * `'transfer-document'` — see the type). * * {@link TransferEncoder.toTransferDocument} is cached per build, so within * one phase event the fingerprint and the subsequently-emitted `envelope` * share a single encode walk. * * Wrapped in {@link Tracer.time} against {@link FINGERPRINT_LOG_AFTER_MS}. */ protected computeDocumentFingerprint(root: AstNode, encoded: EncodedTransferDocument): string; /** * Subscribe to the project tier's change channel and re-fan registry * diffs into per-project wire notifications. The internal * `ProjectChangeEvent` carries arrays of added/updated ids plus a * removed list of `{ id, snapshot }` pairs; each affected project * emits one wire `onProjectsChanged` event so clients react * one-at-a-time without walking arrays. `'removed'` dispatches carry * the pre-removal snapshot bundled in * {@link ProjectChangeEvent.removed} because the registry entry is * already gone by the time the event fires. * * Adopters that warm-load services may want to defer this subscription * until {@link waitForReady} resolves (to avoid replaying the initial * discovery as a burst of `'added'` events). Override * {@link subscribeToProjectManager} on the subclass to gate. */ protected subscribeToProjectManager(): void; /** * Fan one internal {@link ProjectChangeEvent} out to per-project wire * notifications. Each `removed` entry pairs the id with the pre-removal * snapshot needed for the `'removed'` wire payload. A project whose * {@link encodeProject} throws is logged and skipped, so the rest of the * batch still reaches the client. */ protected dispatchProjectChangeEvent(event: ProjectChangeEvent): void; dumpServerState(args: DumpServerStateArgs): Promise; writeHeapSnapshot(args: WriteServerHeapSnapshotArgs): Promise; dumpPodMemory(): Promise; startProfiling(args: StartProfilingArgs): Promise; stopProfiling(args: StopProfilingArgs): Promise; getLatency(): Promise; /** Resolve a partial options object into a fully-defaulted form. */ protected resolveOptions(partial: DataServerOptions): ResolvedDataServerOptions; } //# sourceMappingURL=data-server.d.ts.map