@danielx/civet 0.11.6 → 0.11.8

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.
@@ -1,193 +1,16 @@
1
1
  import { createRequire as __civetCreateRequire } from 'node:module'; const require = __civetCreateRequire(import.meta.url);
2
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
- }) : x)(function(x) {
5
- if (typeof require !== "undefined") return require.apply(this, arguments);
6
- throw Error('Dynamic require of "' + x + '" is not supported');
7
- });
8
2
 
9
- // unplugin-civet:/home/runner/work/Civet/Civet/source/unplugin/unplugin.civet.jsx
3
+ // unplugin-civet:/home/runner/work/Civet/Civet/source/unplugin/unplugin.civet
10
4
  import { createUnplugin } from "unplugin";
11
5
  import civet, { decode, lib, SourceMap } from "@danielx/civet";
12
6
  import { findInDir, loadConfig } from "@danielx/civet/config";
13
7
  import {
14
- remapRange,
8
+ remapPosition,
15
9
  flattenDiagnosticMessageText
16
10
  } from "@danielx/civet/ts-diagnostic";
17
11
  import * as fs from "fs";
18
12
  import path from "path";
19
-
20
- // node_modules/.pnpm/@typescript+vfs@1.6.4_typescript@5.8.3/node_modules/@typescript/vfs/dist/vfs.esm.js
21
- function _extends() {
22
- return _extends = Object.assign ? Object.assign.bind() : function(n) {
23
- for (var e = 1; e < arguments.length; e++) {
24
- var t = arguments[e];
25
- for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
26
- }
27
- return n;
28
- }, _extends.apply(null, arguments);
29
- }
30
- var hasLocalStorage = false;
31
- try {
32
- hasLocalStorage = typeof localStorage !== "undefined";
33
- } catch (error) {
34
- }
35
- var hasProcess = typeof process !== "undefined";
36
- var shouldDebug = hasLocalStorage && typeof localStorage.getItem === "function" && /* @__PURE__ */ localStorage.getItem("DEBUG") || hasProcess && process.env.DEBUG;
37
- var debugLog = shouldDebug ? console.log : function(_message) {
38
- return "";
39
- };
40
- function notImplemented(methodName) {
41
- throw new Error("Method '" + methodName + "' is not implemented.");
42
- }
43
- function audit(name, fn) {
44
- return function() {
45
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
46
- args[_key] = arguments[_key];
47
- }
48
- var res = fn.apply(void 0, args);
49
- var smallres = typeof res === "string" ? res.slice(0, 80) + "..." : res;
50
- debugLog.apply(void 0, ["> " + name].concat(args));
51
- debugLog("< " + smallres);
52
- return res;
53
- };
54
- }
55
- var defaultCompilerOptions = function defaultCompilerOptions2(ts) {
56
- return _extends({}, ts.getDefaultCompilerOptions(), {
57
- jsx: ts.JsxEmit.React,
58
- strict: true,
59
- esModuleInterop: true,
60
- module: ts.ModuleKind.ESNext,
61
- suppressOutputPathCheck: true,
62
- skipLibCheck: true,
63
- skipDefaultLibCheck: true
64
- }, ts.versionMajorMinor && Number(ts.versionMajorMinor.split(".")[0]) >= 6 ? {
65
- ignoreDeprecations: "6.0"
66
- } : {
67
- moduleResolution: ts.ModuleResolutionKind.NodeJs
68
- });
69
- };
70
- function createFSBackedSystem(files, _projectRoot, ts, tsLibDirectory) {
71
- var root = _projectRoot + "/vfs";
72
- var path2 = requirePath();
73
- var nodeSys = ts.sys;
74
- var tsLib = tsLibDirectory != null ? tsLibDirectory : path2.dirname(__require.resolve("typescript"));
75
- return {
76
- // @ts-ignore
77
- name: "fs-vfs",
78
- root,
79
- args: [],
80
- createDirectory: function createDirectory() {
81
- return notImplemented("createDirectory");
82
- },
83
- // TODO: could make a real file tree
84
- directoryExists: audit("directoryExists", function(directory) {
85
- return Array.from(files.keys()).some(function(path3) {
86
- return path3.startsWith(directory);
87
- }) || nodeSys.directoryExists(directory);
88
- }),
89
- exit: nodeSys.exit,
90
- fileExists: audit("fileExists", function(fileName) {
91
- if (files.has(fileName)) return true;
92
- if (fileName.includes("tsconfig.json") || fileName.includes("tsconfig.json")) return false;
93
- if (fileName.startsWith("/lib")) {
94
- var tsLibName = tsLib + "/" + fileName.replace("/", "");
95
- return nodeSys.fileExists(tsLibName);
96
- }
97
- return nodeSys.fileExists(fileName);
98
- }),
99
- getCurrentDirectory: function getCurrentDirectory() {
100
- return root;
101
- },
102
- getDirectories: nodeSys.getDirectories,
103
- getExecutingFilePath: function getExecutingFilePath() {
104
- return notImplemented("getExecutingFilePath");
105
- },
106
- readDirectory: audit("readDirectory", function() {
107
- if ((arguments.length <= 0 ? void 0 : arguments[0]) === "/") {
108
- return Array.from(files.keys());
109
- } else {
110
- return nodeSys.readDirectory.apply(nodeSys, arguments);
111
- }
112
- }),
113
- readFile: audit("readFile", function(fileName) {
114
- if (files.has(fileName)) return files.get(fileName);
115
- if (fileName.startsWith("/lib")) {
116
- var tsLibName = tsLib + "/" + fileName.replace("/", "");
117
- var result = nodeSys.readFile(tsLibName);
118
- if (!result) {
119
- var libs = nodeSys.readDirectory(tsLib);
120
- throw new Error("TSVFS: A request was made for " + tsLibName + " but there wasn't a file found in the file map. You likely have a mismatch in the compiler options for the CDN download vs the compiler program. Existing Libs: " + libs + ".");
121
- }
122
- return result;
123
- }
124
- return nodeSys.readFile(fileName);
125
- }),
126
- resolvePath: function resolvePath(path3) {
127
- if (files.has(path3)) return path3;
128
- return nodeSys.resolvePath(path3);
129
- },
130
- newLine: "\n",
131
- useCaseSensitiveFileNames: true,
132
- write: function write() {
133
- return notImplemented("write");
134
- },
135
- writeFile: function writeFile(fileName, contents) {
136
- files.set(fileName, contents);
137
- },
138
- deleteFile: function deleteFile(fileName) {
139
- files["delete"](fileName);
140
- },
141
- realpath: nodeSys.realpath
142
- };
143
- }
144
- function createVirtualCompilerHost(sys, compilerOptions, ts) {
145
- var sourceFiles = /* @__PURE__ */ new Map();
146
- var save = function save2(sourceFile) {
147
- sourceFiles.set(sourceFile.fileName, sourceFile);
148
- return sourceFile;
149
- };
150
- var vHost = {
151
- compilerHost: _extends({}, sys, {
152
- getCanonicalFileName: function getCanonicalFileName(fileName) {
153
- return fileName;
154
- },
155
- getDefaultLibFileName: function getDefaultLibFileName() {
156
- return "/" + ts.getDefaultLibFileName(compilerOptions);
157
- },
158
- // '/lib.d.ts',
159
- // getDefaultLibLocation: () => '/',
160
- getNewLine: function getNewLine() {
161
- return sys.newLine;
162
- },
163
- getSourceFile: function getSourceFile(fileName, languageVersionOrOptions) {
164
- var _ref;
165
- return sourceFiles.get(fileName) || save(ts.createSourceFile(fileName, sys.readFile(fileName), (_ref = languageVersionOrOptions != null ? languageVersionOrOptions : compilerOptions.target) != null ? _ref : defaultCompilerOptions(ts).target, false));
166
- },
167
- useCaseSensitiveFileNames: function useCaseSensitiveFileNames() {
168
- return sys.useCaseSensitiveFileNames;
169
- }
170
- }),
171
- updateFile: function updateFile(sourceFile) {
172
- var alreadyExists = sourceFiles.has(sourceFile.fileName);
173
- sys.writeFile(sourceFile.fileName, sourceFile.text);
174
- sourceFiles.set(sourceFile.fileName, sourceFile);
175
- return alreadyExists;
176
- },
177
- deleteFile: function deleteFile(sourceFile) {
178
- var alreadyExists = sourceFiles.has(sourceFile.fileName);
179
- sourceFiles["delete"](sourceFile.fileName);
180
- sys.deleteFile(sourceFile.fileName);
181
- return alreadyExists;
182
- }
183
- };
184
- return vHost;
185
- }
186
- var requirePath = function requirePath2() {
187
- return __require(String.fromCharCode(112, 97, 116, 104));
188
- };
189
-
190
- // unplugin-civet:/home/runner/work/Civet/Civet/source/unplugin/unplugin.civet.jsx
13
+ import { pathToFileURL } from "url";
191
14
  import os from "os";
