@danielx/civet 0.11.7 → 0.11.9

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,1239 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // source/ts-service/index.civet
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ Snap: () => Snap,
34
+ TSHost: () => TSHost,
35
+ TSService: () => TSService,
36
+ createDiskCache: () => createDiskCache,
37
+ createInMemoryDocFactory: () => createInMemoryDocFactory,
38
+ createMemoryCache: () => createMemoryCache,
39
+ fullDiffTextChangeRange: () => fullDiffTextChangeRange,
40
+ getCanonicalFileName: () => getCanonicalFileName,
41
+ getExtensionFromPath: () => getExtensionFromPath,
42
+ getTranspiledExtensionsFromPath: () => getTranspiledExtensionsFromPath,
43
+ makeCivetPlugin: () => makeCivetPlugin,
44
+ makeHeraPlugin: () => makeHeraPlugin,
45
+ makeIncrementalTypecheckProgram: () => makeIncrementalTypecheckProgram,
46
+ remapFileName: () => remapFileName,
47
+ removeExtension: () => removeExtension
48
+ });
49
+ module.exports = __toCommonJS(index_exports);
50
+
51
+ // source/ts-service/snapshot.civet
52
+ var import_typescript = __toESM(require("typescript"));
53
+ function fullDiffTextChangeRange(oldText, newText) {
54
+ const oldTextLength = oldText.length;
55
+ const newTextLength = newText.length;
56
+ const minLength = Math.min(oldTextLength, newTextLength);
57
+ for (let start = 0; start < minLength; start++) {
58
+ if (oldText[start] !== newText[start]) {
59
+ let end = oldTextLength;
60
+ let stop = minLength - start;
61
+ for (let i = 0; i < stop; i++) {
62
+ if (oldText[oldTextLength - i - 1] !== newText[newTextLength - i - 1]) {
63
+ break;
64
+ }
65
+ end--;
66
+ }
67
+ const length = end - start;
68
+ const newLength = length + (newTextLength - oldTextLength);
69
+ return {
70
+ span: { start, length },
71
+ newLength
72
+ };
73
+ }
74
+ }
75
+ return void 0;
76
+ }
77
+ function Snap(newText) {
78
+ const changeRanges = /* @__PURE__ */ new Map();
79
+ const snapshot = {
80
+ getText: (start, end) => newText.slice(start, end),
81
+ getLength: () => newText.length,
82
+ getChangeRange(oldSnapshot) {
83
+ if (!changeRanges.has(oldSnapshot)) {
84
+ changeRanges.set(oldSnapshot, void 0);
85
+ const oldText = oldSnapshot.getText(0, oldSnapshot.getLength());
86
+ const changeRange = fullDiffTextChangeRange(oldText, newText);
87
+ if (changeRange) {
88
+ changeRanges.set(oldSnapshot, changeRange);
89
+ }
90
+ }
91
+ return changeRanges.get(oldSnapshot);
92
+ }
93
+ };
94
+ return snapshot;
95
+ }
96
+
97
+ // source/ts-service/path.civet
98
+ var import_typescript3 = __toESM(require("typescript"));
99
+ var import_node_path = __toESM(require("node:path"));
100
+
101
+ // source/ts-service/types.civet
102
+ var import_typescript2 = __toESM(require("typescript"));
103
+
104
+ // source/ts-service/path.civet
105
+ function getCanonicalFileName(fileName) {
106
+ fileName = import_node_path.default.normalize(fileName);
107
+ if (!(import_typescript3.default.sys?.useCaseSensitiveFileNames ?? true)) {
108
+ fileName = fileName.toLowerCase();
109
+ }
110
+ return fileName;
111
+ }
112
+ var lastExtension = /(?:\.(?:[^./]+))?$/;
113
+ var lastTwoExtensions = /(\.[^./]*)(\.[^./]*)$/;
114
+ function getExtensionFromPath(p) {
115
+ const match = p.match(lastExtension);
116
+ if (!match) {
117
+ return "";
118
+ }
119
+ return match[0];
120
+ }
121
+ function getTranspiledExtensionsFromPath(p) {
122
+ const match = p.match(lastTwoExtensions);
123
+ if (!match) {
124
+ return;
125
+ }
126
+ return [match[1], match[2]];
127
+ }
128
+ function removeExtension(p) {
129
+ return p.replace(/\.[^\/.]+$/, "");
130
+ }
131
+ function remapFileName(fileName, transpilers) {
132
+ const [extension, target] = getTranspiledExtensionsFromPath(fileName) ?? [];
133
+ if (!extension) {
134
+ return fileName;
135
+ }
136
+ const transpiler = transpilers.get(extension);
137
+ if (!transpiler) {
138
+ return fileName;
139
+ }
140
+ if (transpiler.target === target) {
141
+ return removeExtension(fileName);
142
+ }
143
+ return fileName;
144
+ }
145
+
146
+ // source/ts-service/host.civet
147
+ var import_node_path3 = __toESM(require("node:path"));
148
+ var import_typescript5 = __toESM(require("typescript"));
149
+ var import_typescript6 = require("typescript");
150
+
151
+ // source/ts-service/config.civet
152
+ var import_typescript4 = __toESM(require("typescript"));
153
+ var import_node_path2 = __toESM(require("node:path"));
154
+ function buildTranspilers(plugins) {
155
+ const m = /* @__PURE__ */ new Map();
156
+ for (const plugin of plugins) {
157
+ plugin.transpilers?.forEach((t) => {
158
+ return m.set(t.extension, t);
159
+ });
160
+ }
161
+ return m;
162
+ }
163
+ function mogrifyPackageJsonImports(contents, transpilers) {
164
+ let parsed;
165
+ try {
166
+ parsed = JSON.parse(contents);
167
+ } catch {
168
+ return contents;
169
+ }
170
+ let ref;
171
+ if (!((ref = parsed.imports) != null && typeof ref === "object")) {
172
+ return contents;
173
+ }
174
+ let modified = false;
175
+ function recurse(node) {
176
+ if (!(node != null && typeof node === "object")) {
177
+ return;
178
+ }
179
+ const obj = node;
180
+ for (const key in obj) {
181
+ const value = obj[key];
182
+ if (typeof value === "string") {
183
+ const ext = getExtensionFromPath(value);
184
+ let ref1;
185
+ if ((ref1 = transpilers.get(ext)) != null) {
186
+ const t = ref1;
187
+ obj[key] = value + t.target;
188
+ modified = true;
189
+ }
190
+ } else if (value) {
191
+ recurse(value);
192
+ }
193
+ }
194
+ }
195
+ recurse(parsed.imports);
196
+ if (modified) {
197
+ return JSON.stringify(parsed);
198
+ } else return contents;
199
+ }
200
+ function parseTsConfigForCivet(projectPath, transpilers, options = {}) {
201
+ const widen = options.widenIncludeFilter ?? true;
202
+ const system = options.system ?? import_typescript4.default.sys;
203
+ const extraExtensions = Array.from(transpilers.keys());
204
+ let ref2;
205
+ if (widen && extraExtensions.length > 0) {
206
+ ref2 = {
207
+ ...system,
208
+ readDirectory: function(p, extensions, excludes, includes, depth) {
209
+ const exts = extensions ? [...extensions, ...extraExtensions] : void 0;
210
+ return system.readDirectory(p, exts, excludes, includes, depth).map((f) => {
211
+ for (const ext of extraExtensions) {
212
+ if (f.endsWith(ext)) {
213
+ const t = transpilers.get(ext);
214
+ if (t) {
215
+ return f + t.target;
216
+ }
217
+ }
218
+ }
219
+ return f;
220
+ });
221
+ }
222
+ };
223
+ } else ref2 = system;
224
+ const configSys = ref2;
225
+ const tsConfigPath = import_node_path2.default.join(projectPath, "tsconfig.json");
226
+ const config = options.tsConfig ?? import_typescript4.default.readConfigFile(tsConfigPath, system.readFile).config;
227
+ const parsed = import_typescript4.default.parseJsonConfigFileContent(
228
+ config,
229
+ configSys,
230
+ projectPath,
231
+ {},
232
+ tsConfigPath,
233
+ void 0
234
+ );
235
+ parsed.options.allowNonTsExtensions ??= true;
236
+ parsed.options.jsx ??= import_typescript4.default.JsxEmit.Preserve;
237
+ parsed.options.rootDir ??= projectPath;
238
+ return parsed;
239
+ }
240
+
241
+ // source/ts-service/host.civet
242
+ var import_node_assert = __toESM(require("node:assert"));
243
+ var { isExternalModuleNameRelative } = import_typescript5.default;
244
+ function TSHost(compilationSettings, initialFileNames, baseHost, transpilers, docFactory, _logger = console, libDir) {
245
+ const { rootDir } = compilationSettings;
246
+ (0, import_node_assert.default)(rootDir, "TSHost requires a rootDir in compilationSettings");
247
+ const scriptFileNames = /* @__PURE__ */ new Map();
248
+ for (const fileName of initialFileNames) {
249
+ const scriptFileName = getTranspiledPath(fileName);
250
+ scriptFileNames.set(getCanonicalFileName(scriptFileName), scriptFileName);
251
+ }
252
+ const fileMetaData = /* @__PURE__ */ new Map();
253
+ const pathMap = /* @__PURE__ */ new Map();
254
+ const snapshotMap = /* @__PURE__ */ new Map();
255
+ let projectVersion = 0;
256
+ const resolutionCache = import_typescript5.default.createModuleResolutionCache(rootDir, (fileName) => fileName, compilationSettings);
257
+ const baseReadFile = baseHost.readFile.bind(baseHost);
258
+ const baseFileExists = baseHost.fileExists.bind(baseHost);
259
+ const baseDirectoryExists = baseHost.directoryExists?.bind(baseHost) ?? (() => false);
260
+ let self;
261
+ return self = Object.assign({}, baseHost, {
262
+ /** Mogrifies transpilable extensions inside `package.json#imports` on read. */
263
+ readFile(filename) {
264
+ const contents = getPathSource(filename);
265
+ if (contents && import_node_path3.default.basename(filename) === "package.json") {
266
+ return mogrifyPackageJsonImports(contents, transpilers);
267
+ }
268
+ return contents;
269
+ },
270
+ /** Treats synthetic `<src>.<target>` siblings as existing whenever the source does. */
271
+ fileExists(filename) {
272
+ return pathExists(filename) || syntheticTargetExists(filename);
273
+ },
274
+ /**
275
+ * LSP bundles its own lib copies under `<dist>/lib` (libDir set);
276
+ * other consumers fall through to TS's resolved-module lookup.
277
+ */
278
+ getDefaultLibFileName(options) {
279
+ if (libDir) {
280
+ return import_node_path3.default.join(libDir, import_typescript5.default.getDefaultLibFileName(options));
281
+ }
282
+ return baseHost.getDefaultLibFileName(options);
283
+ },
284
+ getDefaultLibLocation() {
285
+ if (libDir) {
286
+ return libDir;
287
+ }
288
+ return baseHost.getDefaultLibLocation?.() ?? import_node_path3.default.dirname(baseHost.getDefaultLibFileName(compilationSettings));
289
+ },
290
+ getModuleResolutionCache() {
291
+ return resolutionCache;
292
+ },
293
+ /**
294
+ * Defer to TS's standard resolver first; fall back to our own walk
295
+ * (paths / baseUrl / relative) for transpilable extensions TS doesn't
296
+ * know about. Requires `allowNonTsExtensions`; matches resolve to a
297
+ * synthetic `<src>.<target>` so subsequent `getScriptSnapshot` calls
298
+ * hit the transpiler.
299
+ */
300
+ resolveModuleNames(moduleNames, containingFile, _reusedNames, _redirectedReference, compilerOptions, _containingSourceFile) {
301
+ return moduleNames.map((name) => {
302
+ const { resolvedModule } = import_typescript5.default.resolveModuleName(name, containingFile, compilerOptions, self, resolutionCache);
303
+ if (resolvedModule) {
304
+ return resolvedModule;
305
+ }
306
+ const extension = getExtensionFromPath(name);
307
+ let transpiler = transpilers.get(extension);
308
+ if (transpiler || !extension) {
309
+ const exists = transpiler ? pathExists : baseDirectoryExists;
310
+ const resolvedModule2 = (resolved2) => {
311
+ if (!transpiler) {
312
+ for (const [_, t] of transpilers) {
313
+ const index = import_node_path3.default.join(resolved2, "index" + t.extension);
314
+ if (pathExists(index)) {
315
+ transpiler = t;
316
+ resolved2 = index;
317
+ break;
318
+ }
319
+ }
320
+ if (!transpiler) {
321
+ return;
322
+ }
323
+ }
324
+ const { target } = transpiler;
325
+ return {
326
+ resolvedFileName: resolved2 + target,
327
+ extension: target,
328
+ isExternalLibraryImport: false
329
+ };
330
+ };
331
+ const { paths, pathsBasePath } = compilationSettings;
332
+ const baseUrl = compilationSettings.baseUrl;
333
+ if (!isExternalModuleNameRelative(name)) {
334
+ if (paths) {
335
+ const pathsBase = baseUrl ?? pathsBasePath;
336
+ let best = "";
337
+ let bestPrefix = "";
338
+ for (const [pattern, replacements] of Object.entries(paths)) {
339
+ if (pattern.endsWith("*")) {
340
+ const prefix = pattern.slice(0, -1);
341
+ if (name.startsWith(prefix)) {
342
+ for (const replacement of replacements) {
343
+ const resolved2 = import_node_path3.default.resolve(
344
+ pathsBase,
345
+ replacement.replace("*", name.slice(prefix.length))
346
+ );
347
+ if (exists(resolved2) && prefix.length > bestPrefix.length) {
348
+ best = resolved2;
349
+ bestPrefix = prefix;
350
+ }
351
+ }
352
+ }
353
+ } else if (name === pattern) {
354
+ for (const replacement of replacements) {
355
+ const resolved2 = import_node_path3.default.resolve(pathsBase, replacement);
356
+ if (exists(resolved2) && pattern.length > bestPrefix.length) {
357
+ best = resolved2;
358
+ bestPrefix = pattern;
359
+ }
360
+ }
361
+ }
362
+ }
363
+ if (best) {
364
+ return resolvedModule2(best);
365
+ }
366
+ }
367
+ if (baseUrl) {
368
+ const resolved2 = import_node_path3.default.resolve(baseUrl, name);
369
+ if (exists(resolved2)) {
370
+ return resolvedModule2(resolved2);
371
+ }
372
+ }
373
+ } else {
374
+ }
375
+ const resolved = import_node_path3.default.resolve(import_node_path3.default.dirname(containingFile), name);
376
+ if (exists(resolved)) {
377
+ return resolvedModule2(resolved);
378
+ }
379
+ }
380
+ return void 0;
381
+ });
382
+ },
383
+ resolveModuleNameLiterals(literals, containingFile, _redirectedReference, compilerOptions) {
384
+ return literals.map((literal) => {
385
+ const name = literal.text;
386
+ for (const [ext, t] of transpilers) {
387
+ if (name.endsWith(ext)) {
388
+ const resolved = import_node_path3.default.resolve(import_node_path3.default.dirname(containingFile), name);
389
+ if (pathExists(resolved)) {
390
+ return {
391
+ resolvedModule: {
392
+ resolvedFileName: resolved + t.target,
393
+ extension: t.target,
394
+ isExternalLibraryImport: false
395
+ }
396
+ };
397
+ }
398
+ }
399
+ }
400
+ if (!getExtensionFromPath(name)) {
401
+ const resolved = import_node_path3.default.resolve(import_node_path3.default.dirname(containingFile), name);
402
+ if (baseDirectoryExists(resolved)) {
403
+ for (const [_, t] of transpilers) {
404
+ const index = import_node_path3.default.join(resolved, "index" + t.extension);
405
+ if (pathExists(index)) {
406
+ return {
407
+ resolvedModule: {
408
+ resolvedFileName: index + t.target,
409
+ extension: t.target,
410
+ isExternalLibraryImport: false
411
+ }
412
+ };
413
+ }
414
+ }
415
+ }
416
+ }
417
+ return { resolvedModule: import_typescript5.default.resolveModuleName(name, containingFile, compilerOptions, self, resolutionCache).resolvedModule };
418
+ });
419
+ },
420
+ addOrUpdateDocument(doc) {
421
+ const rawPath = import_node_path3.default.normalize(docFactory.uriToPath(doc.uri));
422
+ const p = getCanonicalFileName(rawPath);
423
+ snapshotMap.delete(p);
424
+ projectVersion++;
425
+ const extension = getExtensionFromPath(p);
426
+ const transpiler = transpilers.get(extension);
427
+ if (transpiler) {
428
+ const { target } = transpiler;
429
+ const transpiledPath = p + target;
430
+ const displayTranspiledPath = rawPath + target;
431
+ let transpiledDoc = pathMap.get(transpiledPath);
432
+ if (!transpiledDoc) {
433
+ initTranspiledDoc(displayTranspiledPath);
434
+ }
435
+ snapshotMap.delete(transpiledPath);
436
+ pathMap.set(p, doc);
437
+ return;
438
+ }
439
+ scriptFileNames.set(p, rawPath);
440
+ pathMap.set(p, doc);
441
+ },
442
+ addScriptFileName(p) {
443
+ const target = getTranspiledPath(p);
444
+ const canonical = getCanonicalFileName(target);
445
+ if (scriptFileNames.has(canonical)) {
446
+ return;
447
+ }
448
+ scriptFileNames.set(canonical, target);
449
+ projectVersion++;
450
+ },
451
+ closeDocument(rawPath) {
452
+ const canonical = getCanonicalFileName(rawPath);
453
+ const transpiledPath = getCanonicalTranspiledPath(rawPath);
454
+ pathMap.delete(canonical);
455
+ snapshotMap.delete(canonical);
456
+ fileMetaData.delete(canonical);
457
+ if (transpiledPath !== canonical) {
458
+ pathMap.delete(transpiledPath);
459
+ snapshotMap.delete(transpiledPath);
460
+ }
461
+ projectVersion++;
462
+ },
463
+ removeDocument(rawPath) {
464
+ const canonical = getCanonicalFileName(rawPath);
465
+ const transpiledPath = getCanonicalTranspiledPath(rawPath);
466
+ pathMap.delete(canonical);
467
+ snapshotMap.delete(canonical);
468
+ fileMetaData.delete(canonical);
469
+ scriptFileNames.delete(canonical);
470
+ if (transpiledPath !== canonical) {
471
+ pathMap.delete(transpiledPath);
472
+ snapshotMap.delete(transpiledPath);
473
+ scriptFileNames.delete(transpiledPath);
474
+ }
475
+ projectVersion++;
476
+ },
477
+ getMeta(p) {
478
+ p = getCanonicalFileName(p);
479
+ getOrCreatePathSnapshot(getCanonicalTranspiledPath(p));
480
+ return fileMetaData.get(p);
481
+ },
482
+ getProjectVersion() {
483
+ return projectVersion.toString();
484
+ },
485
+ getCompilationSettings() {
486
+ return compilationSettings;
487
+ },
488
+ // TS passes forward-slash paths on every OS; both methods
489
+ // normalize through getCanonicalFileName before lookup.
490
+ getScriptSnapshot(p) {
491
+ return getOrCreatePathSnapshot(getCanonicalFileName(p));
492
+ },
493
+ getScriptVersion(p) {
494
+ return pathMap.get(getCanonicalFileName(p))?.version.toString() || "0";
495
+ },
496
+ getScriptFileNames() {
497
+ return Array.from(scriptFileNames.values());
498
+ },
499
+ // CompilerHost requires writeFile, but our consumers always pass an
500
+ // explicit writeFile to program.emit() / builder.emit(), so this is
501
+ // unreachable — keep as a no-op to satisfy the interface.
502
+ writeFile(_fileName, _content) {
503
+ return;
504
+ }
505
+ });
506
+ function syntheticTargetExists(filename) {
507
+ for (const [ext, t] of transpilers) {
508
+ if (filename.endsWith(t.target)) {
509
+ const source = filename.slice(0, -t.target.length);
510
+ if (source.endsWith(ext) && pathExists(source)) {
511
+ return true;
512
+ }
513
+ }
514
+ }
515
+ return false;
516
+ }
517
+ function pathExists(p) {
518
+ return pathMap.has(getCanonicalFileName(p)) || baseFileExists(p);
519
+ }
520
+ function getPathSource(p) {
521
+ p = getCanonicalFileName(p);
522
+ const doc = pathMap.get(p);
523
+ if (doc) {
524
+ return doc.getText();
525
+ }
526
+ if (baseFileExists(p)) {
527
+ return baseReadFile(p);
528
+ }
529
+ return void 0;
530
+ }
531
+ function getTranspiledPath(p) {
532
+ p = import_node_path3.default.normalize(p);
533
+ const extension = getExtensionFromPath(p);
534
+ const transpiler = transpilers.get(extension);
535
+ if (transpiler) {
536
+ return p + transpiler.target;
537
+ }
538
+ return p;
539
+ }
540
+ function getCanonicalTranspiledPath(p) {
541
+ return getCanonicalFileName(getTranspiledPath(p));
542
+ }
543
+ function getOrCreatePathSnapshot(p) {
544
+ const rawPath = import_node_path3.default.normalize(p);
545
+ p = getCanonicalFileName(rawPath);
546
+ let snapshot = snapshotMap.get(p);
547
+ if (snapshot) {
548
+ return snapshot;
549
+ }
550
+ let transpiler;
551
+ const exts = getTranspiledExtensionsFromPath(p);
552
+ if (exts && (transpiler = transpilers.get(exts[0]))) {
553
+ const sourcePath = removeExtension(p);
554
+ const sourceDoc = pathMap.get(sourcePath);
555
+ let transpiledDoc = pathMap.get(p);
556
+ if (!transpiledDoc) {
557
+ transpiledDoc = initTranspiledDoc(rawPath);
558
+ }
559
+ let source;
560
+ let sourceDocVersion = 0;
561
+ if (!sourceDoc) {
562
+ source = getPathSource(sourcePath);
563
+ } else {
564
+ source = sourceDoc.getText();
565
+ sourceDocVersion = sourceDoc.version;
566
+ }
567
+ if (source && sourceDocVersion > transpiledDoc.version) {
568
+ const transpiledCode = doTranspileAndUpdateMeta(transpiledDoc, sourceDocVersion, transpiler, sourcePath, source);
569
+ if (transpiledCode != null) {
570
+ snapshot = Snap(transpiledCode);
571
+ }
572
+ }
573
+ if (!snapshot) {
574
+ snapshot = Snap(transpiledDoc.getText());
575
+ }
576
+ snapshotMap.set(p, snapshot);
577
+ return snapshot;
578
+ }
579
+ snapshot = Snap(getPathSource(p) ?? "");
580
+ snapshotMap.set(p, snapshot);
581
+ return snapshot;
582
+ }
583
+ function createOrUpdateMeta(p, update) {
584
+ p = getCanonicalFileName(p);
585
+ let meta = fileMetaData.get(p);
586
+ if (!meta) {
587
+ return fileMetaData.set(p, update);
588
+ } else {
589
+ return Object.assign(meta, update);
590
+ }
591
+ }
592
+ function doTranspileAndUpdateMeta(transpiledDoc, version, transpiler, sourcePath, sourceCode) {
593
+ let result;
594
+ try {
595
+ result = transpiler.compile(sourcePath, sourceCode);
596
+ } catch (e) {
597
+ createOrUpdateMeta(sourcePath, {
598
+ transpiledDoc,
599
+ sourcemapLines: void 0,
600
+ commentRanges: void 0,
601
+ parseErrors: [e],
602
+ fatal: true
603
+ });
604
+ return;
605
+ }
606
+ if (result instanceof Promise) {
607
+ return;
608
+ }
609
+ if (!result) {
610
+ return;
611
+ }
612
+ const { code: transpiledCode, sourceMap, commentRanges, errors } = result;
613
+ let sourcemapLines = sourceMap?.lines;
614
+ sourcemapLines ??= sourceMap?.data?.lines;
615
+ createOrUpdateMeta(sourcePath, {
616
+ transpiledDoc,
617
+ sourcemapLines,
618
+ commentRanges,
619
+ parseErrors: errors,
620
+ fatal: false
621
+ });
622
+ docFactory.update(transpiledDoc, transpiledCode, version);
623
+ return transpiledCode;
624
+ }
625
+ function initTranspiledDoc(p) {
626
+ const scriptPath = import_node_path3.default.normalize(p);
627
+ p = getCanonicalFileName(scriptPath);
628
+ const uri = docFactory.pathToUri(scriptPath);
629
+ const transpiledDoc = docFactory.create(uri, "none", -1, "");
630
+ pathMap.set(p, transpiledDoc);
631
+ scriptFileNames.set(p, scriptPath);
632
+ return transpiledDoc;
633
+ }
634
+ }
635
+
636
+ // source/ts-service/service.civet
637
+ var import_node_path4 = __toESM(require("node:path"));
638
+ var import_typescript7 = __toESM(require("typescript"));
639
+ var import_typescript8 = require("typescript");
640
+ var {
641
+ createCompilerHost,
642
+ createLanguageService
643
+ } = import_typescript7.default;
644
+ function TSService(projectPath, options) {
645
+ const { plugins = [], docFactory, libDir, discoverProjectFiles = true, extraCompilerOptions } = options;
646
+ const system = options.system ?? import_typescript7.default.sys;
647
+ const logger = options.logger ?? console;
648
+ const transpilers = buildTranspilers(plugins);
649
+ function registerPlugin(plugin) {
650
+ plugin.transpilers?.forEach((t) => {
651
+ return transpilers.set(t.extension, t);
652
+ });
653
+ }
654
+ const parsedConfig = parseTsConfigForCivet(projectPath, transpilers, {
655
+ tsConfig: options.tsConfig,
656
+ widenIncludeFilter: discoverProjectFiles,
657
+ system
658
+ });
659
+ let ref;
660
+ if (extraCompilerOptions) {
661
+ ref = { ...parsedConfig.options, ...extraCompilerOptions };
662
+ } else {
663
+ ref = parsedConfig.options;
664
+ }
665
+ ;
666
+ const hostOptions = ref;
667
+ const baseHost = createBaseHost(hostOptions, system);
668
+ const host = TSHost(hostOptions, parsedConfig.fileNames, baseHost, transpilers, docFactory, logger, libDir);
669
+ const service = createLanguageService(host);
670
+ const loadPlugins = async function() {
671
+ const civetFolder = import_node_path4.default.join(projectPath, "./.civet/");
672
+ let civetFiles;
673
+ try {
674
+ civetFiles = system.readDirectory(civetFolder);
675
+ } catch (e) {
676
+ logger.info(`No .civet plugin folder at ${civetFolder} (${e.message})`);
677
+ return;
678
+ }
679
+ const pluginFiles = civetFiles.filter((file) => file.endsWith("plugin.mjs"));
680
+ for (const filePath of pluginFiles) {
681
+ const pluginUri = docFactory.pathToUri(filePath);
682
+ logger.info("Loading plugin " + pluginUri);
683
+ try {
684
+ const { default: plugin } = await import(
685
+ /* @vite-ignore */
686
+ pluginUri
687
+ );
688
+ logger.info("Loaded plugin " + plugin);
689
+ registerPlugin(plugin);
690
+ } catch (e) {
691
+ logger.error("Error loading plugin " + pluginUri + " " + e);
692
+ }
693
+ }
694
+ return;
695
+ };
696
+ return Object.assign({}, service, {
697
+ host,
698
+ /** `foo.civet.tsx` → `foo.civet`; passthrough for non-transpiled files. */
699
+ getSourceFileName(fileName) {
700
+ return getCanonicalFileName(remapFileName(fileName, transpilers));
701
+ },
702
+ registerPlugin,
703
+ loadPlugins
704
+ });
705
+ }
706
+ function createBaseHost(options, system) {
707
+ if (system === import_typescript7.default.sys) {
708
+ return createCompilerHost(options);
709
+ }
710
+ const getCanonicalFileName2 = (fileName) => {
711
+ if (system.useCaseSensitiveFileNames) {
712
+ return fileName;
713
+ } else return fileName.toLowerCase();
714
+ };
715
+ return {
716
+ getSourceFile(fileName, languageVersion) {
717
+ const sourceText = system.readFile(fileName);
718
+ if (!(sourceText != null)) {
719
+ return;
720
+ }
721
+ return import_typescript7.default.createSourceFile(fileName, sourceText, languageVersion);
722
+ },
723
+ getDefaultLibFileName(options2) {
724
+ return import_node_path4.default.join("/typescript/lib", import_typescript7.default.getDefaultLibFileName(options2));
725
+ },
726
+ writeFile(fileName, content) {
727
+ return system.writeFile?.(fileName, content);
728
+ },
729
+ getCurrentDirectory() {
730
+ return system.getCurrentDirectory();
731
+ },
732
+ getDirectories(path7) {
733
+ return system.getDirectories?.(path7) ?? [];
734
+ },
735
+ fileExists(fileName) {
736
+ return system.fileExists(fileName);
737
+ },
738
+ readFile(fileName) {
739
+ return system.readFile(fileName);
740
+ },
741
+ useCaseSensitiveFileNames() {
742
+ return system.useCaseSensitiveFileNames;
743
+ },
744
+ getCanonicalFileName: getCanonicalFileName2,
745
+ getNewLine() {
746
+ return system.newLine;
747
+ },
748
+ directoryExists(path7) {
749
+ return system.directoryExists?.(path7) ?? false;
750
+ },
751
+ readDirectory(path7, extensions, excludes, includes, depth) {
752
+ return system.readDirectory(path7, extensions, excludes, includes, depth);
753
+ },
754
+ realpath(path7) {
755
+ return system.realpath ? system.realpath(path7) : path7;
756
+ }
757
+ };
758
+ }
759
+
760
+ // source/ts-service/doc.civet
761
+ var import_node_url = require("node:url");
762
+ var InMemoryDoc = class {
763
+ uri;
764
+ version;
765
+ text;
766
+ constructor(uri, version, text) {
767
+ this.uri = uri;
768
+ this.version = version;
769
+ this.text = text;
770
+ }
771
+ getText() {
772
+ return this.text;
773
+ }
774
+ setText(t) {
775
+ this.text = t;
776
+ }
777
+ };
778
+ function createInMemoryDocFactory() {
779
+ return {
780
+ create: (uri, _languageId, version, text) => {
781
+ return new InMemoryDoc(uri, version, text);
782
+ },
783
+ update: (doc, text, version) => {
784
+ doc.setText(text);
785
+ return doc.version = version;
786
+ },
787
+ uriToPath: (uri) => (0, import_node_url.fileURLToPath)(uri),
788
+ pathToUri: (p) => (0, import_node_url.pathToFileURL)(p).toString()
789
+ };
790
+ }
791
+
792
+ // source/ts-service/plugins/civet.civet
793
+ var import_civet = require("@danielx/civet");
794
+ var import_civet2 = __toESM(require("@danielx/civet"));
795
+ var import_package = __toESM(require("@danielx/civet/package.json"));
796
+ var import_typescript9 = require("typescript");
797
+
798
+ // source/cache.civet
799
+ var crypto = __toESM(require("node:crypto"));
800
+ var fs = __toESM(require("node:fs"));
801
+ var path5 = __toESM(require("node:path"));
802
+ function hashParts(parts) {
803
+ const hash = crypto.createHash("sha1");
804
+ for (const part of parts) {
805
+ hash.update(part).update("\0");
806
+ }
807
+ return hash.digest("hex");
808
+ }
809
+ function stableStringify(value) {
810
+ return JSON.stringify(value, (_key, val) => {
811
+ if (typeof val === "function") {
812
+ return void 0;
813
+ }
814
+ if (val && typeof val === "object" && !Array.isArray(val)) {
815
+ const sorted = {};
816
+ for (const key of Object.keys(val).sort()) {
817
+ sorted[key] = val[key];
818
+ }
819
+ return sorted;
820
+ }
821
+ return val;
822
+ });
823
+ }
824
+ function makeCacheKey(input) {
825
+ const resolved = path5.resolve(input.sourcePath).replace(/\\/g, "/");
826
+ return hashParts([
827
+ input.source,
828
+ input.compilerName,
829
+ input.compilerVersion,
830
+ input.civetVersion ?? "",
831
+ input.civetMtime ?? "",
832
+ resolved,
833
+ stableStringify(input.options ?? {})
834
+ ]);
835
+ }
836
+ function createMemoryCache() {
837
+ const store = /* @__PURE__ */ new Map();
838
+ return {
839
+ get(key) {
840
+ return store.get(key);
841
+ },
842
+ set(key, value) {
843
+ store.set(key, value);
844
+ return;
845
+ }
846
+ };
847
+ }
848
+ function createDiskCache(dir) {
849
+ try {
850
+ fs.mkdirSync(dir, { recursive: true });
851
+ } catch {
852
+ }
853
+ return {
854
+ get(key) {
855
+ const target = path5.join(dir, key);
856
+ try {
857
+ const content = fs.readFileSync(target, "utf8");
858
+ try {
859
+ const now = /* @__PURE__ */ new Date();
860
+ fs.utimesSync(target, now, now);
861
+ } catch {
862
+ }
863
+ return content;
864
+ } catch {
865
+ return void 0;
866
+ }
867
+ },
868
+ set(key, value) {
869
+ const target = path5.join(dir, key);
870
+ try {
871
+ const tmp = `${target}.tmp.${process.pid}`;
872
+ fs.writeFileSync(tmp, value);
873
+ return fs.renameSync(tmp, target);
874
+ } catch {
875
+ return;
876
+ }
877
+ }
878
+ };
879
+ }
880
+
881
+ // source/ts-service/plugins/civet.civet
882
+ function makeCivetPlugin(options = {}) {
883
+ const Civet = options.Civet ?? import_civet2.default;
884
+ const CivetLib = options.CivetLib ?? import_civet.lib;
885
+ const CivetVersion = options.CivetVersion ?? import_package.default.version;
886
+ const civetConfig = options.config ?? {};
887
+ const cache = options.cache;
888
+ function transpileCivet(p, source) {
889
+ const errors = [];
890
+ const options2 = {
891
+ ...civetConfig,
892
+ filename: p,
893
+ errors,
894
+ sync: true,
895
+ parseOptions: {
896
+ ...civetConfig.parseOptions,
897
+ comptime: false
898
+ }
899
+ };
900
+ const [major, minor, patch] = CivetVersion.split(".").map(Number);
901
+ if (major === 0 && (minor < 9 || minor === 9 && patch < 4)) {
902
+ const result = Civet.compile(source, { ...options2, sourceMap: true });
903
+ return { ...result, errors };
904
+ }
905
+ let ref;
906
+ if (cache) {
907
+ ref = makeCacheKey({
908
+ source,
909
+ sourcePath: p,
910
+ compilerName: "civet",
911
+ compilerVersion: CivetVersion,
912
+ options: civetConfig
913
+ });
914
+ } else ref = void 0;
915
+ const cacheKey = ref;
916
+ if (cacheKey) {
917
+ const hit = cache.get(cacheKey);
918
+ if (hit) {
919
+ try {
920
+ const parsed = JSON.parse(hit);
921
+ const result = {
922
+ code: parsed.code,
923
+ sourceMap: { lines: parsed.lines },
924
+ errors
925
+ };
926
+ if (parsed.commentRanges) {
927
+ result.commentRanges = parsed.commentRanges;
928
+ }
929
+ return result;
930
+ } catch {
931
+ }
932
+ }
933
+ }
934
+ options2.ast = true;
935
+ const ast = Civet.compile(source, options2);
936
+ const sourceMap = new Civet.SourceMap(source, p);
937
+ const code = Civet.generate(ast, {
938
+ ...options2,
939
+ sourceMap
940
+ });
941
+ const commentRanges = collectCommentRanges(ast);
942
+ if (cacheKey && errors.length === 0) {
943
+ const lines = sourceMap.lines ?? sourceMap.data?.lines;
944
+ cache.set(cacheKey, JSON.stringify({ code, lines, commentRanges }));
945
+ }
946
+ return {
947
+ code,
948
+ sourceMap,
949
+ commentRanges,
950
+ errors
951
+ };
952
+ }
953
+ function collectCommentRanges(ast) {
954
+ const comments = CivetLib.gatherRecursiveAll(
955
+ ast,
956
+ (node) => {
957
+ return node?.type === "Comment" && node.$loc?.length > 0;
958
+ }
959
+ );
960
+ return comments.map((comment) => comment.$loc);
961
+ }
962
+ return {
963
+ transpilers: [{
964
+ extension: ".civet",
965
+ target: ".tsx",
966
+ compile: transpileCivet
967
+ }]
968
+ };
969
+ }
970
+
971
+ // source/ts-service/plugins/hera.civet
972
+ var import_civet3 = require("@danielx/civet");
973
+ var import_civet4 = __toESM(require("@danielx/civet"));
974
+ var import_package2 = __toESM(require("@danielx/civet/package.json"));
975
+ var import_node_module = require("node:module");
976
+ var import_typescript10 = require("typescript");
977
+ var heraRequire = (0, import_node_module.createRequire)(
978
+ /* c8 ignore start -- one branch fires per build target; tests cover only one */
979
+ typeof __filename !== "undefined" ? __filename : ""
980
+ /* c8 ignore stop */
981
+ );
982
+ function makeHeraPlugin(options = {}) {
983
+ const Civet = options.Civet ?? import_civet4.default;
984
+ const CivetVersion = options.CivetVersion ?? import_package2.default.version;
985
+ const civetConfig = options.config ?? {};
986
+ const cache = options.cache;
987
+ let resolvedHera;
988
+ let resolvedHeraVersion;
989
+ function getHera() {
990
+ if (resolvedHera) {
991
+ return resolvedHera;
992
+ }
993
+ if (options.Hera) {
994
+ resolvedHera = options.Hera;
995
+ return resolvedHera;
996
+ }
997
+ let mod;
998
+ try {
999
+ mod = heraRequire("@danielx/hera");
1000
+ } catch {
1001
+ throw new Error("@danielx/hera is not installed; install it as a (peer) dependency to type-check .hera files, or pass HeraPluginOptions.Hera explicitly.");
1002
+ }
1003
+ resolvedHera = { compile: mod.compile };
1004
+ return resolvedHera;
1005
+ }
1006
+ function getHeraVersion() {
1007
+ if (resolvedHeraVersion) {
1008
+ return resolvedHeraVersion;
1009
+ }
1010
+ if (options.HeraVersion) {
1011
+ resolvedHeraVersion = options.HeraVersion;
1012
+ return resolvedHeraVersion;
1013
+ }
1014
+ try {
1015
+ const pkg = heraRequire("@danielx/hera/package.json");
1016
+ resolvedHeraVersion = pkg.version;
1017
+ } catch {
1018
+ resolvedHeraVersion = "unknown";
1019
+ }
1020
+ return resolvedHeraVersion;
1021
+ }
1022
+ const heraOptions = {
1023
+ module: true,
1024
+ sourceMap: true,
1025
+ language: "civet"
1026
+ };
1027
+ function transpileHera(p, source) {
1028
+ const errors = [];
1029
+ let ref;
1030
+ if (cache) {
1031
+ ref = makeCacheKey({
1032
+ source,
1033
+ sourcePath: p,
1034
+ compilerName: "hera",
1035
+ compilerVersion: getHeraVersion(),
1036
+ civetVersion: CivetVersion,
1037
+ options: { heraOptions, civetConfig }
1038
+ });
1039
+ } else ref = void 0;
1040
+ const cacheKey = ref;
1041
+ if (cacheKey) {
1042
+ const hit = cache.get(cacheKey);
1043
+ if (hit) {
1044
+ try {
1045
+ const { code, lines } = JSON.parse(hit);
1046
+ return {
1047
+ code,
1048
+ sourceMap: { lines },
1049
+ errors
1050
+ };
1051
+ } catch {
1052
+ }
1053
+ }
1054
+ }
1055
+ try {
1056
+ const heraResult = getHera().compile(source, { ...heraOptions, filename: p });
1057
+ const civetOptions = {
1058
+ ...civetConfig,
1059
+ filename: p,
1060
+ js: false,
1061
+ sync: true,
1062
+ sourceMap: true,
1063
+ upstreamSourceMap: heraResult.sourceMap,
1064
+ parseOptions: {
1065
+ ...civetConfig.parseOptions,
1066
+ comptime: false
1067
+ }
1068
+ };
1069
+ const civetResult = Civet.compile(heraResult.code, civetOptions);
1070
+ if (cacheKey) {
1071
+ const sm = civetResult.sourceMap;
1072
+ const lines = sm?.lines ?? sm?.data?.lines;
1073
+ cache.set(cacheKey, JSON.stringify({ code: civetResult.code, lines }));
1074
+ }
1075
+ return {
1076
+ code: civetResult.code,
1077
+ sourceMap: civetResult.sourceMap,
1078
+ errors
1079
+ };
1080
+ } catch (e) {
1081
+ errors.push(e);
1082
+ return { code: "", errors };
1083
+ }
1084
+ }
1085
+ return {
1086
+ transpilers: [{
1087
+ extension: ".hera",
1088
+ target: ".tsx",
1089
+ compile: transpileHera
1090
+ }]
1091
+ };
1092
+ }
1093
+
1094
+ // source/ts-service/typecheck.civet
1095
+ var import_typescript11 = __toESM(require("typescript"));
1096
+ var fs2 = __toESM(require("fs"));
1097
+ var path6 = __toESM(require("path"));
1098
+ function makeIncrementalTypecheckProgram(projectPath, options) {
1099
+ const transpilers = buildTranspilers(options.plugins);
1100
+ const extraExtensions = Array.from(transpilers.keys());
1101
+ const parsed = parseTsConfigForCivet(projectPath, transpilers, { tsConfig: options.tsConfig });
1102
+ const compilerOptions = {
1103
+ ...parsed.options,
1104
+ ...options.extraCompilerOptions
1105
+ };
1106
+ compilerOptions.jsx ??= import_typescript11.default.JsxEmit.Preserve;
1107
+ const baseHost = import_typescript11.default.createIncrementalCompilerHost(compilerOptions);
1108
+ const fileMetaData = /* @__PURE__ */ new Map();
1109
+ const hashText = (text) => {
1110
+ return baseHost.createHash?.(text) ?? text.length.toString();
1111
+ };
1112
+ const origGetSourceFile = baseHost.getSourceFile.bind(baseHost);
1113
+ baseHost.getSourceFile = (fileName, langVersion, onError, shouldCreateNew) => {
1114
+ const exts = getTranspiledExtensionsFromPath(fileName);
1115
+ const transpiler = exts && transpilers.get(exts[0]);
1116
+ if (exts && transpiler && transpiler.target === exts[1]) {
1117
+ const sourcePath = removeExtension(fileName);
1118
+ let sourceText;
1119
+ try {
1120
+ sourceText = fs2.readFileSync(sourcePath, "utf8");
1121
+ } catch {
1122
+ return void 0;
1123
+ }
1124
+ let result;
1125
+ try {
1126
+ result = transpiler.compile(sourcePath, sourceText);
1127
+ } catch (e) {
1128
+ fileMetaData.set(getCanonicalFileName(sourcePath), {
1129
+ sourcemapLines: void 0,
1130
+ transpiledDoc: void 0,
1131
+ commentRanges: void 0,
1132
+ parseErrors: [e],
1133
+ fatal: true
1134
+ });
1135
+ return void 0;
1136
+ }
1137
+ if (result instanceof Promise) {
1138
+ return void 0;
1139
+ }
1140
+ if (!(result && result.code)) {
1141
+ return void 0;
1142
+ }
1143
+ const sourcemapLines = result.sourceMap?.lines ?? result.sourceMap?.data?.lines;
1144
+ fileMetaData.set(getCanonicalFileName(sourcePath), {
1145
+ sourcemapLines,
1146
+ transpiledDoc: void 0,
1147
+ commentRanges: result.commentRanges,
1148
+ parseErrors: result.errors,
1149
+ fatal: false
1150
+ });
1151
+ const sf2 = import_typescript11.default.createSourceFile(fileName, result.code, langVersion, true);
1152
+ sf2.version = hashText(result.code);
1153
+ return sf2;
1154
+ }
1155
+ const sf = origGetSourceFile(fileName, langVersion, onError, shouldCreateNew);
1156
+ if (sf && sf.version === void 0) {
1157
+ sf.version = hashText(sf.text);
1158
+ }
1159
+ return sf;
1160
+ };
1161
+ const origFileExists = baseHost.fileExists.bind(baseHost);
1162
+ baseHost.fileExists = (fileName) => {
1163
+ const exts = getTranspiledExtensionsFromPath(fileName);
1164
+ if (exts) {
1165
+ const transpiler = transpilers.get(exts[0]);
1166
+ if (transpiler && transpiler.target === exts[1]) {
1167
+ return origFileExists(removeExtension(fileName));
1168
+ }
1169
+ }
1170
+ return origFileExists(fileName);
1171
+ };
1172
+ const origReadFile = baseHost.readFile.bind(baseHost);
1173
+ baseHost.readFile = (fileName) => {
1174
+ const contents = origReadFile(fileName);
1175
+ if (contents && path6.basename(fileName) === "package.json") {
1176
+ return mogrifyPackageJsonImports(contents, transpilers);
1177
+ }
1178
+ return contents;
1179
+ };
1180
+ baseHost.resolveModuleNameLiterals = (literals, containingFile, _redirected, opts) => {
1181
+ return literals.map((lit) => {
1182
+ const name = lit.text;
1183
+ for (const ext of extraExtensions) {
1184
+ if (name.endsWith(ext)) {
1185
+ const t = transpilers.get(ext);
1186
+ const containingDir = path6.dirname(containingFile);
1187
+ const resolved = path6.resolve(containingDir, name);
1188
+ if (origFileExists(resolved)) {
1189
+ return {
1190
+ resolvedModule: {
1191
+ resolvedFileName: resolved + t.target,
1192
+ extension: t.target,
1193
+ isExternalLibraryImport: false
1194
+ }
1195
+ };
1196
+ }
1197
+ }
1198
+ }
1199
+ return { resolvedModule: import_typescript11.default.resolveModuleName(name, containingFile, opts, baseHost).resolvedModule };
1200
+ });
1201
+ };
1202
+ const programOptions = {
1203
+ rootNames: parsed.fileNames,
1204
+ options: compilerOptions,
1205
+ host: baseHost,
1206
+ configFileParsingDiagnostics: import_typescript11.default.getConfigFileParsingDiagnostics(parsed)
1207
+ };
1208
+ if (parsed.projectReferences) {
1209
+ programOptions.projectReferences = parsed.projectReferences;
1210
+ }
1211
+ const builder = import_typescript11.default.createIncrementalProgram(programOptions);
1212
+ return {
1213
+ builder,
1214
+ host: baseHost,
1215
+ getMeta(sourcePath) {
1216
+ return fileMetaData.get(getCanonicalFileName(sourcePath));
1217
+ },
1218
+ configErrors: parsed.errors
1219
+ };
1220
+ }
1221
+ // Annotate the CommonJS export names for ESM import in node:
1222
+ 0 && (module.exports = {
1223
+ Snap,
1224
+ TSHost,
1225
+ TSService,
1226
+ createDiskCache,
1227
+ createInMemoryDocFactory,
1228
+ createMemoryCache,
1229
+ fullDiffTextChangeRange,
1230
+ getCanonicalFileName,
1231
+ getExtensionFromPath,
1232
+ getTranspiledExtensionsFromPath,
1233
+ makeCivetPlugin,
1234
+ makeHeraPlugin,
1235
+ makeIncrementalTypecheckProgram,
1236
+ remapFileName,
1237
+ removeExtension
1238
+ });
1239
+ //# sourceMappingURL=index.js.map