tailwint 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,410 @@
1
+ /**
2
+ * Tests for applyEdits from tailwint/edits.ts
3
+ */
4
+ import { describe, it } from "node:test";
5
+ import { strict as assert } from "node:assert";
6
+ import { applyEdits } from "./edits.js";
7
+ // ---------------------------------------------------------------------------
8
+ // Helpers
9
+ // ---------------------------------------------------------------------------
10
+ /** Shorthand to build a TextEdit */
11
+ function edit(startLine, startChar, endLine, endChar, newText) {
12
+ return {
13
+ range: {
14
+ start: { line: startLine, character: startChar },
15
+ end: { line: endLine, character: endChar },
16
+ },
17
+ newText,
18
+ };
19
+ }
20
+ // ---------------------------------------------------------------------------
21
+ // Tests
22
+ // ---------------------------------------------------------------------------
23
+ describe("applyEdits", () => {
24
+ // ---- Basic operations ----
25
+ it("returns content unchanged for empty edits array", () => {
26
+ assert.equal(applyEdits("hello", []), "hello");
27
+ });
28
+ it("returns content unchanged for empty string input with no edits", () => {
29
+ assert.equal(applyEdits("", []), "");
30
+ });
31
+ it("replaces a single word", () => {
32
+ assert.equal(applyEdits("flex-shrink-0", [edit(0, 0, 0, 13, "shrink-0")]), "shrink-0");
33
+ });
34
+ it("inserts text at the beginning", () => {
35
+ assert.equal(applyEdits("world", [edit(0, 0, 0, 0, "hello ")]), "hello world");
36
+ });
37
+ it("inserts text at the end", () => {
38
+ assert.equal(applyEdits("hello", [edit(0, 5, 0, 5, " world")]), "hello world");
39
+ });
40
+ it("deletes text (empty newText)", () => {
41
+ assert.equal(applyEdits("hello world", [edit(0, 5, 0, 11, "")]), "hello");
42
+ });
43
+ // ---- Multiple edits on the same line ----
44
+ it("applies two non-overlapping edits on the same line", () => {
45
+ const content = "z-[1] flex-shrink-0";
46
+ const result = applyEdits(content, [
47
+ edit(0, 0, 0, 5, "z-1"),
48
+ edit(0, 6, 0, 19, "shrink-0"),
49
+ ]);
50
+ assert.equal(result, "z-1 shrink-0");
51
+ });
52
+ it("applies edits regardless of input order (unsorted)", () => {
53
+ const content = "z-[1] flex-shrink-0";
54
+ // Provide edits in reverse order — should still work
55
+ const result = applyEdits(content, [
56
+ edit(0, 6, 0, 19, "shrink-0"),
57
+ edit(0, 0, 0, 5, "z-1"),
58
+ ]);
59
+ assert.equal(result, "z-1 shrink-0");
60
+ });
61
+ it("applies three edits on the same line", () => {
62
+ const content = "z-[1] flex-shrink-0 min-w-[200px]";
63
+ const result = applyEdits(content, [
64
+ edit(0, 0, 0, 5, "z-1"),
65
+ edit(0, 6, 0, 19, "shrink-0"),
66
+ edit(0, 20, 0, 33, "min-w-50"),
67
+ ]);
68
+ assert.equal(result, "z-1 shrink-0 min-w-50");
69
+ });
70
+ // ---- Adjacent edits (shared boundary) ----
71
+ it("handles adjacent edits that share a boundary", () => {
72
+ const content = "aabbcc";
73
+ const result = applyEdits(content, [
74
+ edit(0, 0, 0, 2, "AA"),
75
+ edit(0, 2, 0, 4, "BB"),
76
+ edit(0, 4, 0, 6, "CC"),
77
+ ]);
78
+ assert.equal(result, "AABBCC");
79
+ });
80
+ it("handles adjacent insert-then-replace at same position", () => {
81
+ // Two edits at position 0: first is a zero-width insert, second replaces chars 0-2
82
+ // This is ambiguous — cursor advances past the first edit's end (0),
83
+ // so the second edit at start=0 would have start < cursor after the first.
84
+ // Current implementation: second edit's content replaces, but start <= cursor
85
+ // means the slice between them is empty.
86
+ const content = "abc";
87
+ const result = applyEdits(content, [
88
+ edit(0, 0, 0, 0, "X"), // insert X at position 0
89
+ edit(0, 0, 0, 1, "Y"), // replace 'a' with Y
90
+ ]);
91
+ // Both edits start at offset 0. After sorting, they're in input order (stable sort?).
92
+ // First edit: start=0, end=0 → inserts "X", cursor=0
93
+ // Second edit: start=0 >= cursor(0), end=1 → but start is NOT > cursor, so no gap slice
94
+ // Result: "X" + "Y" + "bc" = "XYbc"
95
+ // This might be surprising — the "a" is deleted by the second edit but "X" is also inserted.
96
+ // Let's just verify the actual behavior.
97
+ assert.equal(result, "XYbc");
98
+ });
99
+ // ---- Multi-line edits ----
100
+ it("replaces across multiple lines", () => {
101
+ const content = "line1\nline2\nline3";
102
+ const result = applyEdits(content, [
103
+ edit(0, 3, 2, 3, "REPLACED"),
104
+ ]);
105
+ assert.equal(result, "linREPLACEDe3");
106
+ });
107
+ it("applies edits on different lines", () => {
108
+ const content = "aaa\nbbb\nccc";
109
+ const result = applyEdits(content, [
110
+ edit(0, 0, 0, 3, "AAA"),
111
+ edit(2, 0, 2, 3, "CCC"),
112
+ ]);
113
+ assert.equal(result, "AAA\nbbb\nCCC");
114
+ });
115
+ it("deletes an entire line including newline", () => {
116
+ const content = "keep\ndelete\nkeep";
117
+ const result = applyEdits(content, [
118
+ edit(1, 0, 2, 0, ""),
119
+ ]);
120
+ assert.equal(result, "keep\nkeep");
121
+ });
122
+ it("inserts a new line", () => {
123
+ const content = "line1\nline3";
124
+ const result = applyEdits(content, [
125
+ edit(1, 0, 1, 0, "line2\n"),
126
+ ]);
127
+ assert.equal(result, "line1\nline2\nline3");
128
+ });
129
+ // ---- Edge cases: out-of-bounds ----
130
+ it("handles edit past end of file (line beyond last)", () => {
131
+ const content = "hello";
132
+ const result = applyEdits(content, [
133
+ edit(5, 0, 5, 0, " world"),
134
+ ]);
135
+ // Line 5 doesn't exist — toOffset clamps to content.length
136
+ assert.equal(result, "hello world");
137
+ });
138
+ it("handles edit with character past end of line", () => {
139
+ const content = "hi";
140
+ const result = applyEdits(content, [
141
+ edit(0, 100, 0, 100, "!"),
142
+ ]);
143
+ // Character 100 on a 2-char line clamps to position 2
144
+ assert.equal(result, "hi!");
145
+ });
146
+ // ---- Edge cases: empty content ----
147
+ it("inserts into empty string", () => {
148
+ assert.equal(applyEdits("", [edit(0, 0, 0, 0, "hello")]), "hello");
149
+ });
150
+ it("handles edit on empty string with out-of-bounds range", () => {
151
+ assert.equal(applyEdits("", [edit(0, 0, 0, 10, "hello")]), "hello");
152
+ });
153
+ // ---- CRLF line endings ----
154
+ it("handles CRLF line endings", () => {
155
+ const content = "line1\r\nline2\r\nline3";
156
+ // With CRLF, \r is a regular character — only \n triggers new line offset.
157
+ // So line 1 starts after the \n at position 7 (l-i-n-e-1-\r-\n = 7 chars).
158
+ // "line2" on line 1 starts at offset 7, char 0.
159
+ const result = applyEdits(content, [
160
+ edit(1, 0, 1, 5, "LINE2"),
161
+ ]);
162
+ assert.equal(result, "line1\r\nLINE2\r\nline3");
163
+ });
164
+ it("CRLF: replacing including \\r works correctly", () => {
165
+ const content = "aa\r\nbb";
166
+ // Line 0 is "aa\r", line 1 starts at offset 4
167
+ // Replace from (0,2) to (1,0) — should delete "\r\n"
168
+ const result = applyEdits(content, [
169
+ edit(0, 2, 1, 0, ""),
170
+ ]);
171
+ assert.equal(result, "aabb");
172
+ });
173
+ // ---- Unicode and emoji ----
174
+ it("handles unicode content correctly", () => {
175
+ const content = "café";
176
+ // "café" — the é is one JS char (U+00E9)
177
+ const result = applyEdits(content, [
178
+ edit(0, 0, 0, 4, "CAFÉ"),
179
+ ]);
180
+ assert.equal(result, "CAFÉ");
181
+ });
182
+ it("handles emoji content", () => {
183
+ // "hi 👋 there" — 👋 is 2 JS chars (surrogate pair)
184
+ const content = "hi 👋 there";
185
+ // LSP character offsets use UTF-16 code units, same as JS string length
186
+ // "hi " = 3 chars, "👋" = 2 chars, " there" = 6 chars
187
+ // Replace "👋" (chars 3-5) with "🎉" (also 2 chars)
188
+ const result = applyEdits(content, [
189
+ edit(0, 3, 0, 5, "🎉"),
190
+ ]);
191
+ assert.equal(result, "hi 🎉 there");
192
+ });
193
+ // ---- Overlapping edits (potentially dangerous) ----
194
+ it("overlapping edits: second edit starts inside first edit's range", () => {
195
+ const content = "abcdef";
196
+ // Edit 1: replace chars 1-4 ("bcd") with "X"
197
+ // Edit 2: replace chars 2-5 ("cde") with "Y"
198
+ // After sorting: edit1 (start=1) comes first, cursor advances to 4
199
+ // edit2 (start=2) has start < cursor(4), so no gap, but edit2's
200
+ // newText "Y" is still pushed and cursor goes to 5.
201
+ // This produces: "a" + "X" + "Y" + "f" = "aXYf"
202
+ // The overlap means chars 2-4 are "deleted twice" — 'c' and 'd' appear
203
+ // in both edit ranges. The implementation doesn't detect this.
204
+ const result = applyEdits(content, [
205
+ edit(0, 1, 0, 4, "X"),
206
+ edit(0, 2, 0, 5, "Y"),
207
+ ]);
208
+ assert.equal(result, "aXYf");
209
+ });
210
+ // ---- Realistic Tailwind scenarios ----
211
+ it("fixes className with multiple bracket notations", () => {
212
+ const content = `<div className="w-[1200px] h-[630px] overflow-hidden">`;
213
+ // w-[1200px] = chars 16-26 (end exclusive), h-[630px] = chars 27-36 (end exclusive)
214
+ const result = applyEdits(content, [
215
+ edit(0, 16, 0, 26, "w-300"),
216
+ edit(0, 27, 0, 36, "h-157.5"),
217
+ ]);
218
+ assert.equal(result, `<div className="w-300 h-157.5 overflow-hidden">`);
219
+ });
220
+ it("fixes multi-line JSX with edits on different lines", () => {
221
+ const content = [
222
+ `<div`,
223
+ ` className="z-[1] flex-shrink-0"`,
224
+ ` style={{}}`,
225
+ `/>`,
226
+ ].join("\n");
227
+ // z-[1] starts at char 13 on line 1, flex-shrink-0 at char 19
228
+ const result = applyEdits(content, [
229
+ edit(1, 13, 1, 18, "z-1"),
230
+ edit(1, 19, 1, 32, "shrink-0"),
231
+ ]);
232
+ const expected = [
233
+ `<div`,
234
+ ` className="z-1 shrink-0"`,
235
+ ` style={{}}`,
236
+ `/>`,
237
+ ].join("\n");
238
+ assert.equal(result, expected);
239
+ });
240
+ // ---- Trailing newline ----
241
+ it("preserves trailing newline", () => {
242
+ const content = "hello\n";
243
+ const result = applyEdits(content, [
244
+ edit(0, 0, 0, 5, "world"),
245
+ ]);
246
+ assert.equal(result, "world\n");
247
+ });
248
+ it("edit on the empty last line after trailing newline", () => {
249
+ const content = "hello\n";
250
+ // Line 1 exists (empty, after the \n). Insert there.
251
+ const result = applyEdits(content, [
252
+ edit(1, 0, 1, 0, "world"),
253
+ ]);
254
+ assert.equal(result, "hello\nworld");
255
+ });
256
+ // ---- Stress: many edits ----
257
+ it("handles 50 edits across 50 lines", () => {
258
+ const lines = Array.from({ length: 50 }, (_, i) => `line-${i}-old`);
259
+ const content = lines.join("\n");
260
+ const edits = lines.map((_, i) => {
261
+ const old = `line-${i}-old`;
262
+ return edit(i, 0, i, old.length, `line-${i}-new`);
263
+ });
264
+ const result = applyEdits(content, edits);
265
+ const expected = Array.from({ length: 50 }, (_, i) => `line-${i}-new`).join("\n");
266
+ assert.equal(result, expected);
267
+ });
268
+ // ---- Zero-width replacements at various positions ----
269
+ it("multiple zero-width inserts at different positions", () => {
270
+ const content = "ac";
271
+ const result = applyEdits(content, [
272
+ edit(0, 1, 0, 1, "b"), // insert 'b' between 'a' and 'c'
273
+ ]);
274
+ assert.equal(result, "abc");
275
+ });
276
+ it("multiple zero-width inserts at the same position", () => {
277
+ // Two inserts at position 1 — both have start=end=1
278
+ // After sorting they're both at offset 1, first insert "X", cursor stays at 1,
279
+ // second insert "Y", cursor stays at 1
280
+ const content = "ac";
281
+ const result = applyEdits(content, [
282
+ edit(0, 1, 0, 1, "X"),
283
+ edit(0, 1, 0, 1, "Y"),
284
+ ]);
285
+ // Both inserts land at offset 1: "a" + "X" + "Y" + "c"
286
+ assert.equal(result, "aXYc");
287
+ });
288
+ // ---- Edit that replaces entire content ----
289
+ it("replaces entire content with single edit", () => {
290
+ const content = "old content\nwith multiple\nlines";
291
+ const result = applyEdits(content, [
292
+ edit(0, 0, 2, 5, "new"),
293
+ ]);
294
+ assert.equal(result, "new");
295
+ });
296
+ // ---- Only newlines ----
297
+ it("handles content that is only newlines", () => {
298
+ const content = "\n\n\n";
299
+ const result = applyEdits(content, [
300
+ edit(1, 0, 1, 0, "inserted"),
301
+ ]);
302
+ assert.equal(result, "\ninserted\n\n");
303
+ });
304
+ // ---- Probing for subtle bugs ----
305
+ it("edit where replacement is longer than original (grows the line)", () => {
306
+ const content = "ab";
307
+ const result = applyEdits(content, [
308
+ edit(0, 0, 0, 1, "AAAA"), // replace 'a' (1 char) with 'AAAA' (4 chars)
309
+ ]);
310
+ assert.equal(result, "AAAAb");
311
+ });
312
+ it("edit where replacement is shorter than original (shrinks the line)", () => {
313
+ const content = "aaaab";
314
+ const result = applyEdits(content, [
315
+ edit(0, 0, 0, 4, "X"), // replace 'aaaa' (4 chars) with 'X' (1 char)
316
+ ]);
317
+ assert.equal(result, "Xb");
318
+ });
319
+ it("two edits where first shrinks and second uses original offsets", () => {
320
+ // This is the key scenario: after first edit shrinks, do second edit's
321
+ // original offsets still work correctly?
322
+ const content = "aaa bbb ccc";
323
+ // Replace 'aaa' (0-3) with 'x', replace 'ccc' (8-11) with 'z'
324
+ const result = applyEdits(content, [
325
+ edit(0, 0, 0, 3, "x"),
326
+ edit(0, 8, 0, 11, "z"),
327
+ ]);
328
+ // Since we use original offsets: "x" + content[3:8]=" bbb " + "z"
329
+ assert.equal(result, "x bbb z");
330
+ });
331
+ it("two edits where first grows and second uses original offsets", () => {
332
+ const content = "a b c";
333
+ const result = applyEdits(content, [
334
+ edit(0, 0, 0, 1, "XXXX"), // 'a' → 'XXXX'
335
+ edit(0, 4, 0, 5, "ZZZZ"), // 'c' → 'ZZZZ'
336
+ ]);
337
+ assert.equal(result, "XXXX b ZZZZ");
338
+ });
339
+ it("edit that deletes everything and inserts nothing", () => {
340
+ const content = "hello\nworld";
341
+ const result = applyEdits(content, [
342
+ edit(0, 0, 1, 5, ""),
343
+ ]);
344
+ assert.equal(result, "");
345
+ });
346
+ it("edit range with end before start (invalid range)", () => {
347
+ // Pathological: end offset < start offset after conversion
348
+ // toOffset(0,5) = 5, toOffset(0,2) = 2 → start=5, end=2
349
+ // After sort, this edit has start=5 > cursor=0, so we'd push content[0:5]
350
+ // then push newText, then cursor=2 which is < 5...
351
+ // This should behave oddly. Let's see what happens.
352
+ const content = "abcdef";
353
+ const result = applyEdits(content, [
354
+ edit(0, 5, 0, 2, "X"), // start > end
355
+ ]);
356
+ // start=5, end=2: push "abcde" (0-5), push "X", cursor=2
357
+ // cursor(2) < content.length(6), push content[2:] = "cdef"
358
+ // Result: "abcdeXcdef" — the reversed range causes duplication
359
+ assert.equal(result, "abcdeXcdef");
360
+ });
361
+ it("consecutive edits that delete and insert on multi-line content", () => {
362
+ const content = "line1\nline2\nline3\nline4\nline5";
363
+ // Delete line2, replace line4 with NEW4
364
+ const result = applyEdits(content, [
365
+ edit(1, 0, 2, 0, ""), // delete "line2\n"
366
+ edit(3, 0, 3, 5, "NEW4"), // replace "line4" with "NEW4"
367
+ ]);
368
+ assert.equal(result, "line1\nline3\nNEW4\nline5");
369
+ });
370
+ it("edit at exact end of content (no trailing newline)", () => {
371
+ const content = "end";
372
+ const result = applyEdits(content, [
373
+ edit(0, 3, 0, 3, "!"),
374
+ ]);
375
+ assert.equal(result, "end!");
376
+ });
377
+ it("many edits on the same line, varying replacement lengths", () => {
378
+ // Simulates what the LSP might do with a class like:
379
+ // "z-[1] flex-shrink-0 bg-primary/[0.06] min-w-[200px] h-[1px]"
380
+ const content = `className="z-[1] flex-shrink-0 bg-primary/[0.06] min-w-[200px] h-[1px]"`;
381
+ const result = applyEdits(content, [
382
+ edit(0, 11, 0, 16, "z-1"), // z-[1] → z-1
383
+ edit(0, 17, 0, 30, "shrink-0"), // flex-shrink-0 → shrink-0
384
+ edit(0, 31, 0, 48, "bg-primary/6"), // bg-primary/[0.06] → bg-primary/6
385
+ edit(0, 49, 0, 62, "min-w-50"), // min-w-[200px] → min-w-50
386
+ edit(0, 63, 0, 70, "h-px"), // h-[1px] → h-px
387
+ ]);
388
+ assert.equal(result, `className="z-1 shrink-0 bg-primary/6 min-w-50 h-px"`);
389
+ });
390
+ it("single char file with replacement", () => {
391
+ assert.equal(applyEdits("x", [edit(0, 0, 0, 1, "y")]), "y");
392
+ });
393
+ it("edit newText contains newlines (splitting a line)", () => {
394
+ const content = "before after";
395
+ const result = applyEdits(content, [
396
+ edit(0, 6, 0, 7, "\n"), // replace space with newline
397
+ ]);
398
+ assert.equal(result, "before\nafter");
399
+ });
400
+ it("edit that joins lines by replacing newline with space", () => {
401
+ const content = "before\nafter";
402
+ // The \n is at the end of line 0 (char 6 = the newline itself?).
403
+ // Actually, line 0 is "before", line 1 is "after".
404
+ // Range (0,6) to (1,0) covers just the \n character.
405
+ const result = applyEdits(content, [
406
+ edit(0, 6, 1, 0, " "),
407
+ ]);
408
+ assert.equal(result, "before after");
409
+ });
410
+ });
package/dist/lsp.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * LSP client — spawns tailwindcss-language-server over stdio and speaks JSON-RPC.
3
+ */
4
+ export declare const diagnosticsReceived: Map<string, any[]>;
5
+ export declare let projectReady: boolean;
6
+ /** Reset module state between runs (for programmatic multi-run usage). */
7
+ export declare function resetState(): void;
8
+ /** Returns a promise that resolves when @/tailwindCSS/projectInitialized fires. */
9
+ export declare function waitForProjectReady(timeoutMs?: number): Promise<void>;
10
+ /** Returns a promise that resolves when diagnosticsReceived.size >= count. */
11
+ export declare function waitForDiagnosticCount(count: number, timeoutMs?: number): Promise<void>;
12
+ /** Returns a promise that resolves when diagnostics are published for a specific URI. */
13
+ export declare function waitForDiagnostic(uri: string, timeoutMs?: number): Promise<any[]>;
14
+ export declare function startServer(root: string): void;
15
+ export declare function send(method: string, params: object): Promise<any>;
16
+ export declare function notify(method: string, params: object): void;
17
+ export declare function shutdown(): Promise<void>;
18
+ export declare function fileUri(absPath: string): string;
19
+ export declare function langId(filePath: string): string;
package/dist/lsp.js ADDED
@@ -0,0 +1,239 @@
1
+ /**
2
+ * LSP client — spawns tailwindcss-language-server over stdio and speaks JSON-RPC.
3
+ */
4
+ import { spawn } from "child_process";
5
+ import { resolve } from "path";
6
+ import { existsSync } from "fs";
7
+ const DEBUG = process.env.DEBUG === "1";
8
+ let server;
9
+ let msgId = 0;
10
+ const chunks = [];
11
+ let chunksLen = 0;
12
+ const pending = new Map();
13
+ export const diagnosticsReceived = new Map();
14
+ export let projectReady = false;
15
+ // ---------------------------------------------------------------------------
16
+ // Event-driven waiters — resolved by processMessages, no polling
17
+ // ---------------------------------------------------------------------------
18
+ let projectReadyResolve = null;
19
+ let diagTarget = 0;
20
+ let diagTargetResolve = null;
21
+ const diagWaiters = new Map();
22
+ /** Reset module state between runs (for programmatic multi-run usage). */
23
+ export function resetState() {
24
+ msgId = 0;
25
+ chunks.length = 0;
26
+ chunksLen = 0;
27
+ pending.clear();
28
+ diagnosticsReceived.clear();
29
+ projectReady = false;
30
+ projectReadyResolve = null;
31
+ diagTarget = 0;
32
+ diagTargetResolve = null;
33
+ diagWaiters.clear();
34
+ }
35
+ /** Returns a promise that resolves when @/tailwindCSS/projectInitialized fires. */
36
+ export function waitForProjectReady(timeoutMs = 15_000) {
37
+ if (projectReady)
38
+ return Promise.resolve();
39
+ return new Promise((res, rej) => {
40
+ projectReadyResolve = res;
41
+ const timer = setTimeout(() => {
42
+ projectReadyResolve = null;
43
+ res(); // resolve anyway — don't block forever
44
+ }, timeoutMs);
45
+ // Clean up timer if resolved early
46
+ const origRes = res;
47
+ projectReadyResolve = () => { clearTimeout(timer); origRes(); };
48
+ });
49
+ }
50
+ /** Returns a promise that resolves when diagnosticsReceived.size >= count. */
51
+ export function waitForDiagnosticCount(count, timeoutMs = 30_000) {
52
+ if (diagnosticsReceived.size >= count)
53
+ return Promise.resolve();
54
+ return new Promise((res) => {
55
+ diagTarget = count;
56
+ const timer = setTimeout(() => {
57
+ diagTargetResolve = null;
58
+ res();
59
+ }, timeoutMs);
60
+ diagTargetResolve = () => { clearTimeout(timer); res(); };
61
+ });
62
+ }
63
+ /** Returns a promise that resolves when diagnostics are published for a specific URI. */
64
+ export function waitForDiagnostic(uri, timeoutMs = 10_000) {
65
+ // Clear stale entry so we wait for the server to re-publish
66
+ diagnosticsReceived.delete(uri);
67
+ return new Promise((res) => {
68
+ diagWaiters.set(uri, res);
69
+ setTimeout(() => {
70
+ if (diagWaiters.has(uri)) {
71
+ diagWaiters.delete(uri);
72
+ res([]);
73
+ }
74
+ }, timeoutMs);
75
+ });
76
+ }
77
+ // ---------------------------------------------------------------------------
78
+ // JSON-RPC framing
79
+ // ---------------------------------------------------------------------------
80
+ function encode(obj) {
81
+ const body = JSON.stringify(obj);
82
+ return `Content-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`;
83
+ }
84
+ function getRawBuf() {
85
+ if (chunks.length === 0)
86
+ return Buffer.alloc(0);
87
+ if (chunks.length === 1)
88
+ return chunks[0];
89
+ const buf = Buffer.concat(chunks, chunksLen);
90
+ chunks.length = 0;
91
+ chunks.push(buf);
92
+ return buf;
93
+ }
94
+ function setRawBuf(buf) {
95
+ chunks.length = 0;
96
+ if (buf.length > 0) {
97
+ chunks.push(buf);
98
+ chunksLen = buf.length;
99
+ }
100
+ else {
101
+ chunksLen = 0;
102
+ }
103
+ }
104
+ function processMessages() {
105
+ while (true) {
106
+ const rawBuf = getRawBuf();
107
+ if (rawBuf.length === 0)
108
+ break;
109
+ const str = rawBuf.toString("ascii", 0, Math.min(rawBuf.length, 256));
110
+ const headerEnd = str.indexOf("\r\n\r\n");
111
+ if (headerEnd === -1) {
112
+ setRawBuf(rawBuf);
113
+ break;
114
+ }
115
+ const headerBlock = str.slice(0, headerEnd);
116
+ const clMatch = headerBlock.match(/Content-Length:\s*(\d+)/i);
117
+ if (!clMatch) {
118
+ setRawBuf(rawBuf.subarray(headerEnd + 4));
119
+ continue;
120
+ }
121
+ const len = parseInt(clMatch[1], 10);
122
+ const bodyStart = headerEnd + 4;
123
+ if (rawBuf.length < bodyStart + len) {
124
+ setRawBuf(rawBuf);
125
+ break;
126
+ }
127
+ const body = rawBuf.subarray(bodyStart, bodyStart + len).toString("utf-8");
128
+ setRawBuf(rawBuf.subarray(bodyStart + len));
129
+ let msg;
130
+ try {
131
+ msg = JSON.parse(body);
132
+ }
133
+ catch {
134
+ continue;
135
+ }
136
+ if (DEBUG)
137
+ console.error(`<- ${msg.method || `response#${msg.id}`}`);
138
+ // Response to our request
139
+ if (msg.id != null && !msg.method && pending.has(msg.id)) {
140
+ const p = pending.get(msg.id);
141
+ pending.delete(msg.id);
142
+ if (msg.error)
143
+ p.reject(msg.error);
144
+ else
145
+ p.resolve(msg.result);
146
+ continue;
147
+ }
148
+ // Server-initiated requests — must respond
149
+ if (msg.id != null && msg.method) {
150
+ let result = null;
151
+ if (msg.method === "workspace/configuration") {
152
+ result = (msg.params?.items || []).map(() => ({}));
153
+ }
154
+ server.stdin.write(encode({ jsonrpc: "2.0", id: msg.id, result }));
155
+ continue;
156
+ }
157
+ // Published diagnostics
158
+ if (msg.method === "textDocument/publishDiagnostics" && msg.params) {
159
+ const uri = msg.params.uri;
160
+ const diags = msg.params.diagnostics || [];
161
+ diagnosticsReceived.set(uri, diags);
162
+ // Resolve URI-specific waiter
163
+ if (diagWaiters.has(uri)) {
164
+ const resolve = diagWaiters.get(uri);
165
+ diagWaiters.delete(uri);
166
+ resolve(diags);
167
+ }
168
+ // Resolve count-based waiter
169
+ if (diagTargetResolve && diagnosticsReceived.size >= diagTarget) {
170
+ const resolve = diagTargetResolve;
171
+ diagTargetResolve = null;
172
+ resolve();
173
+ }
174
+ }
175
+ // Tailwind project initialized
176
+ if (msg.method === "@/tailwindCSS/projectInitialized") {
177
+ projectReady = true;
178
+ if (projectReadyResolve) {
179
+ const resolve = projectReadyResolve;
180
+ projectReadyResolve = null;
181
+ resolve();
182
+ }
183
+ }
184
+ }
185
+ }
186
+ // ---------------------------------------------------------------------------
187
+ // Server lifecycle
188
+ // ---------------------------------------------------------------------------
189
+ function findLanguageServer(cwd) {
190
+ const local = resolve(cwd, "node_modules/.bin/tailwindcss-language-server");
191
+ return existsSync(local) ? local : "tailwindcss-language-server";
192
+ }
193
+ export function startServer(root) {
194
+ const bin = findLanguageServer(root);
195
+ server = spawn(bin, ["--stdio"], { stdio: ["pipe", "pipe", "pipe"] });
196
+ server.on("error", (err) => {
197
+ if (err.code === "ENOENT") {
198
+ console.error("\n \x1b[38;5;203m\x1b[1mERROR\x1b[0m @tailwindcss/language-server not found.\n");
199
+ console.error(" Install it: npm install -D @tailwindcss/language-server\n");
200
+ process.exit(2);
201
+ }
202
+ });
203
+ server.stdout.on("data", (chunk) => {
204
+ chunks.push(chunk);
205
+ chunksLen += chunk.length;
206
+ processMessages();
207
+ });
208
+ server.stderr.on("data", (chunk) => {
209
+ if (DEBUG)
210
+ process.stderr.write(chunk);
211
+ });
212
+ }
213
+ export function send(method, params) {
214
+ const id = ++msgId;
215
+ return new Promise((res, rej) => {
216
+ pending.set(id, { resolve: res, reject: rej });
217
+ server.stdin.write(encode({ jsonrpc: "2.0", id, method, params }));
218
+ });
219
+ }
220
+ export function notify(method, params) {
221
+ server.stdin.write(encode({ jsonrpc: "2.0", method, params }));
222
+ }
223
+ export async function shutdown() {
224
+ await send("shutdown", {}).catch(() => { });
225
+ notify("exit", {});
226
+ server.kill();
227
+ }
228
+ export function fileUri(absPath) {
229
+ return `file://${absPath}`;
230
+ }
231
+ export function langId(filePath) {
232
+ if (filePath.endsWith(".css"))
233
+ return "css";
234
+ if (filePath.endsWith(".html") || filePath.endsWith(".vue") || filePath.endsWith(".svelte"))
235
+ return "html";
236
+ if (filePath.endsWith(".jsx"))
237
+ return "javascriptreact";
238
+ return "typescriptreact";
239
+ }