@systemfsoftware/stryker-js-typescript-checker 8.0.1 → 8.1.1

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,1495 @@
1
+ import { Blueprint, Cell, Handle, Sandwich, Workflow } from "@systemfsoftware/effect-cell-types";
2
+ import { SpanTaxonomy } from "@systemfsoftware/stryker-js-cli-contract";
3
+ import { ErrorText, lineStartsOf, offsetAt } from "@systemfsoftware/stryker-js-instrumenter";
4
+ import { Checker, Mutant } from "@systemfsoftware/stryker-js-plugin-interface";
5
+ import * as Arr from "effect/Array";
6
+ import * as Boolean from "effect/Boolean";
7
+ import * as Context from "effect/Context";
8
+ import * as Effect from "effect/Effect";
9
+ import * as FileSystem from "effect/FileSystem";
10
+ import * as HashMap from "effect/HashMap";
11
+ import * as Layer from "effect/Layer";
12
+ import * as Match from "effect/Match";
13
+ import * as Option from "effect/Option";
14
+ import * as Path from "effect/Path";
15
+ import * as Result from "effect/Result";
16
+ import * as S from "effect/Schema";
17
+ import { dual } from "effect/Function";
18
+ import * as HashSet from "effect/HashSet";
19
+ import * as SynchronizedRef from "effect/SynchronizedRef";
20
+ import { SyntaxKind } from "typescript/unstable/ast";
21
+ import { isModuleDeclaration } from "typescript/unstable/ast/is";
22
+ import { API, DiagnosticCategory, ModifierFlags } from "typescript/unstable/async";
23
+ import { Schema } from "effect";
24
+ import * as SchemaIssue from "effect/SchemaIssue";
25
+ import * as SchemaTransformation from "effect/SchemaTransformation";
26
+ import * as Clock from "effect/Clock";
27
+ import * as DateTime from "effect/DateTime";
28
+ //#region src/CheckMutants.schema.ts
29
+ const SourceFileSchema = S.NonEmptyString.pipe(S.check(S.isPattern(/\.[^./\\]+$/u)));
30
+ const DiagnosticSeveritySchema = S.Literals([
31
+ "error",
32
+ "warning",
33
+ "suggestion",
34
+ "message"
35
+ ]);
36
+ var DiagnosticLine = class extends S.Class("DiagnosticLine")({
37
+ fileName: S.optional(SourceFileSchema),
38
+ position: S.String,
39
+ severity: DiagnosticSeveritySchema,
40
+ code: S.Finite,
41
+ text: S.String
42
+ }) {
43
+ get rendered() {
44
+ return this.position + this.severity + " TS" + this.code + ": " + this.text;
45
+ }
46
+ };
47
+ var MutantVerdict = class extends S.Class("MutantVerdict")({
48
+ id: Mutant.MutantId,
49
+ diagnostics: S.Array(DiagnosticLine)
50
+ }) {};
51
+ var CheckMutantsInput = class extends S.TaggedClass()("CheckMutantsInput", {
52
+ mutants: S.Array(Checker.CheckerMutantWire),
53
+ verdicts: S.Array(MutantVerdict)
54
+ }) {
55
+ static [Workflow.InstrumentationBrand] = {};
56
+ };
57
+ S.is(SourceFileSchema);
58
+ //#endregion
59
+ //#region src/check-mutants.workflow.ts
60
+ const CheckTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/CheckOutcome");
61
+ var MutantPassed = class extends S.TaggedClass()("MutantPassed", { id: Mutant.MutantId }) {
62
+ [CheckTypeId] = CheckTypeId;
63
+ };
64
+ var MutantFailed = class extends S.TaggedClass()("MutantFailed", {
65
+ id: Mutant.MutantId,
66
+ reason: S.String
67
+ }) {
68
+ [CheckTypeId] = CheckTypeId;
69
+ };
70
+ const CheckOutcomes = S.Array(S.Union([MutantPassed, MutantFailed]));
71
+ const outcomeOf = (mutantId, diagnostics) => Boolean.match(diagnostics.length === 0, {
72
+ onTrue: () => MutantPassed.make({ id: mutantId }),
73
+ onFalse: () => MutantFailed.make({
74
+ id: mutantId,
75
+ reason: Arr.map(diagnostics, (diagnostic) => diagnostic.rendered).join("\n")
76
+ })
77
+ });
78
+ const decide$8 = (input) => {
79
+ const diagnostics = HashMap.fromIterable(Arr.map(input.verdicts, (verdict) => [verdict.id, verdict.diagnostics]));
80
+ return Result.succeed(Arr.map(input.mutants, (mutant) => outcomeOf(mutant.id, Option.getOrElse(HashMap.get(diagnostics, mutant.id), () => []))));
81
+ };
82
+ const checkMutants = Workflow.make({
83
+ command: CheckMutantsInput,
84
+ decision: CheckOutcomes,
85
+ error: S.Never,
86
+ decide: decide$8
87
+ });
88
+ S.Struct({ typescriptChecker: S.optional(S.Struct({})) });
89
+ var CheckMutantsCommand = class extends S.TaggedClass()("CheckMutantsCommand", { mutants: S.Array(Checker.CheckerMutantWire) }) {};
90
+ //#endregion
91
+ //#region src/Tsconfig.schema.ts
92
+ var TsConfigParseError = class extends Schema.TaggedError()("TsConfigParseError", {
93
+ file: Schema.String,
94
+ reason: Schema.String
95
+ }) {
96
+ get message() {
97
+ return `Could not parse tsconfig file '${this.file}': ${this.reason}`;
98
+ }
99
+ };
100
+ var TsConfigNotFoundError = class extends Schema.TaggedError()("TsConfigNotFoundError", { file: Schema.String }) {
101
+ get message() {
102
+ return `The tsconfig file does not exist at: "${this.file}". Please configure the tsconfig file in your stryker.conf file using "tsconfigFile"`;
103
+ }
104
+ };
105
+ const PathAliasesSchema = Schema.Record(Schema.String, Schema.Array(Schema.String));
106
+ const JsonRecord = Schema.Record(Schema.String, Schema.Json);
107
+ const ProjectReferenceSchema = Schema.StructWithRest(Schema.Struct({ path: Schema.String }), [JsonRecord]);
108
+ const TsConfigCompilerOptionsSchema = JsonRecord;
109
+ const TsConfigDocumentSchema = Schema.StructWithRest(Schema.Struct({
110
+ references: Schema.optional(Schema.Array(ProjectReferenceSchema)),
111
+ compilerOptions: Schema.optional(TsConfigCompilerOptionsSchema)
112
+ }), [JsonRecord]);
113
+ Schema.is(TsConfigDocumentSchema);
114
+ //#endregion
115
+ //#region src/CheckerCommands.schema.ts
116
+ var GroupMutantsCommand = class extends S.TaggedClass()("GroupMutantsCommand", { mutants: S.Array(Checker.CheckerMutantWire) }) {
117
+ static [Workflow.InstrumentationBrand] = {};
118
+ };
119
+ var TraceAffectedFilesCommand = class extends S.TaggedClass()("TraceAffectedFilesCommand", {
120
+ importsByFile: S.Record(S.String, S.Array(S.String)),
121
+ mutatedFileNames: S.Array(S.String)
122
+ }) {
123
+ static [Workflow.InstrumentationBrand] = { mutatedFileNames: "stryker.typescript_checker.mutated_files" };
124
+ };
125
+ var RequestAffectedFilesCommand = class extends S.TaggedClass()("RequestAffectedFilesCommand", {
126
+ affectedFileNames: S.Array(S.String),
127
+ presentFileNames: S.Array(S.String)
128
+ }) {
129
+ static [Workflow.InstrumentationBrand] = { affectedFileNames: "stryker.typescript_checker.affected_files" };
130
+ };
131
+ var PlanDiagnosticBatchesCommand = class extends S.TaggedClass()("PlanDiagnosticBatchesCommand", { fileNames: S.Array(S.String) }) {
132
+ static [Workflow.InstrumentationBrand] = { fileNames: "stryker.typescript_checker.requested_files" };
133
+ };
134
+ var CaptureAliasSpecifierCommand = class extends S.TaggedClass()("CaptureAliasSpecifierCommand", {
135
+ pattern: S.String,
136
+ specifier: S.String
137
+ }) {
138
+ static [Workflow.InstrumentationBrand] = { specifier: "stryker.typescript_checker.specifier" };
139
+ };
140
+ var PlanResolutionCandidatesCommand = class extends S.TaggedClass()("PlanResolutionCandidatesCommand", {
141
+ resolved: S.String,
142
+ extension: S.String
143
+ }) {
144
+ static [Workflow.InstrumentationBrand] = { resolved: "stryker.typescript_checker.resolved_file" };
145
+ };
146
+ var OverrideTsconfigOptionsCommand = class extends S.TaggedClass()("OverrideTsconfigOptionsCommand", {
147
+ document: TsConfigDocumentSchema,
148
+ buildMode: S.Boolean
149
+ }) {
150
+ static [Workflow.InstrumentationBrand] = { buildMode: "stryker.typescript_checker.build_mode" };
151
+ };
152
+ var ParseTsconfigTextCommand = class extends S.TaggedClass()("ParseTsconfigTextCommand", { text: S.String }) {
153
+ static [Workflow.InstrumentationBrand] = {};
154
+ };
155
+ //#endregion
156
+ //#region src/capture-alias-specifier.workflow.ts
157
+ const CaptureTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/AliasCapture");
158
+ var AliasSpecifierCaptured = class extends S.TaggedClass()("AliasSpecifierCaptured", { capture: S.String }) {
159
+ [CaptureTypeId] = CaptureTypeId;
160
+ };
161
+ var AliasSpecifierUnmatched = class extends S.TaggedClass()("AliasSpecifierUnmatched", {}) {
162
+ [CaptureTypeId] = CaptureTypeId;
163
+ };
164
+ const AliasCapture = S.Union([AliasSpecifierCaptured, AliasSpecifierUnmatched]);
165
+ const prefixOf = (pattern) => pattern.slice(0, pattern.indexOf("*"));
166
+ const suffixOf = (pattern) => pattern.slice(pattern.indexOf("*") + 1);
167
+ const stripPrefix = (specifier, prefix) => Option.map(Option.liftPredicate(specifier, (candidate) => candidate.startsWith(prefix)), (candidate) => candidate.slice(prefix.length));
168
+ const stripSuffix = (specifier, suffix) => Option.map(Option.liftPredicate(specifier, (candidate) => candidate.endsWith(suffix)), (candidate) => candidate.slice(0, candidate.length - suffix.length));
169
+ const wildcardCaptureOf = (pattern, specifier) => Option.flatMap(stripPrefix(specifier, prefixOf(pattern)), (rest) => stripSuffix(rest, suffixOf(pattern)));
170
+ const exactCaptureOf = (pattern, specifier) => Option.map(Option.liftPredicate(specifier, (candidate) => candidate === pattern), () => "");
171
+ const captureOf = (pattern, specifier) => Boolean.match(pattern.includes("*"), {
172
+ onTrue: () => wildcardCaptureOf(pattern, specifier),
173
+ onFalse: () => exactCaptureOf(pattern, specifier)
174
+ });
175
+ const decide$7 = (command) => Result.succeed(Option.match(captureOf(command.pattern, command.specifier), {
176
+ onNone: () => AliasSpecifierUnmatched.make({}),
177
+ onSome: (capture) => AliasSpecifierCaptured.make({ capture })
178
+ }));
179
+ const captureAliasSpecifier = Workflow.make({
180
+ command: CaptureAliasSpecifierCommand,
181
+ decision: AliasCapture,
182
+ error: S.Never,
183
+ decide: decide$7
184
+ });
185
+ //#endregion
186
+ //#region src/Compiler.schema.ts
187
+ /**
188
+ * Compiler — declarations for the TypeScript compiler and version guard.
189
+ *
190
+ * The error vocabulary every compiler operation refuses with; decoded and
191
+ * reported at the checker boundary, no I/O.
192
+ */
193
+ /** The installed TypeScript version is below the supported floor. */
194
+ var UnsupportedTypeScriptVersionError = class extends Schema.TaggedError()("UnsupportedTypeScriptVersionError", { version: Schema.String }) {
195
+ get message() {
196
+ return `@systemfsoftware/stryker-js-typescript-checker only supports typescript@7.0.0 or higher. Found typescript@${this.version}`;
197
+ }
198
+ };
199
+ /** Requested file is not present in the hybrid in-memory file map. */
200
+ var HybridFileNotFoundError = class extends Schema.TaggedError()("HybridFileNotFoundError", { fileName: Schema.String }) {
201
+ get message() {
202
+ return `'${this.fileName}' is part of your TypeScript project but could not be found on disk`;
203
+ }
204
+ };
205
+ var HybridMutantOutsideFileError = class extends Schema.TaggedError()("HybridMutantOutsideFileError", { fileName: Schema.String }) {
206
+ get message() {
207
+ return `A mutant's location falls outside '${this.fileName}'`;
208
+ }
209
+ };
210
+ /**
211
+ * Every way the TypeScript compiler can fail while serving a check.
212
+ * One tagged error — callers branch only on failure itself; `reason` keeps
213
+ * cases distinguishable in reports.
214
+ */
215
+ var CompilerFailed = class extends Schema.TaggedError()("CompilerFailed", {
216
+ reason: Schema.Literals([
217
+ "not-initialized",
218
+ "no-projects",
219
+ "unknown-file-node",
220
+ "file-not-in-project",
221
+ "mutant-outside-file"
222
+ ]),
223
+ subject: Schema.optional(Schema.String)
224
+ }) {
225
+ get message() {
226
+ return Match.value(this.reason).pipe(Match.when("not-initialized", () => "The TypeScript compiler was used before it was initialized"), Match.when("no-projects", () => `No projects were found for ${this.subject ?? "the tsconfig"}`), Match.when("unknown-file-node", () => `The file graph has no node for '${this.subject ?? "a file"}', which should not happen`), Match.when("file-not-in-project", () => `'${this.subject ?? "a file"}' is part of your TypeScript project but could not be found on disk`), Match.when("mutant-outside-file", () => `A mutant's location falls outside '${this.subject ?? "a file"}'`), Match.exhaustive);
227
+ }
228
+ };
229
+ var DryRunCompileErrors = class extends Schema.TaggedError()("DryRunCompileErrors", { text: Schema.String }) {
230
+ get message() {
231
+ return `Typescript error(s) found in dry run compilation: ${this.text}`;
232
+ }
233
+ };
234
+ //#endregion
235
+ //#region src/group-mutants.workflow.ts
236
+ const GroupingTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/Grouping");
237
+ var MutantGroup = class extends S.TaggedClass()("MutantGroup", { ids: S.Array(S.String) }) {
238
+ [GroupingTypeId] = GroupingTypeId;
239
+ };
240
+ const MutantGroups = S.Array(MutantGroup);
241
+ const emptyBatching = {
242
+ files: [],
243
+ idsByFile: HashMap.empty()
244
+ };
245
+ const accumulate = (batching, mutant) => Option.match(HashMap.get(batching.idsByFile, mutant.fileName), {
246
+ onNone: () => ({
247
+ files: [...batching.files, mutant.fileName],
248
+ idsByFile: HashMap.set(batching.idsByFile, mutant.fileName, [mutant.id])
249
+ }),
250
+ onSome: (ids) => ({
251
+ ...batching,
252
+ idsByFile: HashMap.set(batching.idsByFile, mutant.fileName, [...ids, mutant.id])
253
+ })
254
+ });
255
+ const batchIdsOf = (command) => {
256
+ const batching = Arr.reduce(command.mutants, emptyBatching, accumulate);
257
+ return Arr.map(batching.files, (fileName) => Option.getOrElse(HashMap.get(batching.idsByFile, fileName), () => []));
258
+ };
259
+ const decide$6 = (command) => Result.succeed(Arr.map(batchIdsOf(command), (ids) => MutantGroup.make({ ids })));
260
+ const groupMutants = Workflow.make({
261
+ command: GroupMutantsCommand,
262
+ decision: MutantGroups,
263
+ error: S.Never,
264
+ decide: decide$6
265
+ });
266
+ //#endregion
267
+ //#region src/override-tsconfig-options.workflow.ts
268
+ const OverrideTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TsconfigOverride");
269
+ var ProjectReferencesOverride = class extends S.TaggedClass()("ProjectReferencesOverride", { text: S.String }) {
270
+ [OverrideTypeId] = OverrideTypeId;
271
+ };
272
+ var SingleProjectOverride = class extends S.TaggedClass()("SingleProjectOverride", { text: S.String }) {
273
+ [OverrideTypeId] = OverrideTypeId;
274
+ };
275
+ const TsconfigOverride = S.Union([ProjectReferencesOverride, SingleProjectOverride]);
276
+ const COMPILER_OPTIONS_OVERRIDES = Object.freeze({
277
+ allowUnreachableCode: true,
278
+ noUnusedLocals: false,
279
+ noUnusedParameters: false,
280
+ skipLibCheck: true
281
+ });
282
+ const NO_EMIT_OPTIONS_FOR_SINGLE_PROJECT = Object.freeze({
283
+ noEmit: true,
284
+ incremental: false,
285
+ tsBuildInfoFile: void 0,
286
+ composite: false
287
+ });
288
+ const LOW_EMIT_OPTIONS_FOR_PROJECT_REFERENCES = Object.freeze({
289
+ emitDeclarationOnly: true,
290
+ noEmit: false,
291
+ declarationMap: true,
292
+ declaration: true,
293
+ composite: true
294
+ });
295
+ const compilerOptionsOf$1 = (document) => Option.getOrElse(Option.fromUndefinedOr(document.compilerOptions), () => ({}));
296
+ const withCompilerOverrides = (document, extraOptions) => ({
297
+ ...compilerOptionsOf$1(document),
298
+ ...COMPILER_OPTIONS_OVERRIDES,
299
+ ...extraOptions
300
+ });
301
+ const projectReferencesJson = (document) => {
302
+ const compilerOptions = withCompilerOverrides(document, LOW_EMIT_OPTIONS_FOR_PROJECT_REFERENCES);
303
+ delete compilerOptions["inlineSourceMap"];
304
+ delete compilerOptions["inlineSources"];
305
+ delete compilerOptions["mapRoute"];
306
+ delete compilerOptions["sourceRoot"];
307
+ delete compilerOptions["outFile"];
308
+ return JSON.stringify({
309
+ ...document,
310
+ compilerOptions
311
+ });
312
+ };
313
+ const singleProjectJson = (document) => {
314
+ const compilerOptions = withCompilerOverrides(document, NO_EMIT_OPTIONS_FOR_SINGLE_PROJECT);
315
+ Boolean.match(compilerOptions["declarationDir"] !== null, {
316
+ onTrue: () => {
317
+ delete compilerOptions["declarationDir"];
318
+ },
319
+ onFalse: () => void 0
320
+ });
321
+ const { references: _references, ...withoutReferences } = document;
322
+ return JSON.stringify({
323
+ ...withoutReferences,
324
+ compilerOptions
325
+ });
326
+ };
327
+ const decide$5 = (command) => Result.succeed(Boolean.match(command.buildMode, {
328
+ onTrue: () => ProjectReferencesOverride.make({ text: projectReferencesJson(command.document) }),
329
+ onFalse: () => SingleProjectOverride.make({ text: singleProjectJson(command.document) })
330
+ }));
331
+ const overrideTsconfigOptions = Workflow.make({
332
+ command: OverrideTsconfigOptionsCommand,
333
+ decision: TsconfigOverride,
334
+ error: S.Never,
335
+ decide: decide$5
336
+ });
337
+ //#endregion
338
+ //#region ../../node_modules/.pnpm/@jsr+std__jsonc@1.0.2/node_modules/@jsr/std__jsonc/parse.js
339
+ /**
340
+ * Converts a JSON with Comments (JSONC) string into an object.
341
+ *
342
+ * @example Usage
343
+ * ```ts
344
+ * import { parse } from "@std/jsonc";
345
+ * import { assertEquals } from "@std/assert";
346
+ *
347
+ * assertEquals(parse('{"foo": "bar"}'), { foo: "bar" });
348
+ * assertEquals(parse('{"foo": "bar", }'), { foo: "bar" });
349
+ * assertEquals(parse('{"foo": "bar", } /* comment *\/'), { foo: "bar" });
350
+ * ```
351
+ *
352
+ * @throws {SyntaxError} If the JSONC string is invalid.
353
+ * @param text A valid JSONC string.
354
+ * @returns The parsed JsonValue from the JSONC string.
355
+ */ function parse(text) {
356
+ if (new.target) throw new TypeError("Cannot create an instance: parse is not a constructor");
357
+ return new JsoncParser(text).parse();
358
+ }
359
+ var JsoncParser = class {
360
+ #whitespace = /* @__PURE__ */ new Set(" \r\n");
361
+ #numberEndToken = /* @__PURE__ */ new Set([..."[]{}:,/", ...this.#whitespace]);
362
+ #text;
363
+ #length;
364
+ #tokenized;
365
+ constructor(text) {
366
+ this.#text = `${text}`;
367
+ this.#length = this.#text.length;
368
+ this.#tokenized = this.#tokenize();
369
+ }
370
+ parse() {
371
+ const token = this.#getNext();
372
+ const res = this.#parseJsonValue(token);
373
+ const { done, value } = this.#tokenized.next();
374
+ if (!done) throw new SyntaxError(buildErrorMessage(value));
375
+ return res;
376
+ }
377
+ /** Read the next token. If the token is read to the end, it throws a SyntaxError. */ #getNext() {
378
+ const { done, value } = this.#tokenized.next();
379
+ if (done) throw new SyntaxError("Cannot parse JSONC: unexpected end of JSONC input");
380
+ return value;
381
+ }
382
+ /** Split the JSONC string into token units. Whitespace and comments are skipped. */ *#tokenize() {
383
+ for (let i = 0; i < this.#length; i++) {
384
+ if (this.#whitespace.has(this.#text[i])) continue;
385
+ if (this.#text[i] === "/" && this.#text[i + 1] === "*") {
386
+ i += 2;
387
+ let hasEndOfComment = false;
388
+ for (; i < this.#length; i++) if (this.#text[i] === "*" && this.#text[i + 1] === "/") {
389
+ hasEndOfComment = true;
390
+ break;
391
+ }
392
+ if (!hasEndOfComment) throw new SyntaxError("Cannot parse JSONC: unexpected end of JSONC input");
393
+ i++;
394
+ continue;
395
+ }
396
+ if (this.#text[i] === "/" && this.#text[i + 1] === "/") {
397
+ i += 2;
398
+ for (; i < this.#length; i++) if (this.#text[i] === "\n" || this.#text[i] === "\r") break;
399
+ continue;
400
+ }
401
+ switch (this.#text[i]) {
402
+ case "{":
403
+ yield {
404
+ type: "BeginObject",
405
+ position: i
406
+ };
407
+ break;
408
+ case "}":
409
+ yield {
410
+ type: "EndObject",
411
+ position: i
412
+ };
413
+ break;
414
+ case "[":
415
+ yield {
416
+ type: "BeginArray",
417
+ position: i
418
+ };
419
+ break;
420
+ case "]":
421
+ yield {
422
+ type: "EndArray",
423
+ position: i
424
+ };
425
+ break;
426
+ case ":":
427
+ yield {
428
+ type: "NameSeparator",
429
+ position: i
430
+ };
431
+ break;
432
+ case ",":
433
+ yield {
434
+ type: "ValueSeparator",
435
+ position: i
436
+ };
437
+ break;
438
+ case "\"": {
439
+ const startIndex = i;
440
+ let shouldEscapeNext = false;
441
+ i++;
442
+ for (; i < this.#length; i++) {
443
+ if (this.#text[i] === "\"" && !shouldEscapeNext) break;
444
+ shouldEscapeNext = this.#text[i] === "\\" && !shouldEscapeNext;
445
+ }
446
+ yield {
447
+ type: "String",
448
+ sourceText: this.#text.substring(startIndex, i + 1),
449
+ position: startIndex
450
+ };
451
+ break;
452
+ }
453
+ default: {
454
+ const startIndex = i;
455
+ for (; i < this.#length; i++) if (this.#numberEndToken.has(this.#text[i])) break;
456
+ i--;
457
+ yield {
458
+ type: "NullOrTrueOrFalseOrNumber",
459
+ sourceText: this.#text.substring(startIndex, i + 1),
460
+ position: startIndex
461
+ };
462
+ }
463
+ }
464
+ }
465
+ }
466
+ #parseJsonValue(value) {
467
+ switch (value.type) {
468
+ case "BeginObject": return this.#parseObject();
469
+ case "BeginArray": return this.#parseArray();
470
+ case "NullOrTrueOrFalseOrNumber": return this.#parseNullOrTrueOrFalseOrNumber(value);
471
+ case "String": return this.#parseString(value);
472
+ default: throw new SyntaxError(buildErrorMessage(value));
473
+ }
474
+ }
475
+ #parseObject() {
476
+ const target = {};
477
+ while (true) {
478
+ const token1 = this.#getNext();
479
+ if (token1.type === "EndObject") return target;
480
+ if (token1.type !== "String") throw new SyntaxError(buildErrorMessage(token1));
481
+ const key = this.#parseString(token1);
482
+ const token2 = this.#getNext();
483
+ if (token2.type !== "NameSeparator") throw new SyntaxError(buildErrorMessage(token2));
484
+ const token3 = this.#getNext();
485
+ Object.defineProperty(target, key, {
486
+ value: this.#parseJsonValue(token3),
487
+ writable: true,
488
+ enumerable: true,
489
+ configurable: true
490
+ });
491
+ const token4 = this.#getNext();
492
+ if (token4.type === "EndObject") return target;
493
+ if (token4.type !== "ValueSeparator") throw new SyntaxError(buildErrorMessage(token4));
494
+ }
495
+ }
496
+ #parseArray() {
497
+ const target = [];
498
+ while (true) {
499
+ const token1 = this.#getNext();
500
+ if (token1.type === "EndArray") return target;
501
+ target.push(this.#parseJsonValue(token1));
502
+ const token2 = this.#getNext();
503
+ if (token2.type === "EndArray") return target;
504
+ if (token2.type !== "ValueSeparator") throw new SyntaxError(buildErrorMessage(token2));
505
+ }
506
+ }
507
+ #parseString(value) {
508
+ let parsed;
509
+ try {
510
+ parsed = JSON.parse(value.sourceText);
511
+ } catch {
512
+ throw new SyntaxError(buildErrorMessage(value));
513
+ }
514
+ if (typeof parsed !== "string") throw new TypeError(`Parsed value is not a string: ${parsed}`);
515
+ return parsed;
516
+ }
517
+ #parseNullOrTrueOrFalseOrNumber(value) {
518
+ if (value.sourceText === "null") return null;
519
+ if (value.sourceText === "true") return true;
520
+ if (value.sourceText === "false") return false;
521
+ let parsed;
522
+ try {
523
+ parsed = JSON.parse(value.sourceText);
524
+ } catch {
525
+ throw new SyntaxError(buildErrorMessage(value));
526
+ }
527
+ if (typeof parsed !== "number") throw new TypeError(`Parsed value is not a number: ${parsed}`);
528
+ return parsed;
529
+ }
530
+ };
531
+ function buildErrorMessage({ type, sourceText, position }) {
532
+ let token = "";
533
+ switch (type) {
534
+ case "BeginObject":
535
+ token = "{";
536
+ break;
537
+ case "EndObject":
538
+ token = "}";
539
+ break;
540
+ case "BeginArray":
541
+ token = "[";
542
+ break;
543
+ case "EndArray":
544
+ token = "]";
545
+ break;
546
+ case "NameSeparator":
547
+ token = ":";
548
+ break;
549
+ case "ValueSeparator":
550
+ token = ",";
551
+ break;
552
+ case "NullOrTrueOrFalseOrNumber":
553
+ case "String": token = 30 < sourceText.length ? `${sourceText.slice(0, 30)}...` : sourceText;
554
+ }
555
+ return `Cannot parse JSONC: unexpected token "${token}" in JSONC at position ${position}`;
556
+ }
557
+ //#endregion
558
+ //#region src/parse-tsconfig-text.workflow.ts
559
+ const TsconfigTextTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TsconfigText");
560
+ var TsconfigParsed = class extends S.TaggedClass()("TsconfigParsed", { document: TsConfigDocumentSchema }) {
561
+ [TsconfigTextTypeId] = TsconfigTextTypeId;
562
+ };
563
+ var TsconfigRefused = class extends S.TaggedClass()("TsconfigRefused", { reason: S.String }) {
564
+ [TsconfigTextTypeId] = TsconfigTextTypeId;
565
+ };
566
+ const TsconfigTextDecision = S.Union([TsconfigParsed, TsconfigRefused]);
567
+ const reasonOfThrown = (cause) => Option.getOrElse(Option.map(Option.liftPredicate(cause, (error) => error instanceof Error), (error) => error.message), () => "a non-Error value was thrown");
568
+ const documentIssueOf = (value) => new SchemaIssue.InvalidValue({ message: Result.match(S.decodeUnknownResult(TsConfigDocumentSchema)(value), {
569
+ onFailure: (error) => error.message,
570
+ onSuccess: () => "expected a TypeScript configuration object"
571
+ }) });
572
+ const parseJsonc = (jsonText) => Result.match(Result.try({
573
+ try: () => parse(jsonText.replace(/^\uFEFF/, "")),
574
+ catch: (cause) => cause
575
+ }), {
576
+ onFailure: (cause) => Result.fail(new SchemaIssue.InvalidValue({ message: reasonOfThrown(cause) })),
577
+ onSuccess: (value) => Result.mapError(S.decodeUnknownResult(S.Json)(value), (error) => new SchemaIssue.InvalidValue({ message: error.message }))
578
+ });
579
+ const documentOf = (value) => Option.match(Option.liftPredicate(value, S.is(TsConfigDocumentSchema)), {
580
+ onNone: () => Result.fail(documentIssueOf(value)),
581
+ onSome: () => Result.mapError(S.decodeUnknownResult(TsConfigDocumentSchema)(value), (error) => new SchemaIssue.InvalidValue({ message: error.message }))
582
+ });
583
+ const decodeText = (jsonText) => Result.flatMap(parseJsonc(jsonText), documentOf);
584
+ const TsConfigText = S.String.pipe(S.decodeTo(TsConfigDocumentSchema, SchemaTransformation.transformEffect({
585
+ decode: (jsonText) => Result.match(decodeText(jsonText), {
586
+ onFailure: (issue) => Effect.fail(issue),
587
+ onSuccess: (document) => Effect.succeed(document)
588
+ }),
589
+ encode: (document) => Effect.succeed(JSON.stringify(document))
590
+ })));
591
+ const decide$4 = (command) => Result.succeed(Result.match(S.decodeResult(TsConfigText)(command.text), {
592
+ onFailure: (error) => TsconfigRefused.make({ reason: error.message }),
593
+ onSuccess: (document) => TsconfigParsed.make({ document })
594
+ }));
595
+ const parseTsconfigText = Workflow.make({
596
+ command: ParseTsconfigTextCommand,
597
+ decision: TsconfigTextDecision,
598
+ error: S.Never,
599
+ decide: decide$4
600
+ });
601
+ //#endregion
602
+ //#region src/plan-diagnostic-batches.workflow.ts
603
+ const DiagnosticBatchSize = 64;
604
+ const BatchesTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/DiagnosticBatches");
605
+ var DiagnosticBatchesPlanned = class extends S.TaggedClass()("DiagnosticBatchesPlanned", { batches: S.String.pipe(S.Array, S.Array) }) {
606
+ [BatchesTypeId] = BatchesTypeId;
607
+ };
608
+ var NoDiagnosticBatches = class extends S.TaggedClass()("NoDiagnosticBatches", {}) {
609
+ [BatchesTypeId] = BatchesTypeId;
610
+ };
611
+ const DiagnosticBatches = S.Union([DiagnosticBatchesPlanned, NoDiagnosticBatches]);
612
+ const diagnosticBatchesOf = (fileNames) => Arr.chunksOf(fileNames, DiagnosticBatchSize);
613
+ const decide$3 = (command) => Result.succeed(Boolean.match(command.fileNames.length === 0, {
614
+ onTrue: () => NoDiagnosticBatches.make({}),
615
+ onFalse: () => DiagnosticBatchesPlanned.make({ batches: diagnosticBatchesOf(command.fileNames) })
616
+ }));
617
+ const planDiagnosticBatches = Workflow.make({
618
+ command: PlanDiagnosticBatchesCommand,
619
+ decision: DiagnosticBatches,
620
+ error: S.Never,
621
+ decide: decide$3
622
+ });
623
+ //#endregion
624
+ //#region src/plan-resolution-candidates.workflow.ts
625
+ const ExtensionlessTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/ResolutionCandidates");
626
+ var ExtensionNamedPath = class extends S.TaggedClass()("ExtensionNamedPath", { candidates: S.Array(S.String) }) {
627
+ [ExtensionlessTypeId] = ExtensionlessTypeId;
628
+ };
629
+ var ExtensionlessPath = class extends S.TaggedClass()("ExtensionlessPath", { candidates: S.Array(S.String) }) {
630
+ [ExtensionlessTypeId] = ExtensionlessTypeId;
631
+ };
632
+ const ResolutionCandidates = S.Union([ExtensionNamedPath, ExtensionlessPath]);
633
+ const withoutExtensionCandidates = (resolved) => [
634
+ resolved,
635
+ resolved + ".ts",
636
+ resolved + ".tsx",
637
+ resolved + ".d.ts",
638
+ resolved + "/index.ts",
639
+ resolved + "/index.tsx",
640
+ resolved + "/index.d.ts",
641
+ resolved + ".js",
642
+ resolved + ".jsx",
643
+ resolved + ".mjs",
644
+ resolved + ".cjs",
645
+ resolved + "/index.js",
646
+ resolved + "/index.jsx",
647
+ resolved + "/index.mjs",
648
+ resolved + "/index.cjs"
649
+ ];
650
+ const withExtensionCandidates = (resolved, extension) => {
651
+ const withoutExtension = resolved.slice(0, -extension.length);
652
+ return [
653
+ resolved,
654
+ withoutExtension + ".ts",
655
+ withoutExtension + ".tsx",
656
+ withoutExtension + ".d.ts",
657
+ withoutExtension + ".js",
658
+ withoutExtension + ".jsx",
659
+ withoutExtension + ".mjs",
660
+ withoutExtension + ".cjs"
661
+ ];
662
+ };
663
+ const decide$2 = (command) => Result.succeed(Boolean.match(command.extension === "", {
664
+ onTrue: () => ExtensionlessPath.make({ candidates: withoutExtensionCandidates(command.resolved) }),
665
+ onFalse: () => ExtensionNamedPath.make({ candidates: withExtensionCandidates(command.resolved, command.extension) })
666
+ }));
667
+ const planResolutionCandidates = Workflow.make({
668
+ command: PlanResolutionCandidatesCommand,
669
+ decision: ResolutionCandidates,
670
+ error: S.Never,
671
+ decide: decide$2
672
+ });
673
+ //#endregion
674
+ //#region src/request-affected-files.workflow.ts
675
+ const RequestTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/RequestAffectedFiles");
676
+ var AffectedFilesRequested = class extends S.TaggedClass()("AffectedFilesRequested", { fileNames: S.Array(S.String) }) {
677
+ [RequestTypeId] = RequestTypeId;
678
+ };
679
+ var NoAffectedFileRequested = class extends S.TaggedClass()("NoAffectedFileRequested", {}) {
680
+ [RequestTypeId] = RequestTypeId;
681
+ };
682
+ const RequestedFiles = S.Union([AffectedFilesRequested, NoAffectedFileRequested]);
683
+ const requestedFileNames = (presentFileNames, affectedFileNames) => Arr.filter(presentFileNames, (fileName) => HashSet.has(affectedFileNames, fileName));
684
+ const decide$1 = (command) => {
685
+ const requested = requestedFileNames(command.presentFileNames, HashSet.fromIterable(command.affectedFileNames));
686
+ return Result.succeed(Boolean.match(requested.length === 0, {
687
+ onTrue: () => NoAffectedFileRequested.make({}),
688
+ onFalse: () => AffectedFilesRequested.make({ fileNames: requested })
689
+ }));
690
+ };
691
+ const requestAffectedFiles = Workflow.make({
692
+ command: RequestAffectedFilesCommand,
693
+ decision: RequestedFiles,
694
+ error: S.Never,
695
+ decide: decide$1
696
+ });
697
+ //#endregion
698
+ //#region src/trace-affected-files.workflow.ts
699
+ const TraceTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TraceAffectedFiles");
700
+ var MutatedFileAffected = class extends S.TaggedClass()("MutatedFileAffected", { fileName: S.String }) {
701
+ [TraceTypeId] = TraceTypeId;
702
+ };
703
+ var DependentFileAffected = class extends S.TaggedClass()("DependentFileAffected", { fileName: S.String }) {
704
+ [TraceTypeId] = TraceTypeId;
705
+ };
706
+ const AffectedFiles = S.Array(S.Union([MutatedFileAffected, DependentFileAffected]));
707
+ const dependentsOf = (importsByFile) => Arr.reduce(Object.entries(importsByFile), HashMap.empty(), (dependents, [fileName, imports]) => Arr.reduce(imports, dependents, (accumulated, imported) => HashMap.set(accumulated, imported, HashSet.add(Option.getOrElse(HashMap.get(accumulated, imported), () => HashSet.empty()), fileName))));
708
+ const dependentsOfFile = (dependents, fileName) => Option.getOrElse(HashMap.get(dependents, fileName), () => HashSet.empty());
709
+ const closeOverDependents = (dependents, affected) => {
710
+ const grown = HashSet.union(affected, HashSet.fromIterable(Arr.flatMap(Arr.fromIterable(affected), (fileName) => Arr.fromIterable(dependentsOfFile(dependents, fileName)))));
711
+ return Boolean.match(HashSet.size(grown) === HashSet.size(affected), {
712
+ onTrue: () => grown,
713
+ onFalse: () => closeOverDependents(dependents, grown)
714
+ });
715
+ };
716
+ const affectedEvents = (seed, affected) => Arr.map(Arr.fromIterable(affected), (fileName) => Boolean.match(HashSet.has(seed, fileName), {
717
+ onTrue: () => MutatedFileAffected.make({ fileName }),
718
+ onFalse: () => DependentFileAffected.make({ fileName })
719
+ }));
720
+ const decide = (command) => {
721
+ const seed = HashSet.fromIterable(command.mutatedFileNames);
722
+ return Result.succeed(affectedEvents(seed, closeOverDependents(dependentsOf(command.importsByFile), seed)));
723
+ };
724
+ const traceAffectedFiles = Workflow.make({
725
+ command: TraceAffectedFilesCommand,
726
+ decision: AffectedFiles,
727
+ error: S.Never,
728
+ decide
729
+ });
730
+ //#endregion
731
+ //#region src/ts-files.handle.ts
732
+ const TypeId$2 = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TSFiles");
733
+ const normalizeFileName$1 = (fileName) => fileName.replace(/\\/g, "/");
734
+ const isBuildInfoFile = (fileName) => normalizeFileName$1(fileName).endsWith(".tsbuildinfo");
735
+ const TSFiles = Handle.make()(TypeId$2);
736
+ TSFiles.is;
737
+ const stateOf = (self) => TSFiles.slot(self);
738
+ const emptySources = {
739
+ files: HashMap.empty(),
740
+ overrides: HashMap.empty()
741
+ };
742
+ const make$2 = (host) => TSFiles.make({}, {
743
+ host,
744
+ snapshot: { current: emptySources }
745
+ });
746
+ const publish = (state, next) => Effect.sync(() => {
747
+ state.snapshot.current = next(state.snapshot.current);
748
+ });
749
+ const makeScriptFile = (content, fileName, now) => ({
750
+ content,
751
+ fileName,
752
+ originalContent: content,
753
+ modifiedTime: now,
754
+ lineStarts: lineStartsOf(content)
755
+ });
756
+ const withContent = (file, content, now) => ({
757
+ ...file,
758
+ content,
759
+ modifiedTime: now
760
+ });
761
+ const mutateScriptFile = (file, mutant, now) => Option.map(Option.all([offsetAt(file.lineStarts, mutant.location.start), offsetAt(file.lineStarts, mutant.location.end)]), ([start, end]) => withContent(file, file.originalContent.slice(0, start) + mutant.replacement + file.originalContent.slice(end), now));
762
+ const resetScriptFile = (file, now) => ({
763
+ ...file,
764
+ content: file.originalContent,
765
+ modifiedTime: now
766
+ });
767
+ const now = Effect.map(Clock.currentTimeMillis, DateTime.makeUnsafe);
768
+ const readFromDisk = Effect.fnUntraced(function* (state, fileName) {
769
+ const at = yield* now;
770
+ const file = Option.map(yield* Effect.option(state.host.readFileString(fileName)), (content) => makeScriptFile(content, fileName, at));
771
+ yield* publish(state, (sources) => ({
772
+ ...sources,
773
+ files: HashMap.set(sources.files, fileName, file)
774
+ }));
775
+ return file;
776
+ });
777
+ const getFile = dual(2, (self, fileName) => {
778
+ const state = stateOf(self);
779
+ const normalized = normalizeFileName$1(fileName);
780
+ return Option.match(HashMap.get(state.snapshot.current.files, normalized), {
781
+ onNone: () => readFromDisk(state, normalized),
782
+ onSome: Effect.succeed
783
+ });
784
+ });
785
+ const mutateFile = dual(3, Effect.fnUntraced(function* (self, fileName, mutant) {
786
+ const state = stateOf(self);
787
+ const at = yield* now;
788
+ const file = yield* getFile(self, fileName);
789
+ yield* Option.match(file, {
790
+ onNone: () => Effect.fail(HybridFileNotFoundError.make({ fileName })),
791
+ onSome: (found) => Option.match(mutateScriptFile(found, mutant, at), {
792
+ onNone: () => Effect.fail(HybridMutantOutsideFileError.make({ fileName })),
793
+ onSome: (mutated) => publish(state, (sources) => ({
794
+ ...sources,
795
+ files: HashMap.set(sources.files, normalizeFileName$1(fileName), Option.some(mutated))
796
+ }))
797
+ })
798
+ });
799
+ }));
800
+ const resetFile = dual(2, Effect.fnUntraced(function* (self, fileName) {
801
+ const state = stateOf(self);
802
+ const at = yield* now;
803
+ const normalized = normalizeFileName$1(fileName);
804
+ yield* Option.match(HashMap.get(state.snapshot.current.files, normalized), {
805
+ onNone: () => Effect.void,
806
+ onSome: Option.match({
807
+ onNone: () => Effect.void,
808
+ onSome: (file) => publish(state, (sources) => ({
809
+ ...sources,
810
+ files: HashMap.set(sources.files, normalized, Option.some(resetScriptFile(file, at)))
811
+ }))
812
+ })
813
+ });
814
+ }));
815
+ const setOverrides = dual(2, (self, overrides) => publish(stateOf(self), (sources) => ({
816
+ ...sources,
817
+ overrides
818
+ })));
819
+ const tsFileSystem = (self) => {
820
+ const state = stateOf(self);
821
+ const contentFromSources = (fileName) => Option.match(HashMap.get(state.snapshot.current.overrides, fileName), {
822
+ onSome: (override) => override,
823
+ onNone: () => Option.match(HashMap.get(state.snapshot.current.files, fileName), {
824
+ onNone: () => void 0,
825
+ onSome: Option.match({
826
+ onNone: () => null,
827
+ onSome: (file) => file.content
828
+ })
829
+ })
830
+ });
831
+ const existsInSources = (fileName) => Option.match(HashMap.get(state.snapshot.current.overrides, fileName), {
832
+ onSome: () => true,
833
+ onNone: () => Option.match(HashMap.get(state.snapshot.current.files, fileName), {
834
+ onNone: () => void 0,
835
+ onSome: Option.isSome
836
+ })
837
+ });
838
+ return {
839
+ readFile: (fileName) => Boolean.match(isBuildInfoFile(fileName), {
840
+ onTrue: () => null,
841
+ onFalse: () => contentFromSources(normalizeFileName$1(fileName))
842
+ }),
843
+ fileExists: (fileName) => Boolean.match(isBuildInfoFile(fileName), {
844
+ onTrue: () => false,
845
+ onFalse: () => existsInSources(normalizeFileName$1(fileName))
846
+ }),
847
+ directoryExists: () => void 0,
848
+ getAccessibleEntries: () => void 0,
849
+ realpath: () => void 0
850
+ };
851
+ };
852
+ //#endregion
853
+ //#region src/ts-compiler.handle.ts
854
+ const TypeId$1 = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TSCompiler");
855
+ const normalizeFileName = (fileName) => fileName.replace(/\\/g, "/");
856
+ const findSourceMapRegex = /\/\/# sourceMappingURL=(.+)$/m;
857
+ const getSourceMappingURL = (content) => findSourceMapRegex.exec(content)?.[1];
858
+ const isString = (value) => typeof value === "string";
859
+ const isNonEmptyString = (value) => value !== void 0 && value !== "";
860
+ const relativeSpecifierPattern = /^\.\.?\//;
861
+ const CLEAN_SPECIFIER_PATTERN = /^["']|["']$/g;
862
+ const ignoredGraphFileNamePattern = /\.d\.ts$|node_modules/;
863
+ const TSCompiler = Handle.make()(TypeId$1);
864
+ TSCompiler.is;
865
+ const runtimeOf = (self) => TSCompiler.slot(self);
866
+ const decided = (result) => Result.match(result, {
867
+ onFailure: (refused) => refused,
868
+ onSuccess: (decision) => decision
869
+ });
870
+ const make$1 = dual(2, Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerMake.name)(function* (options, services) {
871
+ const files = make$2(services.host);
872
+ const tsconfigFile = normalizeFileName(options.tsconfigFile);
873
+ const state = yield* SynchronizedRef.make({
874
+ api: void 0,
875
+ snapshot: void 0,
876
+ sourceFiles: HashMap.empty(),
877
+ nodes: HashMap.empty(),
878
+ lastMutants: [],
879
+ lastMutatedFileNames: [],
880
+ aliases: [],
881
+ allTSConfigFiles: HashSet.fromIterable([tsconfigFile]),
882
+ tsconfigFile
883
+ });
884
+ return TSCompiler.make({}, {
885
+ options,
886
+ host: services.host,
887
+ pathService: services.pathService,
888
+ files,
889
+ sourceFileSystem: tsFileSystem(files),
890
+ state
891
+ });
892
+ }));
893
+ const minimumTypeScriptVersion = {
894
+ major: 7,
895
+ minor: 0,
896
+ patch: 0
897
+ };
898
+ const versionComponent = (parts, index) => Number.parseInt(parts[index] ?? "0", 10);
899
+ const splitVersion = (version) => {
900
+ const parts = version.replace(/[-+][\s\S]*$/, "").split(".");
901
+ return {
902
+ major: versionComponent(parts, 0),
903
+ minor: versionComponent(parts, 1),
904
+ patch: versionComponent(parts, 2)
905
+ };
906
+ };
907
+ const isNewerOrSame = (left, right) => {
908
+ return ([
909
+ left.major - right.major,
910
+ left.minor - right.minor,
911
+ left.patch - right.patch
912
+ ].find((difference) => difference !== 0) ?? 0) >= 0;
913
+ };
914
+ const isSupportedTypeScriptVersion = (version) => {
915
+ const parsed = splitVersion(version);
916
+ return [
917
+ parsed.major,
918
+ parsed.minor,
919
+ parsed.patch
920
+ ].every((part) => !Number.isNaN(part)) && isNewerOrSame(parsed, minimumTypeScriptVersion);
921
+ };
922
+ const readTypescriptVersion = Effect.fnUntraced(function* (rt) {
923
+ const packagePath = yield* rt.pathService.fromFileUrl(new URL(import.meta.resolve("typescript/package.json")));
924
+ const text = yield* rt.host.readFileString(packagePath);
925
+ return Result.match(S.decodeResult(S.fromJsonString(S.Struct({ version: S.String })))(text), {
926
+ onFailure: () => "",
927
+ onSuccess: (pkg) => pkg.version
928
+ });
929
+ });
930
+ const guardTypescriptVersion = (rt) => Effect.flatMap(readTypescriptVersion(rt).pipe(Effect.orElseSucceed(() => "")), (version) => Boolean.match(isSupportedTypeScriptVersion(version), {
931
+ onFalse: () => Effect.fail(UnsupportedTypeScriptVersionError.make({ version })),
932
+ onTrue: () => Effect.void
933
+ }));
934
+ const parseTsConfig = (fileName, jsonText) => parseTsconfigText(ParseTsconfigTextCommand.make({ text: jsonText })).pipe(decided, Match.value, Match.tag("TsconfigParsed", ({ document }) => Result.succeed(document)), Match.tag("TsconfigRefused", ({ reason }) => Result.fail(TsConfigParseError.make({
935
+ file: fileName,
936
+ reason
937
+ }))), Match.exhaustive);
938
+ const tsconfigDeclaresReferences = (fileName, jsonText) => Result.match(parseTsConfig(fileName, jsonText), {
939
+ onFailure: () => false,
940
+ onSuccess: (config) => config["references"] !== void 0
941
+ });
942
+ const overrideTextOf = (document, buildMode) => decided(overrideTsconfigOptions(OverrideTsconfigOptionsCommand.make({
943
+ document,
944
+ buildMode
945
+ }))).text;
946
+ const tsConfigReferencesOf = (config) => Option.getOrElse(Option.fromUndefinedOr(config.references), () => []);
947
+ const referencedProjectsOf = (rt, config, fromDirName) => Arr.map(tsConfigReferencesOf(config), (reference) => {
948
+ const resolved = rt.pathService.resolve(fromDirName, reference.path);
949
+ return normalizeFileName(Boolean.match(rt.pathService.basename(resolved).endsWith(".json"), {
950
+ onTrue: () => resolved,
951
+ onFalse: () => rt.pathService.join(resolved, "tsconfig.json")
952
+ }));
953
+ });
954
+ const compilerOptionsOf = (config) => Option.getOrElse(Option.fromUndefinedOr(config.compilerOptions), () => ({}));
955
+ const aliasEntriesOf = (compilerOptions) => Object.entries(Option.getOrElse(S.decodeUnknownOption(PathAliasesSchema)(compilerOptions["paths"]), () => ({})));
956
+ const pathAliasesOf = (pathService, fileName, config) => aliasEntriesOf(compilerOptionsOf(config)).map(([pattern, targets]) => ({
957
+ pattern,
958
+ targets,
959
+ baseDir: pathService.dirname(fileName)
960
+ }));
961
+ const recordTsConfig = (rt, buildMode, walk, fileName, jsonText) => Result.match(parseTsConfig(fileName, jsonText), {
962
+ onFailure: () => ({
963
+ ...walk,
964
+ overrides: HashMap.set(walk.overrides, fileName, jsonText)
965
+ }),
966
+ onSuccess: (config) => ({
967
+ overrides: HashMap.set(walk.overrides, fileName, overrideTextOf(config, buildMode)),
968
+ aliases: [...walk.aliases, ...pathAliasesOf(rt.pathService, fileName, config)],
969
+ files: Arr.reduce(referencedProjectsOf(rt, config, rt.pathService.dirname(fileName)), walk.files, (files, referenced) => HashSet.add(files, normalizeFileName(referenced))),
970
+ processed: walk.processed
971
+ })
972
+ });
973
+ const enqueueUnseen = (walk, pending) => Arr.reduce(Arr.fromIterable(walk.files), pending, (queued, fileName) => Boolean.match(HashSet.has(walk.processed, fileName) || queued.includes(fileName), {
974
+ onTrue: () => queued,
975
+ onFalse: () => [...queued, fileName]
976
+ }));
977
+ const readTsConfigText = (rt, preRead, fileName) => Option.match(HashMap.get(preRead, fileName), {
978
+ onNone: () => rt.host.readFileString(fileName).pipe(Effect.mapError(() => TsConfigNotFoundError.make({ file: fileName }))),
979
+ onSome: (jsonText) => Effect.succeed(jsonText)
980
+ });
981
+ const walkTsConfigs = (rt, buildMode, walk, pending, preRead) => Option.match(Option.filter(Arr.head(pending), (fileName) => !HashSet.has(walk.processed, fileName)), {
982
+ onNone: () => Effect.succeed(walk),
983
+ onSome: (fileName) => Effect.flatMap(readTsConfigText(rt, preRead, fileName), (jsonText) => {
984
+ const recorded = recordTsConfig(rt, buildMode, {
985
+ ...walk,
986
+ processed: HashSet.add(walk.processed, fileName)
987
+ }, fileName, jsonText);
988
+ return walkTsConfigs(rt, buildMode, recorded, enqueueUnseen(recorded, pending.slice(1)), preRead);
989
+ })
990
+ });
991
+ const snapshotOf = (state) => Effect.fromOption(Option.fromUndefinedOr(state.snapshot), () => CompilerFailed.make({ reason: "not-initialized" }));
992
+ const projectsOf = (rt) => Effect.flatMap(SynchronizedRef.get(rt.state), (state) => Effect.flatMap(snapshotOf(state), (snapshot) => {
993
+ const projects = snapshot.getProjects();
994
+ return Boolean.match(projects.length === 0, {
995
+ onTrue: () => Effect.fail(CompilerFailed.make({
996
+ reason: "no-projects",
997
+ subject: state.tsconfigFile
998
+ })),
999
+ onFalse: () => Effect.succeed(projects)
1000
+ });
1001
+ }));
1002
+ const programsOf = (rt) => Effect.map(projectsOf(rt), (projects) => Arr.map(projects, (project) => project.program));
1003
+ const resolveFileName = (rt, fileName) => normalizeFileName(rt.pathService.resolve(fileName));
1004
+ const nodeSpanOf = (node) => ({
1005
+ start: node.getStart(node.getSourceFile()),
1006
+ end: node.end
1007
+ });
1008
+ const childrenOf = (node) => {
1009
+ const children = [];
1010
+ node.forEachChild((child) => {
1011
+ children.push(child);
1012
+ });
1013
+ return children;
1014
+ };
1015
+ const spanEqualsOf = (node, start, end) => {
1016
+ const span = nodeSpanOf(node);
1017
+ return span.start === start && span.end === end;
1018
+ };
1019
+ const spanContainsOf = (node, start, end) => {
1020
+ const span = nodeSpanOf(node);
1021
+ return span.start <= start && end <= span.end;
1022
+ };
1023
+ const hasSpanOf = (node, start, end) => {
1024
+ if (spanEqualsOf(node, start, end)) return true;
1025
+ return Arr.some(childrenOf(node), (child) => Boolean.and(spanContainsOf(child, start, end), hasSpanOf(child, start, end)));
1026
+ };
1027
+ const parseHeldOf = (sourceFile, file, mutant) => Option.match(offsetAt(file.lineStarts, mutant.location.start), {
1028
+ onNone: () => true,
1029
+ onSome: (start) => hasSpanOf(sourceFile, start, start + mutant.replacement.length)
1030
+ });
1031
+ const mutatedSourceFileOf = (rt, fileName) => Effect.flatMap(projectsOf(rt), (projects) => Effect.map(projectOfFile(projects, fileName), (owned) => Option.map(owned, (found) => found.sourceFile)));
1032
+ const parseHeldAfterSpliceOf = (rt, file, mutant, fileName) => Effect.gen(function* () {
1033
+ const sourceFile = yield* mutatedSourceFileOf(rt, fileName);
1034
+ return Option.match(Option.all([file, sourceFile]), {
1035
+ onNone: () => true,
1036
+ onSome: ([spliced, mutated]) => parseHeldOf(mutated, spliced, mutant)
1037
+ });
1038
+ });
1039
+ const parenthesizedSpliceOf = (rt, mutant, fileName, changedFiles) => Effect.flatMap(applyMutant(rt, mutant, "(" + mutant.replacement + ")"), () => refreshSnapshot(rt, changedFiles));
1040
+ const applyMutant = (rt, mutant, replacement) => Effect.flatMap(getFile(rt.files, resolveFileName(rt, mutant.fileName)), (file) => Effect.flatMap(Effect.fromOption(file, () => CompilerFailed.make({
1041
+ reason: "file-not-in-project",
1042
+ subject: mutant.fileName
1043
+ })), () => Effect.mapError(mutateFile(rt.files, resolveFileName(rt, mutant.fileName), {
1044
+ location: mutant.location,
1045
+ replacement
1046
+ }), (error) => Match.value(error).pipe(Match.tag("HybridFileNotFoundError", () => CompilerFailed.make({
1047
+ reason: "file-not-in-project",
1048
+ subject: mutant.fileName
1049
+ })), Match.tag("HybridMutantOutsideFileError", () => CompilerFailed.make({
1050
+ reason: "mutant-outside-file",
1051
+ subject: mutant.fileName
1052
+ })), Match.exhaustive))));
1053
+ const resetMutatedFiles = (rt, mutants) => Effect.forEach(mutants, (mutant) => resetFile(rt.files, resolveFileName(rt, mutant.fileName)), { discard: true });
1054
+ const hasOpenSnapshot = (state) => state.api !== void 0 && state.snapshot !== void 0;
1055
+ const updateSnapshot = Effect.fnUntraced(function* (rt, initialized, changedFiles) {
1056
+ const next = yield* Effect.promise(() => initialized.api.updateSnapshot({
1057
+ openProjects: Array.from(initialized.allTSConfigFiles),
1058
+ fileChanges: { changed: [...changedFiles] }
1059
+ }));
1060
+ yield* Effect.promise(() => initialized.snapshot.dispose());
1061
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
1062
+ ...prev,
1063
+ snapshot: next
1064
+ }));
1065
+ });
1066
+ const refreshSnapshot = (rt, changedFiles) => Effect.flatMap(SynchronizedRef.get(rt.state), (current) => Option.match(Option.liftPredicate(current, hasOpenSnapshot), {
1067
+ onNone: () => Effect.void,
1068
+ onSome: (initialized) => updateSnapshot(rt, initialized, changedFiles)
1069
+ }));
1070
+ const annotateDiagnosticSample = (diagnostics) => Boolean.match(diagnostics.length === 0, {
1071
+ onTrue: () => Effect.void,
1072
+ onFalse: () => Effect.annotateCurrentSpan({ "typescript.diagnostics.sample": Arr.map(Arr.take(diagnostics, 10), (diagnostic) => diagnostic.fileName + ":" + diagnostic.code + ": " + diagnostic.text).join("; ") })
1073
+ });
1074
+ const carriesModuleSpecifier = (statement) => statement.kind === SyntaxKind.ImportDeclaration || statement.kind === SyntaxKind.ExportDeclaration;
1075
+ const moduleSpecifierOf = (statement, sourceFile) => Boolean.match(carriesModuleSpecifier(statement), {
1076
+ onTrue: () => {
1077
+ const children = [];
1078
+ statement.forEachChild((child) => {
1079
+ children.push(child);
1080
+ });
1081
+ return Option.map(Arr.findLast(children, (child) => child.kind === SyntaxKind.StringLiteral), (literal) => literal.getText(sourceFile));
1082
+ },
1083
+ onFalse: () => Option.none()
1084
+ });
1085
+ const keepSome = (option) => Option.match(option, {
1086
+ onNone: () => Result.failVoid,
1087
+ onSome: Result.succeed
1088
+ });
1089
+ const importsOf = (sourceFile) => [
1090
+ ...Arr.filterMap(sourceFile.statements, (statement) => keepSome(moduleSpecifierOf(statement, sourceFile))),
1091
+ ...Arr.map(sourceFile.referencedFiles, (reference) => reference.fileName),
1092
+ ...Arr.map(sourceFile.typeReferenceDirectives, (reference) => reference.fileName)
1093
+ ];
1094
+ const aliasTargetPaths = (pathService, aliases, specifier) => Arr.flatMap(aliases, (alias) => {
1095
+ const command = CaptureAliasSpecifierCommand.make({
1096
+ pattern: alias.pattern,
1097
+ specifier
1098
+ });
1099
+ const decision = decided(captureAliasSpecifier(command));
1100
+ return Match.value(decision).pipe(Match.tag("AliasSpecifierCaptured", ({ capture }) => Arr.map(alias.targets, (target) => normalizeFileName(pathService.resolve(alias.baseDir, target.replace("*", capture))))), Match.tag("AliasSpecifierUnmatched", () => []), Match.exhaustive);
1101
+ });
1102
+ const candidatePathsOf = (pathService, resolved) => {
1103
+ const command = PlanResolutionCandidatesCommand.make({
1104
+ resolved,
1105
+ extension: pathService.extname(resolved)
1106
+ });
1107
+ const decision = decided(planResolutionCandidates(command));
1108
+ return Match.value(decision).pipe(Match.tag("ExtensionNamedPath", ({ candidates }) => candidates), Match.tag("ExtensionlessPath", ({ candidates }) => candidates), Match.exhaustive);
1109
+ };
1110
+ const existingCandidateOf = (pathService, sourceFiles, resolved) => Arr.findFirst(candidatePathsOf(pathService, resolved), (candidate) => HashMap.has(sourceFiles, candidate));
1111
+ const resolveAliasedSpecifier = (pathService, aliases, sourceFiles, specifier) => Option.firstSomeOf(Arr.map(aliasTargetPaths(pathService, aliases, specifier), (target) => existingCandidateOf(pathService, sourceFiles, target)));
1112
+ const resolveSpecifier = (pathService, aliases, sourceFiles, fileName, specifier) => {
1113
+ const cleaned = specifier.replace(CLEAN_SPECIFIER_PATTERN, "");
1114
+ return Boolean.match(relativeSpecifierPattern.test(cleaned), {
1115
+ onFalse: () => resolveAliasedSpecifier(pathService, aliases, sourceFiles, cleaned),
1116
+ onTrue: () => Option.filter(existingCandidateOf(pathService, sourceFiles, normalizeFileName(pathService.resolve(pathService.dirname(fileName), cleaned))), (candidate) => candidate !== "")
1117
+ });
1118
+ };
1119
+ const readFileText = (rt, fileName) => Option.liftPredicate(rt.sourceFileSystem.readFile?.(fileName), isString);
1120
+ const onlySourceOf = (sources) => Boolean.match(sources.length !== 1, {
1121
+ onTrue: () => Option.none(),
1122
+ onFalse: () => Option.fromUndefinedOr(sources[0])
1123
+ });
1124
+ const sourceMapSourcesOf = (rt, content) => Result.match(S.decodeResult(S.fromJsonString(S.Struct({ sources: S.Array(S.String) })))(content), {
1125
+ onFailure: () => Option.none(),
1126
+ onSuccess: (map) => onlySourceOf(map.sources)
1127
+ });
1128
+ const sourceMappedFileName = (rt, declarationFileName) => Option.flatMap(Option.flatMap(readFileText(rt, declarationFileName), (content) => Option.liftPredicate(getSourceMappingURL(content), isNonEmptyString)), (reference) => {
1129
+ const sourceMapFileName = normalizeFileName(rt.pathService.resolve(rt.pathService.dirname(declarationFileName), reference));
1130
+ return Option.flatMap(Option.flatMap(readFileText(rt, sourceMapFileName), (content) => sourceMapSourcesOf(rt, content)), (source) => Option.some(normalizeFileName(rt.pathService.resolve(rt.pathService.dirname(sourceMapFileName), source))));
1131
+ });
1132
+ const resolveTSInputFile = (rt, dependencyFileName) => Boolean.match(dependencyFileName.endsWith(".d.ts"), {
1133
+ onFalse: () => dependencyFileName,
1134
+ onTrue: () => Option.getOrElse(sourceMappedFileName(rt, dependencyFileName), () => dependencyFileName)
1135
+ });
1136
+ const registeredEntry = (fileName) => Boolean.match(ignoredGraphFileNamePattern.test(fileName), {
1137
+ onTrue: () => Option.none(),
1138
+ onFalse: () => {
1139
+ const normalized = normalizeFileName(fileName);
1140
+ return Option.some([normalized, {
1141
+ fileName: normalized,
1142
+ imports: HashSet.empty()
1143
+ }]);
1144
+ }
1145
+ });
1146
+ const registerOwners = (owners, program, fileNames) => Arr.reduce(fileNames, owners, (accumulated, fileName) => {
1147
+ const normalized = normalizeFileName(fileName);
1148
+ return Boolean.match(HashMap.has(accumulated, normalized), {
1149
+ onTrue: () => accumulated,
1150
+ onFalse: () => HashMap.set(accumulated, normalized, program)
1151
+ });
1152
+ });
1153
+ const sourceFileIn = (program, fileName) => Effect.map(Effect.promise(() => program.getSourceFile(fileName)), (found) => Option.fromUndefinedOr(found));
1154
+ const sourceFileOf = (programs, fileName) => Option.match(Arr.head(programs), {
1155
+ onNone: () => Effect.succeed(Option.none()),
1156
+ onSome: (program) => Effect.filterOrElse(sourceFileIn(program, fileName), Option.isSome, () => sourceFileOf(Arr.drop(programs, 1), fileName))
1157
+ });
1158
+ const linkImport = (rt, aliases, sourceFiles, fileName, specifier) => Option.match(Option.filter(resolveSpecifier(rt.pathService, aliases, sourceFiles, fileName, specifier), (resolved) => resolved !== ""), {
1159
+ onNone: () => sourceFiles,
1160
+ onSome: (resolved) => {
1161
+ const imported = resolveTSInputFile(rt, resolved);
1162
+ return Boolean.match(HashMap.has(sourceFiles, imported), {
1163
+ onFalse: () => sourceFiles,
1164
+ onTrue: () => Option.match(HashMap.get(sourceFiles, fileName), {
1165
+ onNone: () => sourceFiles,
1166
+ onSome: (entry) => HashMap.set(sourceFiles, fileName, {
1167
+ ...entry,
1168
+ imports: HashSet.add(entry.imports, imported)
1169
+ })
1170
+ })
1171
+ });
1172
+ }
1173
+ });
1174
+ const ownedSourceFileOf = (owners, programs, fileName) => Option.match(HashMap.get(owners, fileName), {
1175
+ onNone: () => sourceFileOf(programs, fileName),
1176
+ onSome: (owner) => Effect.filterOrElse(sourceFileIn(owner, fileName), Option.isSome, () => sourceFileOf(programs, fileName))
1177
+ });
1178
+ const buildGraph = Effect.fnUntraced(function* (rt, programs) {
1179
+ const state = yield* SynchronizedRef.get(rt.state);
1180
+ const owners = yield* Effect.reduce(programs, () => HashMap.empty(), (accumulated, program) => Effect.map(Effect.promise(() => program.getSourceFileNames()), (fileNames) => registerOwners(accumulated, program, fileNames)));
1181
+ const registered = owners.pipe(Arr.fromIterable, Arr.filterMap(([fileName]) => keepSome(registeredEntry(fileName))), HashMap.fromIterable);
1182
+ const linked = yield* Effect.reduce(Arr.fromIterable(registered), () => registered, (sourceFiles, [fileName]) => Effect.map(ownedSourceFileOf(owners, programs, fileName), (found) => Option.match(found, {
1183
+ onNone: () => sourceFiles,
1184
+ onSome: (sourceFile) => Arr.reduce(importsOf(sourceFile), sourceFiles, (accumulated, specifier) => linkImport(rt, state.aliases, accumulated, fileName, specifier))
1185
+ })));
1186
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
1187
+ ...prev,
1188
+ sourceFiles: linked
1189
+ }));
1190
+ });
1191
+ const fileNode = (fileName, children, parents = []) => ({
1192
+ children,
1193
+ fileName,
1194
+ parents
1195
+ });
1196
+ const importersOf = (sourceFiles) => Arr.reduce(Arr.fromIterable(sourceFiles), HashMap.empty(), (accumulated, [importer, file]) => Arr.reduce(Arr.fromIterable(file.imports), accumulated, (into, imported) => HashMap.set(into, imported, [...Option.getOrElse(HashMap.get(into, imported), () => []), importer])));
1197
+ const graphNodesOf = (sourceFiles) => {
1198
+ const entries = Arr.fromIterable(sourceFiles);
1199
+ const importers = importersOf(sourceFiles);
1200
+ const leaves = HashMap.fromIterable(Arr.map(entries, ([fileName]) => [fileName, fileNode(fileName, [])]));
1201
+ return HashMap.fromIterable(Arr.map(entries, ([fileName, file]) => [fileName, fileNode(fileName, Arr.filterMap(Arr.fromIterable(file.imports), (imported) => keepSome(HashMap.get(leaves, imported))), Arr.filterMap(Option.getOrElse(HashMap.get(importers, fileName), () => []), (importer) => keepSome(HashMap.get(leaves, importer))))]));
1202
+ };
1203
+ const nodesOf = (rt) => Effect.flatMap(SynchronizedRef.get(rt.state), (state) => Boolean.match(HashMap.isEmpty(state.nodes), {
1204
+ onFalse: () => Effect.succeed(state.nodes),
1205
+ onTrue: () => {
1206
+ const nodes = graphNodesOf(state.sourceFiles);
1207
+ return Effect.as(SynchronizedRef.update(rt.state, (prev) => ({
1208
+ ...prev,
1209
+ nodes
1210
+ })), nodes);
1211
+ }
1212
+ }));
1213
+ const init = Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerInit.name)(function* (self) {
1214
+ const rt = runtimeOf(self);
1215
+ yield* guardTypescriptVersion(rt);
1216
+ const tsconfigFile = normalizeFileName(rt.pathService.resolve(rt.options.tsconfigFile));
1217
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
1218
+ ...prev,
1219
+ tsconfigFile,
1220
+ allTSConfigFiles: HashSet.fromIterable([tsconfigFile])
1221
+ }));
1222
+ const tsconfigText = yield* Effect.mapError(rt.host.readFileString(tsconfigFile), () => TsConfigNotFoundError.make({ file: tsconfigFile }));
1223
+ const buildMode = tsconfigDeclaresReferences(tsconfigFile, tsconfigText);
1224
+ const walk = yield* walkTsConfigs(rt, buildMode, {
1225
+ files: HashSet.fromIterable([tsconfigFile]),
1226
+ overrides: HashMap.empty(),
1227
+ processed: HashSet.empty(),
1228
+ aliases: []
1229
+ }, [tsconfigFile], HashMap.fromIterable([[tsconfigFile, tsconfigText]]));
1230
+ yield* setOverrides(rt.files, walk.overrides);
1231
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
1232
+ ...prev,
1233
+ allTSConfigFiles: walk.files,
1234
+ aliases: walk.aliases
1235
+ }));
1236
+ const api = new API({ fs: rt.sourceFileSystem });
1237
+ const snapshot = yield* Effect.promise(() => api.updateSnapshot({ openProjects: Array.from(walk.files) }));
1238
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
1239
+ ...prev,
1240
+ api,
1241
+ snapshot
1242
+ }));
1243
+ const programs = yield* programsOf(rt);
1244
+ yield* buildGraph(rt, programs);
1245
+ return yield* dryRunDiagnostics(programs);
1246
+ });
1247
+ const semanticDiagnosticsOf = Effect.fnUntraced(function* (program, affectedFileNames) {
1248
+ const presentFileNames = yield* Effect.promise(() => program.getSourceFileNames());
1249
+ const request = RequestAffectedFilesCommand.make({
1250
+ affectedFileNames: Arr.fromIterable(affectedFileNames),
1251
+ presentFileNames: [...presentFileNames]
1252
+ });
1253
+ const requested = decided(requestAffectedFiles(request));
1254
+ const batchPlan = PlanDiagnosticBatchesCommand.make({ fileNames: Match.value(requested).pipe(Match.tag("AffectedFilesRequested", ({ fileNames }) => fileNames), Match.tag("NoAffectedFileRequested", () => []), Match.exhaustive) });
1255
+ const batches = decided(planDiagnosticBatches(batchPlan));
1256
+ const plannedBatches = Match.value(batches).pipe(Match.tag("DiagnosticBatchesPlanned", ({ batches }) => batches), Match.tag("NoDiagnosticBatches", () => []), Match.exhaustive);
1257
+ return [...yield* Effect.forEach(plannedBatches, (batch) => Effect.map(Effect.promise(() => Promise.all(Arr.map(batch, (fileName) => program.getSemanticDiagnostics(fileName)))), (perFile) => Arr.flatten(perFile)), { concurrency: 1 })].flat();
1258
+ });
1259
+ const programWideDiagnosticsOf = (program) => Effect.map(Effect.promise(() => Promise.all([program.getConfigFileParsingDiagnostics(), program.getProgramDiagnostics()])), ([config, programWide]) => [...config, ...programWide]);
1260
+ const wholeProgramDiagnosticsOf = (program) => Effect.all([programWideDiagnosticsOf(program), Effect.promise(() => program.getSemanticDiagnostics())], { concurrency: 2 }).pipe(Effect.map(([programWide, semantic]) => [...semantic, ...programWide]));
1261
+ const dryRunDiagnostics = Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerDryRun.name)(function* (programs) {
1262
+ yield* Effect.annotateCurrentSpan({ "typescript.projects.count": programs.length });
1263
+ return errorDiagnosticsOf(Arr.flatten(yield* Effect.forEach(programs, (program) => wholeProgramDiagnosticsOf(program))));
1264
+ });
1265
+ const errorDiagnosticsOf = (diagnostics) => Arr.filter(diagnostics, (diagnostic) => diagnostic.category === DiagnosticCategory.Error);
1266
+ const projectOfFile = (projects, fileName) => Option.match(Arr.head(projects), {
1267
+ onNone: () => Effect.succeedNone,
1268
+ onSome: (project) => Effect.flatMap(Effect.promise(() => project.program.getSourceFile(fileName)), (sourceFile) => Option.match(Option.fromUndefinedOr(sourceFile), {
1269
+ onNone: () => projectOfFile(Arr.drop(projects, 1), fileName),
1270
+ onSome: (found) => Effect.succeedSome({
1271
+ project,
1272
+ sourceFile: found
1273
+ })
1274
+ }))
1275
+ });
1276
+ const isAmbientGlobal = (sourceFile, statement) => isModuleDeclaration(statement) ? Boolean.and((statement.modifierFlags & ModifierFlags.Ambient) !== 0, statement.name.getText(sourceFile) === "global") : false;
1277
+ const declaresGlobalScope = (sourceFile) => Boolean.or(sourceFile.externalModuleIndicator === void 0, Arr.some(sourceFile.statements, (statement) => isAmbientGlobal(sourceFile, statement)));
1278
+ const importerErrorsOf = (projects, fileNames) => Effect.map(Effect.forEach(projects, (project) => semanticDiagnosticsOf(project.program, fileNames), { concurrency: 1 }), (perProject) => errorDiagnosticsOf(Arr.flatten(perProject)));
1279
+ const wholeProgramErrorsOf = (projects) => Effect.map(Effect.forEach(projects, (project) => wholeProgramDiagnosticsOf(project.program), { concurrency: 1 }), (perProject) => errorDiagnosticsOf(Arr.flatten(perProject)));
1280
+ const ownErrorsOf = (owned, fileName) => Effect.map(Effect.promise(() => owned.project.program.getSemanticDiagnostics(fileName)), errorDiagnosticsOf);
1281
+ const affectedFileNamesOf = (state, mutatedFileNames) => {
1282
+ const command = TraceAffectedFilesCommand.make({
1283
+ importsByFile: Object.fromEntries(Arr.map(Arr.fromIterable(state.sourceFiles), ([fileName, entry]) => [fileName, Arr.fromIterable(entry.imports)])),
1284
+ mutatedFileNames: [...mutatedFileNames]
1285
+ });
1286
+ const affected = decided(traceAffectedFiles(command));
1287
+ return HashSet.fromIterable(Arr.map(affected, (affectedFile) => affectedFile.fileName));
1288
+ };
1289
+ const importerErrorsOfMutant = (state, projects, mutant, fileName) => Effect.map(importerErrorsOf(projects, affectedFileNamesOf(state, [fileName])), (diagnostics) => ({
1290
+ mutantId: mutant.id,
1291
+ diagnostics
1292
+ }));
1293
+ const beyondOwnErrorsOf = (state, projects, mutant, owned, fileName) => Boolean.match(declaresGlobalScope(owned.sourceFile), {
1294
+ onTrue: () => Effect.map(wholeProgramErrorsOf(projects), (diagnostics) => ({
1295
+ mutantId: mutant.id,
1296
+ diagnostics
1297
+ })),
1298
+ onFalse: () => importerErrorsOfMutant(state, projects, mutant, fileName)
1299
+ });
1300
+ const checkedIn = (state, projects, mutant, owned, fileName) => Effect.flatMap(ownErrorsOf(owned, fileName), (own) => Boolean.match(own.length > 0, {
1301
+ onTrue: () => Effect.succeed({
1302
+ mutantId: mutant.id,
1303
+ diagnostics: own
1304
+ }),
1305
+ onFalse: () => beyondOwnErrorsOf(state, projects, mutant, owned, fileName)
1306
+ }));
1307
+ const checkOne = (rt, state, mutant, previousMutants) => Effect.gen(function* () {
1308
+ yield* resetMutatedFiles(rt, previousMutants);
1309
+ const fileName = resolveFileName(rt, mutant.fileName);
1310
+ const previousFileNames = Arr.map(previousMutants, (previous) => resolveFileName(rt, previous.fileName));
1311
+ const changedFiles = Arr.dedupe([...previousFileNames, fileName]);
1312
+ const file = yield* getFile(rt.files, fileName);
1313
+ yield* applyMutant(rt, mutant, mutant.replacement);
1314
+ yield* refreshSnapshot(rt, changedFiles);
1315
+ const held = yield* parseHeldAfterSpliceOf(rt, file, mutant, fileName);
1316
+ yield* Boolean.match(held, {
1317
+ onTrue: () => Effect.void,
1318
+ onFalse: () => parenthesizedSpliceOf(rt, mutant, fileName, changedFiles)
1319
+ });
1320
+ const projects = yield* projectsOf(rt);
1321
+ const owned = yield* projectOfFile(projects, fileName);
1322
+ return yield* Option.match(owned, {
1323
+ onNone: () => Effect.succeed({
1324
+ mutantId: mutant.id,
1325
+ diagnostics: []
1326
+ }),
1327
+ onSome: (found) => checkedIn(state, projects, mutant, found, fileName)
1328
+ });
1329
+ });
1330
+ const check = dual(2, Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerCheck.name)(function* (self, mutants) {
1331
+ const rt = runtimeOf(self);
1332
+ yield* Effect.annotateCurrentSpan({
1333
+ "stryker.mutants.count": mutants.length,
1334
+ "stryker.mutants.ids": Arr.map(mutants, (mutant) => mutant.id).join(",")
1335
+ });
1336
+ const state = yield* SynchronizedRef.get(rt.state);
1337
+ yield* resetMutatedFiles(rt, state.lastMutants);
1338
+ const batchFileNames = Arr.dedupe(Arr.map(mutants, (mutant) => resolveFileName(rt, mutant.fileName)));
1339
+ yield* refreshSnapshot(rt, Arr.dedupe([...state.lastMutatedFileNames, ...batchFileNames]));
1340
+ const checked = (yield* Effect.reduce(mutants, () => ({
1341
+ previous: Option.none(),
1342
+ results: []
1343
+ }), (previous, mutant) => Effect.map(checkOne(rt, state, mutant, Option.toArray(previous.previous)), (result) => ({
1344
+ previous: Option.some(mutant),
1345
+ results: [...previous.results, result]
1346
+ })))).results;
1347
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
1348
+ ...prev,
1349
+ lastMutants: [...mutants],
1350
+ lastMutatedFileNames: batchFileNames
1351
+ }));
1352
+ const failed = Arr.filter(checked, (entry) => entry.diagnostics.length > 0);
1353
+ yield* Effect.annotateCurrentSpan({
1354
+ "typescript.diagnostics.count": Arr.reduce(checked, 0, (total, entry) => total + entry.diagnostics.length),
1355
+ "typescript.compile_errors.count": failed.length
1356
+ });
1357
+ yield* annotateDiagnosticSample(Arr.flatten(Arr.map(failed, (entry) => entry.diagnostics)));
1358
+ return checked;
1359
+ }));
1360
+ const nodes = Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerNodes.name)(function* (self) {
1361
+ return yield* self.pipe(runtimeOf, nodesOf);
1362
+ });
1363
+ const groupedMutants = (mutants) => Arr.map(decided(groupMutants(GroupMutantsCommand.make({ mutants: [...mutants] }))), (group) => group.ids);
1364
+ const groups = (mutants) => Effect.sync(() => groupedMutants(mutants)).pipe(Effect.withSpan(SpanTaxonomy.Spans.typescriptCheckerCompilerGroups.name));
1365
+ const getLineAndCharacterOfPosition = dual(3, Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerLineAndCharacter.name)(function* (self, fileName, position) {
1366
+ const rt = runtimeOf(self);
1367
+ const programs = yield* programsOf(rt).pipe(Effect.orElseSucceed(() => []));
1368
+ const found = yield* sourceFileOf(programs, fileName);
1369
+ return Option.getOrUndefined(Option.map(found, (sourceFile) => sourceFile.getLineAndCharacterOfPosition(position)));
1370
+ }));
1371
+ const severityOf = (category) => Match.value(category).pipe(Match.when(DiagnosticCategory.Warning, () => "warning"), Match.when(DiagnosticCategory.Error, () => "error"), Match.when(DiagnosticCategory.Suggestion, () => "suggestion"), Match.orElse(() => "message"));
1372
+ const renderPosition = (fileName, at) => Option.match(Option.fromUndefinedOr(at), {
1373
+ onNone: () => fileName + "(1,1): ",
1374
+ onSome: (position) => fileName + "(" + (position.line + 1) + "," + (position.character + 1) + "): "
1375
+ });
1376
+ const positionOf = (self, diagnostic) => Option.match(Option.filter(Option.fromUndefinedOr(diagnostic.fileName), (fileName) => fileName !== ""), {
1377
+ onNone: () => Effect.succeed(""),
1378
+ onSome: (fileName) => getLineAndCharacterOfPosition(self, fileName, diagnostic.pos).pipe(Effect.orElseSucceed(() => void 0), Effect.map((at) => renderPosition(fileName, at)))
1379
+ });
1380
+ const describedOf = (self, diagnostic) => Effect.map(positionOf(self, diagnostic), (position) => DiagnosticLine.make({
1381
+ position,
1382
+ severity: severityOf(diagnostic.category),
1383
+ code: diagnostic.code,
1384
+ text: diagnostic.text,
1385
+ ...diagnostic.fileName === void 0 ? {} : { fileName: diagnostic.fileName }
1386
+ }));
1387
+ const describeDiagnostics = dual(2, (self, diagnostics) => Effect.forEach(diagnostics, (diagnostic) => describedOf(self, diagnostic)));
1388
+ const CLOSE_GRACE = "1 second";
1389
+ const close = Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerClose.name)(function* (self) {
1390
+ const rt = runtimeOf(self);
1391
+ const state = yield* SynchronizedRef.getAndUpdate(rt.state, (prev) => ({
1392
+ ...prev,
1393
+ snapshot: void 0,
1394
+ api: void 0
1395
+ }));
1396
+ const released = yield* Option.match(Option.fromUndefinedOr(state.api), {
1397
+ onNone: () => Effect.succeed(true),
1398
+ onSome: (api) => Effect.tryPromise(() => api.close()).pipe(Effect.timeoutOption(CLOSE_GRACE), Effect.tapError((error) => Effect.annotateCurrentSpan("typescript.server.close_error", error.message)), Effect.match({
1399
+ onFailure: () => false,
1400
+ onSuccess: Option.isSome
1401
+ }))
1402
+ });
1403
+ yield* Effect.annotateCurrentSpan("typescript.server.released", released);
1404
+ });
1405
+ //#endregion
1406
+ //#region src/ts-compiler.service.ts
1407
+ var TypeScriptCompiler = class extends Context.Service()("@systemfsoftware/stryker-js-typescript-checker/ts-compiler.service/TypeScriptCompiler") {};
1408
+ //#endregion
1409
+ //#region src/Checker.cell.ts
1410
+ const refuse$1 = (options) => Checker.CheckerFailed.make({
1411
+ checkerName: "typescript",
1412
+ mutantIds: options.mutantIds,
1413
+ cause: Option.getOrElse(Option.map(ErrorText.errorTextOf(options.cause), (rendered) => rendered.text), () => "")
1414
+ });
1415
+ const verdictsOf = (compiler, checked) => Effect.forEach(checked, (entry) => Effect.map(describeDiagnostics(compiler, entry.diagnostics), (diagnostics) => MutantVerdict.make({
1416
+ id: entry.mutantId,
1417
+ diagnostics: [...diagnostics]
1418
+ })), { concurrency: 1 });
1419
+ const checkCell = Sandwich.named(SpanTaxonomy.Spans.typescriptCheckerCheckMutants.name)((command) => Effect.flatMap(TypeScriptCompiler, (compiler) => Effect.flatMap(check(compiler, [...command.mutants]), (checked) => Effect.map(verdictsOf(compiler, checked), (verdicts) => CheckMutantsInput.make({
1420
+ mutants: [...command.mutants],
1421
+ verdicts: [...verdicts]
1422
+ })))).pipe(Effect.mapError((cause) => refuse$1({
1423
+ mutantIds: command.mutants.map((mutant) => mutant.id),
1424
+ cause
1425
+ })))).decide(checkMutants).write({
1426
+ MutantPassed: (outcome) => Effect.succeed(outcome),
1427
+ MutantFailed: (outcome) => Effect.succeed(outcome),
1428
+ CommandRejected: ({ issue }) => Effect.fail(refuse$1({
1429
+ mutantIds: [],
1430
+ cause: issue
1431
+ }))
1432
+ });
1433
+ //#endregion
1434
+ //#region src/ts-compiler.blueprint.ts
1435
+ const TypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TSCompilerResource");
1436
+ const scopedOf = Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerScoped.name)(function* (spec) {
1437
+ const host = yield* FileSystem.FileSystem;
1438
+ const pathService = yield* Path.Path;
1439
+ const compiler = yield* make$1(spec, {
1440
+ host,
1441
+ pathService
1442
+ });
1443
+ yield* Effect.addFinalizer(() => close(compiler));
1444
+ return compiler;
1445
+ });
1446
+ const layerOf = (spec) => (service) => Layer.effect(service)(scopedOf(spec));
1447
+ const TSCompilerResource = Blueprint.make()(TypeId).steps({
1448
+ steps: {},
1449
+ targets: {
1450
+ layer: layerOf,
1451
+ scoped: scopedOf
1452
+ }
1453
+ });
1454
+ const make = (options) => TSCompilerResource.of(options);
1455
+ //#endregion
1456
+ //#region src/CheckerRuntime.service.ts
1457
+ const refuse = (options) => Checker.CheckerFailed.make({
1458
+ checkerName: "typescript",
1459
+ mutantIds: options.mutantIds,
1460
+ cause: Option.getOrElse(Option.map(ErrorText.errorTextOf(options.cause), (rendered) => rendered.text), () => "")
1461
+ });
1462
+ const toCheckResult = (event) => Match.value(event).pipe(Match.tag("MutantPassed", () => ({ status: "passed" })), Match.tag("MutantFailed", (failed) => ({
1463
+ status: "compileError",
1464
+ reason: failed.reason
1465
+ })), Match.exhaustive);
1466
+ const checkResultsOf = (events) => HashMap.fromIterable(Arr.map(events, (event) => [event.id, toCheckResult(event)]));
1467
+ const makeChecker = Effect.fn(SpanTaxonomy.Spans.typescriptCheckerRuntimeMakeChecker.name)(function* (options, compiler) {
1468
+ const verify = Cell.provideContext(checkCell, Context.make(TypeScriptCompiler, compiler));
1469
+ const createErrorText = (errors) => Effect.map(describeDiagnostics(compiler, errors), (diagnostics) => diagnostics.map((entry) => entry.rendered).join("\n"));
1470
+ const service = {
1471
+ init: init(compiler).pipe(Effect.mapError((cause) => refuse({
1472
+ mutantIds: [],
1473
+ cause
1474
+ })), Effect.flatMap((errors) => Boolean.match(errors.length === 0, {
1475
+ onTrue: () => Effect.void,
1476
+ onFalse: () => createErrorText(errors).pipe(Effect.map((text) => refuse({
1477
+ mutantIds: [],
1478
+ cause: DryRunCompileErrors.make({ text })
1479
+ })), Effect.flatMap(Effect.fail))
1480
+ }))),
1481
+ check: (mutants) => verify.run(CheckMutantsCommand.make({ mutants: [...mutants] })).pipe(Effect.map((events) => checkResultsOf(events)), Effect.withSpan(SpanTaxonomy.Spans.typescriptCheckerCheck.name, { attributes: { "stryker.mutants.count": mutants.length } })),
1482
+ group: (mutants) => groups([...mutants])
1483
+ };
1484
+ yield* service.init;
1485
+ return service;
1486
+ });
1487
+ var CheckerRuntime = class CheckerRuntime extends Context.Service()("@systemfsoftware/stryker-js-typescript-checker/CheckerRuntime.service/CheckerRuntime") {
1488
+ static layer = (options) => Layer.effect(CheckerRuntime, Effect.gen(function* () {
1489
+ const compiler = yield* TypeScriptCompiler;
1490
+ const checker = yield* makeChecker(options, compiler).pipe(Effect.catchCause((cause) => Effect.fail(cause)), Effect.cached);
1491
+ return CheckerRuntime.of({ checker });
1492
+ })).pipe(Layer.provideMerge(make(options).layer(TypeScriptCompiler)));
1493
+ };
1494
+ //#endregion
1495
+ export { CheckerRuntime, TypeScriptCompiler, nodes };