@prisma-next/language-server 0.14.0-dev.17

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [Prisma Data, Inc]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,50 @@
1
+ # @prisma-next/language-server
2
+
3
+ > **Internal package.** This package is an implementation detail of [`prisma-next`](https://www.npmjs.com/package/prisma-next)
4
+ > and is published only to support its runtime. Its API is unstable and may change
5
+ > without notice. Do not depend on this package directly; install `prisma-next` instead.
6
+
7
+ The Prisma Next language server. It speaks the Language Server Protocol over stdio and supports PSL parse diagnostics plus whole-document PSL formatting for the schema inputs declared in a project's `prisma-next.config.ts`. It is launched by the `prisma-next lsp` subcommand, so the editor features come from the project's own `@prisma-next` version (version-matched by construction).
8
+
9
+ ## Scope
10
+
11
+ Supported capabilities are intentionally narrow: parse diagnostics and whole-document formatting for configured PSL inputs. Formatting is only available for documents listed in `contract.source.inputs`, uses `@prisma-next/psl-parser/format`, and applies formatter options from the project's Prisma config `formatter` block. Hover, completion, navigation, range formatting, on-type formatting, and editor-extension work are out of scope. A server process can manage multiple projects under the workspace root, keyed by the config file each open document belongs to.
12
+
13
+ ## How it works
14
+
15
+ 1. **`initialize`** — resolves the workspace root from the client's `rootUri` and registers config-file watching when the client supports it. Configs are loaded when matching documents open or when watched config files change. If a config cannot be loaded, the server does not manage that project.
16
+ 2. **Document sync** — text-document sync is **incremental**
17
+ (`TextDocumentSyncKind.Incremental`); the `TextDocuments` manager applies
18
+ incremental edits, and the server re-parses the full current buffer on each
19
+ change.
20
+ 3. **Diagnostics** — on `didOpen` / `didChange` of a document whose URI is a configured PSL input, the server runs `@prisma-next/psl-parser`'s `parse()` (the CST path) and `buildSymbolTable()`, then publishes the merged, mapped diagnostics via `textDocument/publishDiagnostics`. A clean document publishes an empty array (clearing markers). Documents that are not configured inputs publish nothing.
21
+ 4. **Formatting** — on `textDocument/formatting`, the server formats the current in-memory document text with `@prisma-next/psl-parser/format` when the document is a configured PSL input. It returns one whole-document edit when the formatted text differs, and returns no edits for missing or closed documents, unconfigured documents, already canonical text, malformed PSL, or invalid formatter options.
22
+ 5. **Preserved artifacts** — each project keeps the parse artifacts it produces:
23
+ the AST per open document (keyed by URI) and one symbol table per project,
24
+ rebuilt from the open configured input on each edit and dropped when the
25
+ document closes. They are exposed through `getDocumentAst` /
26
+ `getProjectSymbolTable` so future features (completion, semantic tokens) read
27
+ real stages instead of re-parsing. Filling the project table from several
28
+ inputs — and reading unopened inputs from disk — is deferred cross-file work.
29
+
30
+ ## Module layout
31
+
32
+ - `diagnostic-mapping.ts` — pure `ParseDiagnostic[] → LspDiagnostic[]` mapping.
33
+ Free of any `vscode-languageserver` import; it returns plain shape objects
34
+ (ranges pass through unchanged) so it stays reusable. The connection layer
35
+ adapts the numeric severity to the LSP enum.
36
+ - `schema-inputs.ts` — resolves the schema-input set (`SchemaInputSet`) from a
37
+ config and answers URI membership.
38
+ - `config-resolution.ts` — wraps `loadConfig` and resolves schema inputs, formatter options, and control-stack inputs for a config. A standalone async function so it can be re-run on a config change without rewiring the server.
39
+ - `document-diagnostics.ts` — `computeDocumentDiagnostics(uri, text, inputs, controlStack)`, the pure seam that parses, builds the symbol table, and returns the diagnostics plus the parse artifacts.
40
+ - `project-artifacts.ts` — `createProjectArtifacts()`, the per-project store that
41
+ preserves the per-URI ASTs and the single project symbol table across edits.
42
+ - `server.ts` — `createServer(connection)` wires diagnostics and whole-document formatting handlers onto an injected connection.
43
+ - `start-server.ts` — `startServer()` creates a stdio connection and starts the server. This is what the CLI delegates to.
44
+
45
+ ## Package Location
46
+
47
+ - **Domain**: framework (target-agnostic)
48
+ - **Layer**: tooling
49
+ - **Plane**: migration
50
+ - **Path**: `packages/1-framework/3-tooling/language-server`
@@ -0,0 +1,41 @@
1
+ import { Connection } from "vscode-languageserver";
2
+ import { SymbolTable } from "@prisma-next/psl-parser";
3
+ import { DocumentAst, ParseDiagnostic, Range, SourceFile } from "@prisma-next/psl-parser/syntax";
4
+ //#region src/diagnostic-mapping.d.ts
5
+ declare const ParseDiagnosticSeverity: {
6
+ readonly Error: 1;
7
+ readonly Warning: 2;
8
+ readonly Information: 3;
9
+ readonly Hint: 4;
10
+ };
11
+ interface LspDiagnostic {
12
+ readonly range: Range;
13
+ readonly message: string;
14
+ readonly code: string;
15
+ readonly severity: number;
16
+ }
17
+ declare function mapParseDiagnostics(diagnostics: readonly ParseDiagnostic[]): readonly LspDiagnostic[];
18
+ //#endregion
19
+ //#region src/project-artifacts.d.ts
20
+ interface CachedDocument {
21
+ readonly document: DocumentAst;
22
+ readonly sourceFile: SourceFile;
23
+ }
24
+ //#endregion
25
+ //#region src/server.d.ts
26
+ interface LanguageServer {
27
+ dispose(): void;
28
+ /**
29
+ * Exposed for future features (completion, semantic tokens); nothing consumes
30
+ * them yet.
31
+ */
32
+ getDocumentAst(uri: string): CachedDocument | undefined;
33
+ getProjectSymbolTable(uri: string): SymbolTable | undefined;
34
+ }
35
+ declare function createServer(connection: Connection): LanguageServer;
36
+ //#endregion
37
+ //#region src/start-server.d.ts
38
+ declare function startServer(): LanguageServer;
39
+ //#endregion
40
+ export { type LanguageServer, type LspDiagnostic, ParseDiagnosticSeverity, createServer, mapParseDiagnostics, startServer };
41
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/diagnostic-mapping.ts","../../src/project-artifacts.ts","../../src/server.ts","../../src/start-server.ts"],"mappings":";;;;cAEa,uBAAA;EAAA;;;;;UAOI,aAAA;EAAA,SACN,KAAA,EAAO,KAAK;EAAA,SACZ,OAAA;EAAA,SACA,IAAA;EAAA,SACA,QAAA;AAAA;AAAA,iBAGK,mBAAA,CACd,WAAA,WAAsB,eAAA,cACZ,aAAa;;;UCXR,cAAA;EAAA,SACN,QAAA,EAAU,WAAA;EAAA,SACV,UAAA,EAAY,UAAU;AAAA;;;UCmBhB,cAAA;EACf,OAAA;;AF3BF;;;EEgCE,cAAA,CAAe,GAAA,WAAc,cAAA;EAC7B,qBAAA,CAAsB,GAAA,WAAc,WAAW;AAAA;AAAA,iBAejC,YAAA,CAAa,UAAA,EAAY,UAAA,GAAa,cAAc;;;iBC/CpD,WAAA,IAAe,cAAc"}
@@ -0,0 +1,380 @@
1
+ import { join } from "node:path";
2
+ import { fileURLToPath, pathToFileURL } from "node:url";
3
+ import { findNearestConfigPathForFile, loadConfig } from "@prisma-next/config-loader";
4
+ import { format } from "@prisma-next/psl-parser/format";
5
+ import { DiagnosticSeverity, DidChangeWatchedFilesNotification, RegistrationRequest, TextDocumentSyncKind, TextDocuments } from "vscode-languageserver";
6
+ import { TextDocument } from "vscode-languageserver-textdocument";
7
+ import { createControlStack } from "@prisma-next/framework-components/control";
8
+ import { buildSymbolTable } from "@prisma-next/psl-parser";
9
+ import { parse } from "@prisma-next/psl-parser/syntax";
10
+ import { ProposedFeatures, createConnection } from "vscode-languageserver/node";
11
+ //#region src/diagnostic-mapping.ts
12
+ const ParseDiagnosticSeverity = {
13
+ Error: 1,
14
+ Warning: 2,
15
+ Information: 3,
16
+ Hint: 4
17
+ };
18
+ function mapParseDiagnostics(diagnostics) {
19
+ return diagnostics.map((diagnostic) => ({
20
+ range: diagnostic.range,
21
+ message: diagnostic.message,
22
+ code: diagnostic.code,
23
+ severity: ParseDiagnosticSeverity.Error
24
+ }));
25
+ }
26
+ //#endregion
27
+ //#region src/schema-inputs.ts
28
+ function hasPslInputs(config) {
29
+ const source = config.contract?.source;
30
+ return source?.sourceFormat === "psl" && source.inputs !== void 0;
31
+ }
32
+ function resolveSchemaInputs(config) {
33
+ const inputs = hasPslInputs(config) ? config.contract?.source.inputs : void 0;
34
+ const uris = new Set(inputs?.map((input) => pathToFileURL(input).toString()));
35
+ return { includes: (uri) => uris.has(uri) };
36
+ }
37
+ //#endregion
38
+ //#region src/config-resolution.ts
39
+ const CONFIG_FILENAME = "prisma-next.config.ts";
40
+ const emptyPipelineInputs = {
41
+ scalarTypes: [],
42
+ pslBlockDescriptors: {}
43
+ };
44
+ async function resolveConfigInputs(configPath) {
45
+ const config = await loadConfig(configPath);
46
+ const inputs = resolveSchemaInputs(config);
47
+ const controlStack = resolveControlStackInputs(config) ?? emptyPipelineInputs;
48
+ return config.formatter === void 0 ? {
49
+ inputs,
50
+ controlStack
51
+ } : {
52
+ inputs,
53
+ formatter: config.formatter,
54
+ controlStack
55
+ };
56
+ }
57
+ function resolveControlStackInputs(config) {
58
+ if (!hasPslInputs(config)) return;
59
+ const stack = createControlStack(config);
60
+ return {
61
+ scalarTypes: [...stack.scalarTypeDescriptors.keys()],
62
+ pslBlockDescriptors: stack.authoringContributions.pslBlockDescriptors
63
+ };
64
+ }
65
+ //#endregion
66
+ //#region src/pipeline.ts
67
+ /**
68
+ * Composes the stages exactly as the contract-psl provider does, so the editor
69
+ * and the build agree: `parse` then `buildSymbolTable`, parse diagnostics ahead
70
+ * of symbol-table diagnostics. Never throws on malformed input — `parse`
71
+ * recovers and `buildSymbolTable` is documented not to throw.
72
+ */
73
+ function runPipeline(text, inputs) {
74
+ const { document, sourceFile, diagnostics: parseDiagnostics } = parse(text);
75
+ const { table: symbolTable, diagnostics: symbolTableDiagnostics } = buildSymbolTable({
76
+ document,
77
+ sourceFile,
78
+ scalarTypes: inputs.scalarTypes,
79
+ pslBlockDescriptors: inputs.pslBlockDescriptors
80
+ });
81
+ return {
82
+ document,
83
+ sourceFile,
84
+ symbolTable,
85
+ diagnostics: mapParseDiagnostics([...parseDiagnostics, ...symbolTableDiagnostics])
86
+ };
87
+ }
88
+ //#endregion
89
+ //#region src/document-diagnostics.ts
90
+ /**
91
+ * `null` (not a configured input) is distinct from a `DocumentDiagnostics` whose
92
+ * `diagnostics` are `[]` (an input that parsed clean): the caller treats both as
93
+ * "publish no diagnostics", but only the latter is a document we own and keep
94
+ * diagnosing.
95
+ */
96
+ function computeDocumentDiagnostics(uri, text, inputs, controlStack) {
97
+ if (!inputs.includes(uri)) return null;
98
+ const { document, sourceFile, symbolTable, diagnostics } = runPipeline(text, controlStack);
99
+ return {
100
+ diagnostics,
101
+ document,
102
+ sourceFile,
103
+ symbolTable
104
+ };
105
+ }
106
+ //#endregion
107
+ //#region src/project-artifacts.ts
108
+ function createProjectArtifacts() {
109
+ const documents = /* @__PURE__ */ new Map();
110
+ let symbolTable;
111
+ return {
112
+ getDocument: (uri) => documents.get(uri),
113
+ getSymbolTable: () => symbolTable,
114
+ update: (uri, text, inputs, controlStack) => {
115
+ const computed = computeDocumentDiagnostics(uri, text, inputs, controlStack);
116
+ if (computed === null) {
117
+ if (documents.delete(uri)) symbolTable = void 0;
118
+ return null;
119
+ }
120
+ documents.set(uri, {
121
+ document: computed.document,
122
+ sourceFile: computed.sourceFile
123
+ });
124
+ symbolTable = computed.symbolTable;
125
+ return computed.diagnostics;
126
+ },
127
+ remove: (uri) => {
128
+ if (documents.delete(uri)) symbolTable = void 0;
129
+ }
130
+ };
131
+ }
132
+ //#endregion
133
+ //#region src/server.ts
134
+ function createServer(connection) {
135
+ const documents = new TextDocuments(TextDocument);
136
+ const projects = /* @__PURE__ */ new Map();
137
+ const projectLoads = /* @__PURE__ */ new Map();
138
+ const documentConfigPaths = /* @__PURE__ */ new Map();
139
+ let rootPath = process.cwd();
140
+ let watchedConfigGlob = join(rootPath, "**", CONFIG_FILENAME);
141
+ let supportsWatchedFilesRegistration = false;
142
+ async function publish(uri, text) {
143
+ const project = await resolveProjectForDocument(uri);
144
+ if (project === void 0) return;
145
+ const currentDocument = documents.get(uri);
146
+ if (currentDocument === void 0) {
147
+ documentConfigPaths.delete(uri);
148
+ return;
149
+ }
150
+ if (currentDocument.getText() !== text) return;
151
+ const computed = project.artifacts.update(uri, text, project.inputs, project.controlStack);
152
+ if (computed === null) {
153
+ connection.sendDiagnostics({
154
+ uri,
155
+ diagnostics: []
156
+ });
157
+ return;
158
+ }
159
+ const diagnostics = computed.map((diagnostic) => ({
160
+ range: diagnostic.range,
161
+ message: diagnostic.message,
162
+ code: diagnostic.code,
163
+ severity: toLspSeverity(diagnostic.severity),
164
+ source: "prisma-next"
165
+ }));
166
+ connection.sendDiagnostics({
167
+ uri,
168
+ diagnostics
169
+ });
170
+ }
171
+ async function resolveProjectForDocument(uri) {
172
+ const knownConfigPath = documentConfigPaths.get(uri);
173
+ if (knownConfigPath !== void 0) return resolveProject(knownConfigPath);
174
+ const filePath = filePathFromUri(uri);
175
+ if (filePath === void 0) return;
176
+ const configPath = await findNearestConfigPathForFile(filePath);
177
+ if (configPath === void 0) return;
178
+ documentConfigPaths.set(uri, configPath);
179
+ const project = await resolveProjectIfLoadable(configPath);
180
+ if (project === void 0) documentConfigPaths.delete(uri);
181
+ return project;
182
+ }
183
+ async function resolveProjectIfLoadable(configPath) {
184
+ try {
185
+ return await resolveProject(configPath);
186
+ } catch {
187
+ stopManagingProject(configPath);
188
+ return;
189
+ }
190
+ }
191
+ async function resolveProject(configPath) {
192
+ const existing = projects.get(configPath);
193
+ if (existing !== void 0) return existing;
194
+ const existingLoad = projectLoads.get(configPath);
195
+ if (existingLoad !== void 0) return existingLoad;
196
+ return queueProjectLoad(configPath);
197
+ }
198
+ function refreshProject(configPath) {
199
+ return queueProjectLoad(configPath);
200
+ }
201
+ function queueProjectLoad(configPath) {
202
+ const load = (projectLoads.get(configPath) ?? Promise.resolve()).catch(() => void 0).then(() => loadProject(configPath)).finally(() => {
203
+ if (projectLoads.get(configPath) === load) projectLoads.delete(configPath);
204
+ });
205
+ projectLoads.set(configPath, load);
206
+ return load;
207
+ }
208
+ async function loadProject(configPath) {
209
+ const resolution = await resolveConfigInputs(configPath);
210
+ const artifacts = projects.get(configPath)?.artifacts ?? createProjectArtifacts();
211
+ const project = resolution.formatter === void 0 ? {
212
+ configPath,
213
+ inputs: resolution.inputs,
214
+ controlStack: resolution.controlStack,
215
+ artifacts
216
+ } : {
217
+ configPath,
218
+ inputs: resolution.inputs,
219
+ formatter: resolution.formatter,
220
+ controlStack: resolution.controlStack,
221
+ artifacts
222
+ };
223
+ projects.set(configPath, project);
224
+ return project;
225
+ }
226
+ function stopManagingProject(configPath) {
227
+ const hadProject = projects.delete(configPath);
228
+ for (const document of documents.all()) if (documentConfigPaths.get(document.uri) === configPath) {
229
+ documentConfigPaths.delete(document.uri);
230
+ if (hadProject) connection.sendDiagnostics({
231
+ uri: document.uri,
232
+ diagnostics: []
233
+ });
234
+ }
235
+ }
236
+ async function republishOpenDocumentsForConfig(configPath) {
237
+ for (const document of documents.all()) {
238
+ if (documentConfigPaths.get(document.uri) === configPath) {
239
+ await publish(document.uri, document.getText());
240
+ continue;
241
+ }
242
+ const filePath = filePathFromUri(document.uri);
243
+ if (filePath === void 0) continue;
244
+ if (await findNearestConfigPathForFile(filePath) === configPath) {
245
+ documentConfigPaths.set(document.uri, configPath);
246
+ await publish(document.uri, document.getText());
247
+ }
248
+ }
249
+ }
250
+ function publishSafely(uri, text) {
251
+ publish(uri, text).catch((error) => {
252
+ connection.console.error(error instanceof Error ? error.message : String(error));
253
+ });
254
+ }
255
+ async function formatDocument(uri) {
256
+ const document = documents.get(uri);
257
+ if (document === void 0) return [];
258
+ let project;
259
+ try {
260
+ project = await resolveProjectForDocument(uri);
261
+ } catch {
262
+ return [];
263
+ }
264
+ if (project === void 0 || !project.inputs.includes(uri)) return [];
265
+ const source = document.getText();
266
+ let formatted;
267
+ try {
268
+ formatted = format(source, project.formatter);
269
+ } catch {
270
+ return [];
271
+ }
272
+ if (formatted === source) return [];
273
+ return [{
274
+ range: {
275
+ start: {
276
+ line: 0,
277
+ character: 0
278
+ },
279
+ end: document.positionAt(source.length)
280
+ },
281
+ newText: formatted
282
+ }];
283
+ }
284
+ connection.onInitialize(async (params) => {
285
+ rootPath = resolveRootPath(params.rootUri, params.rootPath);
286
+ watchedConfigGlob = join(rootPath, "**", CONFIG_FILENAME);
287
+ supportsWatchedFilesRegistration = clientSupportsWatchedFilesRegistration(params);
288
+ return { capabilities: {
289
+ textDocumentSync: TextDocumentSyncKind.Incremental,
290
+ documentFormattingProvider: true
291
+ } };
292
+ });
293
+ connection.onInitialized(() => {
294
+ if (supportsWatchedFilesRegistration) connection.sendRequest(RegistrationRequest.type, { registrations: [{
295
+ id: "prisma-next-config-watcher",
296
+ method: DidChangeWatchedFilesNotification.type.method,
297
+ registerOptions: { watchers: [{ globPattern: watchedConfigGlob }] }
298
+ }] }).catch(() => void 0);
299
+ else connection.console.warn("Client does not support dynamic file-watcher registration; Prisma Next config changes will not be picked up without a restart.");
300
+ });
301
+ connection.onDidChangeWatchedFiles(async (params) => {
302
+ const changedConfigPaths = configPathsFromWatchedChanges(params.changes.map((change) => filePathFromUri(change.uri)));
303
+ for (const configPath of changedConfigPaths) {
304
+ try {
305
+ await refreshProject(configPath);
306
+ } catch {
307
+ stopManagingProject(configPath);
308
+ continue;
309
+ }
310
+ await republishOpenDocumentsForConfig(configPath);
311
+ }
312
+ });
313
+ connection.onDocumentFormatting((params) => formatDocument(params.textDocument.uri));
314
+ documents.onDidOpen((event) => {
315
+ publishSafely(event.document.uri, event.document.getText());
316
+ });
317
+ documents.onDidChangeContent((event) => {
318
+ publishSafely(event.document.uri, event.document.getText());
319
+ });
320
+ documents.onDidClose((event) => {
321
+ const uri = event.document.uri;
322
+ const configPath = documentConfigPaths.get(uri);
323
+ if (configPath !== void 0) projects.get(configPath)?.artifacts.remove(uri);
324
+ documentConfigPaths.delete(uri);
325
+ connection.sendDiagnostics({
326
+ uri,
327
+ diagnostics: []
328
+ });
329
+ });
330
+ documents.listen(connection);
331
+ connection.listen();
332
+ function artifactsForDocument(uri) {
333
+ const configPath = documentConfigPaths.get(uri);
334
+ return configPath === void 0 ? void 0 : projects.get(configPath)?.artifacts;
335
+ }
336
+ return {
337
+ dispose: () => {
338
+ connection.dispose();
339
+ },
340
+ getDocumentAst: (uri) => artifactsForDocument(uri)?.getDocument(uri),
341
+ getProjectSymbolTable: (uri) => artifactsForDocument(uri)?.getSymbolTable()
342
+ };
343
+ }
344
+ function toLspSeverity(severity) {
345
+ switch (severity) {
346
+ case ParseDiagnosticSeverity.Warning: return DiagnosticSeverity.Warning;
347
+ case ParseDiagnosticSeverity.Information: return DiagnosticSeverity.Information;
348
+ case ParseDiagnosticSeverity.Hint: return DiagnosticSeverity.Hint;
349
+ default: return DiagnosticSeverity.Error;
350
+ }
351
+ }
352
+ function clientSupportsWatchedFilesRegistration(params) {
353
+ return params.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration === true;
354
+ }
355
+ function resolveRootPath(rootUri, rootPath) {
356
+ if (rootUri) return fileURLToPath(rootUri);
357
+ if (rootPath) return rootPath;
358
+ return process.cwd();
359
+ }
360
+ function filePathFromUri(uri) {
361
+ try {
362
+ return fileURLToPath(uri);
363
+ } catch {
364
+ return;
365
+ }
366
+ }
367
+ function configPathsFromWatchedChanges(paths) {
368
+ const configPaths = /* @__PURE__ */ new Set();
369
+ for (const path of paths) if (path?.endsWith("prisma-next.config.ts")) configPaths.add(path);
370
+ return configPaths;
371
+ }
372
+ //#endregion
373
+ //#region src/start-server.ts
374
+ function startServer() {
375
+ return createServer(createConnection(ProposedFeatures.all));
376
+ }
377
+ //#endregion
378
+ export { ParseDiagnosticSeverity, createServer, mapParseDiagnostics, startServer };
379
+
380
+ //# sourceMappingURL=index.mjs.map