192
15
  var DEFAULT_EXTENSIONS = [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"];
193
16
  var DiagnosticCategory = {};
@@ -281,8 +104,15 @@ var rawPlugin = (options = {}, meta) => {
281
104
  let outDir = path.join(rootDir, "dist");
282
105
  let esbuildOptions;
283
106
  let configErrors;
284
- let configFileNames;
107
+ let configFileNames = [];
108
+ const pluginResolvedIds = /* @__PURE__ */ new Set();
285
109
  let skipWorker = false;
110
+ let tsBuildInfoTarget;
111
+ let nextDocVersion = 0;
112
+ let tsService;
113
+ let docFactory;
114
+ let service = null;
115
+ let incrementalTypecheckSetup;
286
116
  let ref;
287
117
  if (transformTS || ts === "tsc") {
288
118
  ref = import("typescript").then(($1) => $1.default);
@@ -291,10 +121,19 @@ var rawPlugin = (options = {}, meta) => {
291
121
  }
292
122
  ;
293
123
  const tsPromise = ref;
124
+ let ref1;
125
+ if (transformTS) {
126
+ ref1 = import("@danielx/civet/ts-service");
127
+ } else {
128
+ ref1 = void 0;
129
+ }
130
+ ;
131
+ const tsServicePromise = ref1;
294
132
  const getFormatHost = (sys) => {
295
133
  return {
296
134
  getCurrentDirectory: () => sys.getCurrentDirectory(),
297
135
  getNewLine: () => sys.newLine,
136
+ /* c8 ignore next 3 -- platform-dependent: tests run where useCaseSensitiveFileNames=true */
298
137
  getCanonicalFileName: sys.useCaseSensitiveFileNames ? (f) => f : (f) => f.toLowerCase()
299
138
  };
300
139
  };
@@ -303,6 +142,7 @@ var rawPlugin = (options = {}, meta) => {
303
142
  name: "unplugin-civet",
304
143
  enforce: "pre",
305
144
  async buildStart() {
145
+ pluginResolvedIds.clear();
306
146
  let civetConfigPath = options.config;
307
147
  if (civetConfigPath === void 0) {
308
148
  civetConfigPath = await findInDir(process.cwd());
@@ -331,14 +171,27 @@ var rawPlugin = (options = {}, meta) => {
331
171
  return;
332
172
  };
333
173
  const ts2 = await tsPromise;
334
- const tsConfigPath = ts2.findConfigFile(process.cwd(), ts2.sys.fileExists);
335
- if (!tsConfigPath) {
336
- throw new Error("Could not find 'tsconfig.json'");
174
+ if (transformTS) {
175
+ tsService = await tsServicePromise;
176
+ docFactory ??= tsService.createInMemoryDocFactory();
177
+ }
178
+ let config, error, tsConfigPath;
179
+ if (options.tsConfig) {
180
+ config = options.tsConfig;
181
+ if (options.tsConfig.rootDir) {
182
+ tsConfigPath = path.join(options.tsConfig.rootDir, "tsconfig.json");
183
+ }
184
+ } else {
185
+ tsConfigPath = ts2.findConfigFile(process.cwd(), ts2.sys.fileExists);
186
+ if (!tsConfigPath) {
187
+ throw new Error("Could not find 'tsconfig.json'");
188
+ }
189
+ ;
190
+ ({ config, error } = ts2.readConfigFile(
191
+ tsConfigPath,
192
+ ts2.sys.readFile
193
+ ));
337
194
  }
338
- const { config, error } = ts2.readConfigFile(
339
- tsConfigPath,
340
- ts2.sys.readFile
341
- );
342
195
  if (error) {
343
196
  console.error(ts2.formatDiagnostic(error, getFormatHost(ts2.sys)));
344
197
  throw error;
@@ -353,7 +206,9 @@ var rawPlugin = (options = {}, meta) => {
353
206
  const configContents = ts2.parseJsonConfigFileContent(
354
207
  config,
355
208
  system,
356
- process.cwd()
209
+ tsConfigPath ? path.dirname(tsConfigPath) : process.cwd(),
210
+ void 0,
211
+ tsConfigPath
357
212
  );
358
213
  configErrors = configContents.errors;
359
214
  configFileNames = configContents.fileNames;
@@ -368,105 +223,223 @@ var rawPlugin = (options = {}, meta) => {
368
223
  sourceMap: true
369
224
  };
370
225
  fsMap = /* @__PURE__ */ new Map();
226
+ let ref2;
227
+ if (tsConfigPath) {
228
+ ref2 = path.dirname(tsConfigPath);
229
+ } else ref2 = process.cwd();
230
+ const servicePath = ref2;
231
+ let extraCompilerOptions;
232
+ if (options.tsBuildInfoFile) {
233
+ tsBuildInfoTarget = path.resolve(servicePath, options.tsBuildInfoFile);
234
+ extraCompilerOptions = {
235
+ incremental: true,
236
+ tsBuildInfoFile: tsBuildInfoTarget,
237
+ noEmit: false
238
+ };
239
+ }
240
+ if (transformTS && tsService && docFactory) {
241
+ const transpileCache = tsService.createDiskCache(path.resolve(servicePath, ".cache/build"));
242
+ const plugins = [
243
+ tsService.makeCivetPlugin({
244
+ Civet: civet,
245
+ config: compileOptions,
246
+ cache: transpileCache
247
+ }),
248
+ tsService.makeHeraPlugin({
249
+ Civet: civet,
250
+ config: compileOptions,
251
+ cache: transpileCache
252
+ })
253
+ ];
254
+ const useIncremental = options.typecheck && !options.emitDeclaration && (options.discoverProjectFiles ?? false);
255
+ if (useIncremental) {
256
+ incrementalTypecheckSetup = {
257
+ plugins,
258
+ tsConfig: config,
259
+ extraCompilerOptions,
260
+ projectPath: servicePath
261
+ };
262
+ } else {
263
+ service = tsService.TSService(servicePath, {
264
+ plugins,
265
+ docFactory,
266
+ discoverProjectFiles: options.discoverProjectFiles ?? false,
267
+ extraCompilerOptions,
268
+ // TSService's own configSys handles .civet + .hera mogrification;
269
+ // unplugin's local one only adds .civet.
270
+ tsConfig: config
271
+ });
272
+ }
273
+ }
371
274
  }
372
275
  },
276
+ // useConfigFileNames=true expands the typecheck scope to every path
277
+ // tsconfig matched (captured in buildStart's `configFileNames`); the
278
+ // false default keeps it scoped to load()-tracked files + their
279
+ // transitive imports.
373
280
  async buildEnd(useConfigFileNames = false) {
374
281
  if (transformTS) {
375
282
  const ts2 = await tsPromise;
376
- const system = createFSBackedSystem(fsMap, process.cwd(), ts2);
377
- const {
378
- fileExists: systemFileExists,
379
- readFile: systemReadFile,
380
- readDirectory: systemReadDirectory
381
- } = system;
382
- system.fileExists = (filename) => {
383
- if (!filename.endsWith(".civet.tsx")) return systemFileExists(filename);
384
- if (fsMap.has(filename)) return true;
385
- return systemFileExists(filename.slice(0, -4));
386
- };
387
- system.readDirectory = (path2) => {
388
- return systemReadDirectory(path2).map(($3) => $3.endsWith(".civet") ? $3 + ".tsx" : $3);
389
- };
390
- const tsCompileOptions = {
391
- ...compileOptions,
392
- rewriteCivetImports: false,
393
- rewriteTsImports: true
283
+ let rawDiagnostics;
284
+ let getMeta;
285
+ let emitTsBuildInfo;
286
+ emitTsBuildInfo = () => {
287
+ return;
394
288
  };
395
- system.readFile = (filename, encoding = "utf-8") => {
396
- if (path.basename(filename) === "package.json") {
397
- let recurse = function(node) {
398
- if (node != null && typeof node === "object") {
399
- for (const key in node) {
400
- const value = node[key];
401
- if (typeof value === "string") {
402
- if (value.endsWith(".civet")) {
403
- node[key] = value + ".tsx";
404
- modified = true;
405
- }
406
- } else if (value) {
407
- recurse(value);
408
- }
409
- }
289
+ let program;
290
+ if (incrementalTypecheckSetup) {
291
+ if (!(tsService != null)) {
292
+ return;
293
+ }
294
+ const { builder, getMeta: gm, configErrors: cErrors } = tsService.makeIncrementalTypecheckProgram(
295
+ incrementalTypecheckSetup.projectPath,
296
+ incrementalTypecheckSetup
297
+ );
298
+ getMeta = gm;
299
+ while (true) {
300
+ const r = builder.getSemanticDiagnosticsOfNextAffectedFile();
301
+ if (!r) {
302
+ break;
303
+ }
304
+ }
305
+ program = builder.getProgram();
306
+ const collected = [];
307
+ collected.push(...builder.getOptionsDiagnostics());
308
+ collected.push(...builder.getGlobalDiagnostics());
309
+ for (const f of program.getSourceFiles()) {
310
+ collected.push(...builder.getSyntacticDiagnostics(f));
311
+ collected.push(...builder.getSemanticDiagnostics(f));
312
+ collected.push(...builder.getDeclarationDiagnostics(f));
313
+ }
314
+ rawDiagnostics = ts2.sortAndDeduplicateDiagnostics(collected);
315
+ if (cErrors && cErrors.length > 0) {
316
+ configErrors = [...cErrors];
317
+ }
318
+ if (tsBuildInfoTarget) {
319
+ const target = tsBuildInfoTarget;
320
+ const writeFile = (fileName, data) => {
321
+ if (fileName === target) {
322
+ return ts2.sys.writeFile(fileName, data);
410
323
  }
324
+ ;
325
+ return;
411
326
  };
412
- const json = systemReadFile(filename, encoding);
413
- if (!json) {
414
- return json;
327
+ emitTsBuildInfo = () => {
328
+ return builder.emit(void 0, writeFile, void 0, false);
329
+ };
330
+ }
331
+ } else {
332
+ if (!(service != null)) {
333
+ return;
334
+ }
335
+ for (const tsxPath of fsMap.keys()) {
336
+ if (!tsxPath.endsWith(".civet.tsx")) {
337
+ continue;
415
338
  }
416
- const parsed = JSON.parse(json);
417
- let modified = false;
418
- recurse(parsed.imports);
419
- return modified ? JSON.stringify(parsed) : json;
339
+ const civetPath = tsxPath.slice(0, -4);
340
+ service.host.getMeta(civetPath);
341
+ }
342
+ if (useConfigFileNames) {
343
+ for (const fn of configFileNames) {
344
+ service.host.addScriptFileName(fn);
345
+ }
346
+ }
347
+ program = service.getProgram();
348
+ let builder;
349
+ if (options.tsBuildInfoFile) {
350
+ const builderHost = {};
351
+ const readHost = {
352
+ useCaseSensitiveFileNames: () => ts2.sys.useCaseSensitiveFileNames,
353
+ getCurrentDirectory: () => ts2.sys.getCurrentDirectory(),
354
+ readFile: (fileName) => ts2.sys.readFile(fileName)
355
+ };
356
+ const oldProgram = ts2.readBuilderProgram(program.getCompilerOptions(), readHost);
357
+ builder = ts2.createSemanticDiagnosticsBuilderProgram(program, builderHost, oldProgram);
358
+ }
359
+ rawDiagnostics = ts2.getPreEmitDiagnostics(builder ?? program);
360
+ getMeta = (p) => service.host.getMeta(p);
361
+ if (builder && tsBuildInfoTarget) {
362
+ const target = tsBuildInfoTarget;
363
+ const writeFile = (fileName, data) => {
364
+ if (fileName === target) {
365
+ return ts2.sys.writeFile(fileName, data);
366
+ }
367
+ ;
368
+ return;
369
+ };
370
+ emitTsBuildInfo = () => {
371
+ return builder.emit(void 0, writeFile, void 0, false);
372
+ };
373
+ }
374
+ }
375
+ const realFileCache = /* @__PURE__ */ new Map();
376
+ const realSourceFile = (realPath) => {
377
+ const cached = realFileCache.get(realPath);
378
+ if (cached) {
379
+ return cached;
380
+ }
381
+ try {
382
+ const src = fs.readFileSync(realPath, "utf8");
383
+ const sf = ts2.createSourceFile(realPath, src, ts2.ScriptTarget.ESNext, true);
384
+ realFileCache.set(realPath, sf);
385
+ return sf;
386
+ } catch {
387
+ return void 0;
420
388
  }
421
- if (!filename.endsWith(".civet.tsx")) return systemReadFile(filename, encoding);
422
- if (fsMap.has(filename)) return fsMap.get(filename);
423
- const civetFilename = filename.slice(0, -4);
424
- const rawCivetSource = fs.readFileSync(civetFilename, { encoding });
425
- const { code: compiledTS, sourceMap } = civet.compile(rawCivetSource, {
426
- ...tsCompileOptions,
427
- filename,
428
- js: false,
429
- sourceMap: true,
430
- sync: true
431
- // TS readFile API seems to need to be synchronous
432
- });
433
- fsMap.set(filename, compiledTS);
434
- sourceMaps.set(filename, sourceMap);
435
- return compiledTS;
436
389
  };
437
- const host = createVirtualCompilerHost(
438
- system,
439
- compilerOptions,
440
- ts2
441
- );
442
- const program = ts2.createProgram({
443
- rootNames: useConfigFileNames ? configFileNames : [...fsMap.keys()],
444
- options: compilerOptions,
445
- host: host.compilerHost
446
- });
447
- const diagnostics = ts2.getPreEmitDiagnostics(program).map((diagnostic) => {
448
- const file = diagnostic.file;
449
- if (!file) return diagnostic;
450
- const sourceMap = sourceMaps.get(file.fileName);
451
- if (!sourceMap) return diagnostic;
452
- const sourcemapLines = sourceMap.lines ?? sourceMap.data.lines;
453
- const range = remapRange(
454
- {
455
- start: diagnostic.start || 0,
456
- end: (diagnostic.start || 0) + (diagnostic.length || 1)
457
- },
458
- sourcemapLines
459
- );
460
- return {
461
- ...diagnostic,
462
- messageText: flattenDiagnosticMessageText(diagnostic.messageText),
463
- length: diagnostic.length,
464
- start: range.start
390
+ const diagnostics = [];
391
+ for (const d of rawDiagnostics) {
392
+ const file = d.file;
393
+ if (!file) {
394
+ diagnostics.push(d);
395
+ continue;
396
+ }
397
+ const isHera = file.fileName.endsWith(".hera.tsx");
398
+ const isTranspiled = file.fileName.endsWith(".civet.tsx") || isHera;
399
+ const sourcePath = isTranspiled ? file.fileName.slice(0, -4) : file.fileName;
400
+ const meta2 = getMeta(sourcePath);
401
+ const sourcemapLines = meta2?.sourcemapLines;
402
+ if (!sourcemapLines) {
403
+ diagnostics.push(d);
404
+ continue;
405
+ }
406
+ const startLc = file.getLineAndCharacterOfPosition(d.start || 0);
407
+ const endLc = file.getLineAndCharacterOfPosition((d.start || 0) + (d.length || 1));
408
+ const remappedStartLc = remapPosition(startLc, sourcemapLines);
409
+ const remappedEndLc = remapPosition(endLc, sourcemapLines);
410
+ const realFile = realSourceFile(sourcePath);
411
+ if (!realFile) {
412
+ diagnostics.push({
413
+ ...d,
414
+ messageText: flattenDiagnosticMessageText(d.messageText)
415
+ });
416
+ continue;
417
+ }
418
+ const toPos = (lc) => {
419
+ try {
420
+ return realFile.getPositionOfLineAndCharacter(lc.line, lc.character);
421
+ } catch {
422
+ return void 0;
423
+ }
465
424
  };
466
- });
425
+ const remappedStart = toPos(remappedStartLc);
426
+ if (remappedStart === void 0) {
427
+ diagnostics.push(d);
428
+ continue;
429
+ }
430
+ const remappedEnd = toPos(remappedEndLc) ?? remappedStart + 1;
431
+ diagnostics.push({
432
+ ...d,
433
+ file: realFile,
434
+ start: remappedStart,
435
+ length: Math.max(1, remappedEnd - remappedStart),
436
+ messageText: flattenDiagnosticMessageText(d.messageText)
437
+ });
438
+ }
467
439
  if (configErrors?.length) {
468
440
  diagnostics.unshift(...configErrors);
469
441
  }
442
+ emitTsBuildInfo();
470
443
  if (diagnostics.length > 0) {
471
444
  console.error(
472
445
  ts2.formatDiagnosticsWithColorAndContext(
@@ -488,9 +461,17 @@ var rawPlugin = (options = {}, meta) => {
488
461
  failures.push(DiagnosticCategory.Error);
489
462
  }
490
463
  const count = diagnostics.filter((d) => failures.includes(d.category)).length;
491
- if (count) {
464
+ const threshold = options.maxErrors ?? 0;
465
+ if (count > threshold) {
492
466
  const reason = count === diagnostics.length ? count : `${count} out of ${diagnostics.length}`;
493
- throw new Error(`Aborting build because of ${reason} TypeScript diagnostic${diagnostics.length > 1 ? "s" : ""} above`);
467
+ let ref3;
468
+ if (threshold > 0) {
469
+ ref3 = ` (baseline ${threshold})`;
470
+ } else ref3 = "";
471
+ const note = ref3;
472
+ throw new Error(`Aborting build because of ${reason} TypeScript diagnostic${diagnostics.length > 1 ? "s" : ""} above${note}`);
473
+ } else if (threshold > 0 && count > 0) {
474
+ console.error(`Within baseline of ${threshold} TypeScript diagnostic${threshold > 1 ? "s" : ""}; not failing.`);
494
475
  }
495
476
  }
496
477
  }
@@ -550,14 +531,14 @@ var rawPlugin = (options = {}, meta) => {
550
531
  }
551
532
  if (/\0/.test(id)) return null;
552
533
  const { filename, postfix } = extractCivetFilename(id, outExt);
553
- let ref1;
534
+ let ref4;
554
535
  if (path.isAbsolute(filename)) {
555
- ref1 = resolveAbsolutePath(rootDir, filename, implicitExtension);
536
+ ref4 = resolveAbsolutePath(rootDir, filename, implicitExtension);
556
537
  } else {
557
- ref1 = path.resolve(path.dirname(importer ?? ""), filename);
538
+ ref4 = path.resolve(path.dirname(importer ?? ""), filename);
558
539
  }
559
540
  ;
560
- let resolved = ref1;
541
+ let resolved = ref4;
561
542
  if (!resolved) return null;
562
543
  if (!resolved.endsWith(civetSuffix)) {
563
544
  if (!implicitExtension) return null;
@@ -565,6 +546,7 @@ var rawPlugin = (options = {}, meta) => {
565
546
  if (!implicitId) return null;
566
547
  resolved = implicitId;
567
548
  }
549
+ pluginResolvedIds.add(resolved);
568
550
  if (options2.scan && meta.framework === "vite") {
569
551
  resolved = `\0${resolved}`;
570
552
  }
@@ -593,9 +575,9 @@ var rawPlugin = (options = {}, meta) => {
593
575
  if (cached.promise) {
594
576
  await cached.promise;
595
577
  }
596
- let ref2;
597
- if ((ref2 = cached.result) != null) {
598
- const result = ref2;
578
+ let ref5;
579
+ if ((ref5 = cached.result) != null) {
580
+ const result = ref5;
599
581
  return result;
600
582
  }
601
583
  }
@@ -625,9 +607,17 @@ var rawPlugin = (options = {}, meta) => {
625
607
  ...civetOptions,
626
608
  ast: true
627
609
  });
610
+ let ref6;
611
+ if (meta.framework === "esbuild" && pluginResolvedIds.has(filename)) {
612
+ ref6 = path.relative(outDir, filename);
613
+ } else {
614
+ ref6 = path.basename(filename);
615
+ }
616
+ ;
617
+ const sourceMapSource = ref6;
628
618
  const civetSourceMap = new SourceMap(
629
619
  rawCivetSource,
630
- normalizePath(path.relative(outDir, filename))
620
+ normalizePath(sourceMapSource)
631
621
  );
632
622
  if (ts === "civet") {
633
623
  compiled = await civet.generate(ast, {
@@ -674,8 +664,8 @@ var rawPlugin = (options = {}, meta) => {
674
664
  }
675
665
  }
676
666
  if (transformTS) {
677
- for (let ref3 = lib.gatherRecursive(ast, (($) => $.type === "ModuleSpecifier")), i = 0, len = ref3.length; i < len; i++) {
678
- const _spec = ref3[i];
667
+ for (let ref7 = lib.gatherRecursive(ast, (($) => $.type === "ModuleSpecifier")), i = 0, len = ref7.length; i < len; i++) {
668
+ const _spec = ref7[i];
679
669
  const spec = _spec;
680
670
  if (spec.module?.input) {
681
671
  spec.module.token = spec.module.input.replace(/\.([mc])?ts(['"])$/, ".$1js$2");
@@ -695,6 +685,15 @@ var rawPlugin = (options = {}, meta) => {
695
685
  fsMap.set(slashed, compiledTS);
696
686
  sourceMaps.set(slashed, civetSourceMap);
697
687
  }
688
+ if (service != null && docFactory != null) {
689
+ const doc = docFactory.create(
690
+ pathToFileURL(filename).toString(),
691
+ "civet",
692
+ ++nextDocVersion,
693
+ rawCivetSource
694
+ );
695
+ service.host.addOrUpdateDocument(doc);
696
+ }
698
697
  }
699
698
  const jsonSourceMap = sourceMap && (typeof sourceMap === "string" ? JSON.parse(sourceMap) : sourceMap.json(normalizePath(path.relative(outDir, id))));
700
699
  let transformed = {
@@ -735,7 +734,7 @@ var rawPlugin = (options = {}, meta) => {
735
734
  config.resolve.extensions.push(".civet");
736
735
  }
737
736
  },
738
- async transformIndexHtml(html) {
737
+ transformIndexHtml(html) {
739
738
  return html.replace(/<!--[^]*?-->|<[^<>]*>/g, (tag) => {
740
739
  return tag.replace(/<\s*script\b[^<>]*>/gi, (script) => {
741
740
  return script.replace(
@@ -757,9 +756,9 @@ var rawPlugin = (options = {}, meta) => {
757
756
  return;
758
757
  }
759
758
  const resolvedId = slash(path.resolve(file) + outExt);
760
- let ref4;
761
- if (ref4 = server.moduleGraph.getModulesByFile(resolvedId)) {
762
- const fileModules = ref4;
759
+ let ref8;
760
+ if (ref8 = server.moduleGraph.getModulesByFile(resolvedId)) {
761
+ const fileModules = ref8;
763
762
  server.moduleGraph.onFileChange(resolvedId);
764
763
  return [...modules, ...fileModules];
765
764
  }
@@ -783,9 +782,9 @@ var rawPlugin = (options = {}, meta) => {
783
782
  compiler.options.resolve.extensions.unshift(".civet");
784
783
  }
785
784
  return aliasResolver = (id) => {
786
- let ref5;
787
- for (const key in ref5 = compiler.options.resolve.alias) {
788
- const value = ref5[key];
785
+ let ref9;
786
+ for (const key in ref9 = compiler.options.resolve.alias) {
787
+ const value = ref9[key];
789
788
  if (key.endsWith("$")) {
790
789
  if (id === key.slice(0, -1)) {
791
790
  return typeof value === "string" ? value : "\0";
@@ -806,9 +805,9 @@ var rawPlugin = (options = {}, meta) => {
806
805
  return plugin;
807
806
  };
808
807
  var unplugin = createUnplugin(rawPlugin);
809
- var unplugin_civet_default = unplugin;
808
+ var unplugin_default = unplugin;
810
809
  export {
811
- unplugin_civet_default as default,
810
+ unplugin_default as default,
812
811
  rawPlugin,
813
812
  slash
814
813
  };