@systemfsoftware/stryker-js-typescript-checker 8.2.0 → 9.0.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,3551 @@
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
3
+ import { Handle, Workflow } from "@systemfsoftware/effect-cell-types";
4
+ import { SpanTaxonomy } from "@systemfsoftware/stryker-js-cli-contract";
5
+ import { lineStartsOf, offsetAt } from "@systemfsoftware/stryker-js-instrumenter";
6
+ import { Checker, Mutant, TypeQuery } from "@systemfsoftware/stryker-js-plugin-interface";
7
+ import * as Arr from "effect/Array";
8
+ import * as Boolean from "effect/Boolean";
9
+ import * as Duration from "effect/Duration";
10
+ import * as Effect from "effect/Effect";
11
+ import * as FileSystem from "effect/FileSystem";
12
+ import { dual } from "effect/Function";
13
+ import * as HashMap from "effect/HashMap";
14
+ import * as HashSet from "effect/HashSet";
15
+ import * as Match from "effect/Match";
16
+ import * as Option from "effect/Option";
17
+ import * as Order from "effect/Order";
18
+ import * as Path from "effect/Path";
19
+ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
20
+ import * as Ref from "effect/Ref";
21
+ import * as Result from "effect/Result";
22
+ import * as S from "effect/Schema";
23
+ import * as SynchronizedRef from "effect/SynchronizedRef";
24
+ import { ModifierFlags, SyntaxKind } from "typescript/unstable/ast";
25
+ import { API, DiagnosticCategory, SignatureKind, TypeFlags } from "typescript/unstable/async";
26
+ import { Schema } from "effect";
27
+ import * as Rec from "effect/Record";
28
+ import * as SchemaIssue from "effect/SchemaIssue";
29
+ import * as SchemaTransformation from "effect/SchemaTransformation";
30
+ import * as Predicate from "effect/Predicate";
31
+ import * as ChildProcess from "effect/process/ChildProcess";
32
+ import * as Clock from "effect/Clock";
33
+ import * as DateTime from "effect/DateTime";
34
+ import * as Layer from "effect/Layer";
35
+ import * as Semaphore from "effect/Semaphore";
36
+ import { isArrayLiteralExpression, isArrowFunction, isAsExpression, isBinaryExpression, isBlock, isCallExpression, isConditionalExpression, isConstructorDeclaration, isExpression, isFunctionExpression, isFunctionLikeDeclaration, isGetAccessorDeclaration, isIdentifier, isNewExpression, isObjectLiteralExpression, isParameterDeclaration, isParenthesizedExpression, isPropertyAssignment, isPropertyDeclaration, isReturnStatement, isSatisfiesExpression, isSetAccessorDeclaration, isTypeReferenceNode, isVariableDeclaration } from "typescript/unstable/ast/is";
37
+ //#region src/edit-site.schema.ts
38
+ const EditSpan = S.Struct({
39
+ start: S.Int.check(S.isGreaterThanOrEqualTo(0)),
40
+ length: S.Int.check(S.isGreaterThanOrEqualTo(0))
41
+ });
42
+ const FunctionLikeFacts = S.Struct({
43
+ kind: S.Int,
44
+ start: S.Int,
45
+ bodyStart: S.Int,
46
+ bodyEnd: S.Int,
47
+ blockBody: S.Boolean,
48
+ header: S.String,
49
+ bodyIndependentSignature: S.Boolean
50
+ });
51
+ const FileFacts = S.Struct({
52
+ typescriptModule: S.Boolean,
53
+ declaresGlobal: S.Boolean
54
+ });
55
+ const EditSiteFacts = S.Struct({
56
+ span: EditSpan,
57
+ ...FileFacts.fields,
58
+ moduleReference: S.Boolean,
59
+ syntaxErrors: S.Boolean,
60
+ enclosing: S.Array(FunctionLikeFacts)
61
+ });
62
+ const IDENTIFIER = 79;
63
+ const IMPORT_KEYWORD = 101;
64
+ const METHOD_DECLARATION = 175;
65
+ const CONSTRUCTOR = 177;
66
+ const GET_ACCESSOR = 178;
67
+ const SET_ACCESSOR = 179;
68
+ const IMPORT_TYPE = 206;
69
+ const CALL_EXPRESSION = 214;
70
+ const FUNCTION_EXPRESSION = 219;
71
+ const ARROW_FUNCTION = 220;
72
+ const BLOCK = 242;
73
+ const FUNCTION_DECLARATION = 263;
74
+ const MODULE_DECLARATION = 268;
75
+ const AMBIENT = 128;
76
+ const FUNCTION_LIKE_KINDS = [
77
+ FUNCTION_DECLARATION,
78
+ FUNCTION_EXPRESSION,
79
+ ARROW_FUNCTION,
80
+ METHOD_DECLARATION,
81
+ CONSTRUCTOR,
82
+ GET_ACCESSOR,
83
+ SET_ACCESSOR
84
+ ];
85
+ const SIGNATURE_FREE_KINDS = [SET_ACCESSOR];
86
+ const isFunctionLikeWithBody = (node) => Arr.contains(FUNCTION_LIKE_KINDS, node.kind);
87
+ const isModuleDeclaration = (node) => node.kind === MODULE_DECLARATION;
88
+ const isCallExpression$1 = (node) => node.kind === CALL_EXPRESSION;
89
+ const isAmbientGlobal = (sourceFile, statement) => Option.exists(Option.liftPredicate(isModuleDeclaration)(statement), (declaration) => Boolean.and((declaration.modifierFlags & AMBIENT) !== 0, declaration.name.getText(sourceFile) === "global"));
90
+ const declaresGlobalOf = (sourceFile) => Arr.some(sourceFile.statements, (statement) => isAmbientGlobal(sourceFile, statement));
91
+ const MODULE_FILE_NAME = /\.(ts|tsx|mts|cts)$/iu;
92
+ const DECLARATION_FILE_NAME = /\.d\.(ts|mts|cts)$/iu;
93
+ const isTypeScriptModuleFileName = (fileName) => Boolean.and(MODULE_FILE_NAME.test(fileName), Boolean.not(DECLARATION_FILE_NAME.test(fileName)));
94
+ const containsSpan = (node, span) => Boolean.and(node.getStart(node.getSourceFile()) <= span.start, span.end <= node.end);
95
+ const overlapsSpan = (node, span) => Boolean.and(node.getStart(node.getSourceFile()) <= span.end, span.start <= node.end);
96
+ const isImportCall = (node) => Option.exists(Option.liftPredicate(isCallExpression$1)(node), (call) => call.expression.kind === IMPORT_KEYWORD);
97
+ const isRequireCall = (node, sourceFile) => Option.exists(Option.liftPredicate(isCallExpression$1)(node), (call) => Boolean.and(call.expression.kind === IDENTIFIER, call.expression.getText(sourceFile) === "require"));
98
+ const isModuleReference = (node, sourceFile) => Boolean.or(node.kind === IMPORT_TYPE, Boolean.or(isImportCall(node), isRequireCall(node, sourceFile)));
99
+ const bodyIndependentSignatureOf = (node) => Boolean.or(Arr.contains(SIGNATURE_FREE_KINDS, node.kind), node.type !== void 0);
100
+ const functionLikeBodyOf$1 = (node) => Option.flatMap(Option.liftPredicate(isFunctionLikeWithBody)(node), (found) => Option.map(Option.fromUndefinedOr(found.body), (body) => ({
101
+ node: found,
102
+ body
103
+ })));
104
+ const factsOf = (found, sourceFile) => {
105
+ const start = found.node.getStart(sourceFile);
106
+ const bodyStart = found.body.getStart(sourceFile);
107
+ return {
108
+ kind: found.node.kind,
109
+ start,
110
+ bodyStart,
111
+ bodyEnd: found.body.end,
112
+ blockBody: found.body.kind === BLOCK,
113
+ header: sourceFile.text.slice(start, bodyStart),
114
+ bodyIndependentSignature: bodyIndependentSignatureOf(found.node)
115
+ };
116
+ };
117
+ const scanOf = (sourceFile, span) => {
118
+ const enclosing = [];
119
+ let moduleReference = false;
120
+ let inspected = 0;
121
+ const inspect = (node) => {
122
+ inspected += 1;
123
+ Option.match(Option.filter(functionLikeBodyOf$1(node), (found) => containsSpan(found.node, span)), {
124
+ onNone: () => void 0,
125
+ onSome: (found) => enclosing.push(factsOf(found, sourceFile))
126
+ });
127
+ moduleReference = Boolean.or(moduleReference, Boolean.and(isModuleReference(node, sourceFile), overlapsSpan(node, span)));
128
+ return node.forEachChild(visit);
129
+ };
130
+ const visit = (node) => Boolean.match(span.end < node.pos, {
131
+ onTrue: () => true,
132
+ onFalse: () => Boolean.match(node.end < span.start, {
133
+ onTrue: () => void 0,
134
+ onFalse: () => inspect(node)
135
+ })
136
+ });
137
+ sourceFile.forEachChild(visit);
138
+ return {
139
+ enclosing,
140
+ moduleReference,
141
+ inspected
142
+ };
143
+ };
144
+ const fileFactsOf = (sourceFile) => ({
145
+ typescriptModule: Boolean.and(isTypeScriptModuleFileName(sourceFile.fileName), sourceFile.externalModuleIndicator !== void 0),
146
+ declaresGlobal: declaresGlobalOf(sourceFile)
147
+ });
148
+ const editSiteFactsOf = dual(3, (sourceFile, span, syntaxErrors) => {
149
+ const scan = scanOf(sourceFile, span);
150
+ return {
151
+ span: {
152
+ start: span.start,
153
+ length: span.end - span.start
154
+ },
155
+ ...fileFactsOf(sourceFile),
156
+ moduleReference: scan.moduleReference,
157
+ syntaxErrors,
158
+ enclosing: scan.enclosing
159
+ };
160
+ });
161
+ S.is(EditSpan);
162
+ //#endregion
163
+ //#region src/Checker.schema.ts
164
+ /**
165
+ * Checker — declarations for the TypeScript checker.
166
+ *
167
+ * Houses the wire types and error variants shared by the capability and its
168
+ * workflow. Decoded at the checker boundary; no I/O.
169
+ */
170
+ const ImporterCheck = S.Literals(["location-rule", "always"]);
171
+ const TypescriptCheckerBlock = S.Struct({ importerCheck: S.optional(ImporterCheck) });
172
+ S.Struct({ typescriptChecker: S.optional(TypescriptCheckerBlock) });
173
+ const UndecodedCheckerBlock = S.Struct({ typescriptChecker: S.optional(S.Unknown) });
174
+ const importerCheckOf = (options) => Option.getOrElse(Option.flatMapNullishOr(Option.fromUndefinedOr(options.typescriptChecker), (checker) => checker.importerCheck), () => "location-rule");
175
+ const readsEditSites = (importerCheck) => importerCheck === "location-rule";
176
+ var CheckMutantsCommand = class extends S.TaggedClass()("CheckMutantsCommand", { mutants: S.Array(Checker.CheckerMutantWire) }) {};
177
+ //#endregion
178
+ //#region src/ImporterShortcut.schema.ts
179
+ const ShortcutClause = S.Literals([
180
+ "outside-function-body",
181
+ "body-dependent-signature",
182
+ "not-typescript-module",
183
+ "module-reference",
184
+ "syntax-error",
185
+ "shared-file"
186
+ ]);
187
+ const ShortcutTree = S.Literals(["original", "mutated"]);
188
+ const ImporterShortcutTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/ImporterShortcutDecision");
189
+ var ShortcutTaken = class extends S.TaggedClass()("ShortcutTaken", {}) {
190
+ [ImporterShortcutTypeId] = ImporterShortcutTypeId;
191
+ };
192
+ var ImportersRechecked = class extends S.TaggedClass()("ImportersRechecked", {
193
+ clause: ShortcutClause,
194
+ tree: ShortcutTree
195
+ }) {
196
+ [ImporterShortcutTypeId] = ImporterShortcutTypeId;
197
+ };
198
+ const ImporterShortcutDecision = S.Union([ShortcutTaken, ImportersRechecked]);
199
+ const takesShortcut = (decision) => S.is(ShortcutTaken)(decision);
200
+ const fallbackKeyOf = (decision) => Match.valueTags(decision, {
201
+ ShortcutTaken: () => Option.none(),
202
+ ImportersRechecked: (rechecked) => Option.some(`${rechecked.tree}.${rechecked.clause}`)
203
+ });
204
+ S.Struct({
205
+ importerCheck: ImporterCheck,
206
+ decisions: ImporterShortcutDecision.pipe(S.Option, S.Array)
207
+ });
208
+ const SHORTCUT_COUNT = "typescript.importer_shortcut.count";
209
+ const outcomeFallbackKeyOf = (decision) => Option.match(decision, {
210
+ onNone: () => Option.some("unread"),
211
+ onSome: fallbackKeyOf
212
+ });
213
+ const locationRuleCountsOf = (decisions) => ({
214
+ [SHORTCUT_COUNT]: Arr.filter(decisions, (decision) => Option.exists(decision, takesShortcut)).length,
215
+ ...Object.fromEntries(Object.entries(Arr.groupBy(Arr.getSomes(Arr.map(decisions, outcomeFallbackKeyOf)), (key) => key)).map(([key, keys]) => [`typescript.importer_shortcut.fallback.${key}.count`, keys.length]))
216
+ });
217
+ const shortcutCountsOf = (outcomes) => Boolean.match(readsEditSites(outcomes.importerCheck), {
218
+ onFalse: () => ({ [SHORTCUT_COUNT]: 0 }),
219
+ onTrue: () => locationRuleCountsOf(outcomes.decisions)
220
+ });
221
+ //#endregion
222
+ //#region src/Tsconfig.schema.ts
223
+ var TsConfigParseError = class extends Schema.TaggedError()("TsConfigParseError", {
224
+ file: Schema.String,
225
+ reason: Schema.String
226
+ }) {
227
+ get message() {
228
+ return `Could not parse tsconfig file '${this.file}': ${this.reason}`;
229
+ }
230
+ };
231
+ var TsConfigNotFoundError = class extends Schema.TaggedError()("TsConfigNotFoundError", { file: Schema.String }) {
232
+ get message() {
233
+ return `The tsconfig file does not exist at: "${this.file}". Please configure the tsconfig file in your stryker.conf file using "tsconfigFile"`;
234
+ }
235
+ };
236
+ const PathAliasesSchema = Schema.Record(Schema.String, Schema.Array(Schema.String));
237
+ const JsonRecord = Schema.Record(Schema.String, Schema.Json);
238
+ const ProjectReferenceSchema = Schema.StructWithRest(Schema.Struct({ path: Schema.String }), [JsonRecord]);
239
+ const TsConfigCompilerOptionsSchema = JsonRecord;
240
+ const TsConfigExtendsSchema = Schema.Union([Schema.String, Schema.Array(Schema.String)]);
241
+ const TsConfigDocumentSchema = Schema.StructWithRest(Schema.Struct({
242
+ extends: Schema.optional(TsConfigExtendsSchema),
243
+ references: Schema.optional(Schema.Array(ProjectReferenceSchema)),
244
+ compilerOptions: Schema.optional(TsConfigCompilerOptionsSchema)
245
+ }), [JsonRecord]);
246
+ const ReferenceGraph = Schema.Record(Schema.String, Schema.Array(Schema.String));
247
+ Schema.Struct({
248
+ references: ReferenceGraph,
249
+ owner: Schema.String,
250
+ holders: Schema.Array(Schema.String)
251
+ });
252
+ const referencesOf = (graph, config) => Option.getOrElse(Rec.get(graph, config), () => []);
253
+ const reachedFrom = (graph, pending, seen) => Option.match(Arr.head(pending), {
254
+ onNone: () => seen,
255
+ onSome: (config) => Boolean.match(HashSet.has(seen, config), {
256
+ onTrue: () => reachedFrom(graph, Arr.drop(pending, 1), seen),
257
+ onFalse: () => reachedFrom(graph, [...Arr.drop(pending, 1), ...referencesOf(graph, config)], HashSet.add(seen, config))
258
+ })
259
+ });
260
+ const reachesOwner = (holders, holder) => HashSet.has(reachedFrom(holders.references, referencesOf(holders.references, holder), HashSet.empty()), holders.owner);
261
+ const otherCompilersOf = (holders) => Arr.filter(Arr.dedupe(holders.holders), (holder) => Boolean.and(holder !== holders.owner, Boolean.not(reachesOwner(holders, holder))));
262
+ Schema.is(TsConfigDocumentSchema);
263
+ //#endregion
264
+ //#region src/CheckerCommands.schema.ts
265
+ const MutantBound = S.Int.pipe(S.check(S.isGreaterThanOrEqualTo(1)));
266
+ var GroupMutantsCommand = class extends S.TaggedClass()("GroupMutantsCommand", {
267
+ mutants: S.Array(Checker.CheckerMutantWire),
268
+ bound: MutantBound
269
+ }) {
270
+ static [Workflow.InstrumentationBrand] = {};
271
+ };
272
+ var TraceAffectedFilesCommand = class extends S.TaggedClass()("TraceAffectedFilesCommand", {
273
+ importsByFile: S.Record(S.String, S.Array(S.String)),
274
+ mutatedFileNames: S.Array(S.String)
275
+ }) {
276
+ static [Workflow.InstrumentationBrand] = { mutatedFileNames: "stryker.typescript_checker.mutated_files" };
277
+ };
278
+ var RequestAffectedFilesCommand = class extends S.TaggedClass()("RequestAffectedFilesCommand", {
279
+ affectedFileNames: S.Array(S.String),
280
+ presentFileNames: S.Array(S.String)
281
+ }) {
282
+ static [Workflow.InstrumentationBrand] = { affectedFileNames: "stryker.typescript_checker.affected_files" };
283
+ };
284
+ var PlanDiagnosticBatchesCommand = class extends S.TaggedClass()("PlanDiagnosticBatchesCommand", { fileNames: S.Array(S.String) }) {
285
+ static [Workflow.InstrumentationBrand] = { fileNames: "stryker.typescript_checker.requested_files" };
286
+ };
287
+ var CaptureAliasSpecifierCommand = class extends S.TaggedClass()("CaptureAliasSpecifierCommand", {
288
+ pattern: S.String,
289
+ specifier: S.String
290
+ }) {
291
+ static [Workflow.InstrumentationBrand] = { specifier: "stryker.typescript_checker.specifier" };
292
+ };
293
+ var PlanResolutionCandidatesCommand = class extends S.TaggedClass()("PlanResolutionCandidatesCommand", {
294
+ resolved: S.String,
295
+ extension: S.String
296
+ }) {
297
+ static [Workflow.InstrumentationBrand] = { resolved: "stryker.typescript_checker.resolved_file" };
298
+ };
299
+ var OverrideTsconfigOptionsCommand = class extends S.TaggedClass()("OverrideTsconfigOptionsCommand", {
300
+ document: TsConfigDocumentSchema,
301
+ buildMode: S.Boolean
302
+ }) {
303
+ static [Workflow.InstrumentationBrand] = { buildMode: "stryker.typescript_checker.build_mode" };
304
+ };
305
+ var ParseTsconfigTextCommand = class extends S.TaggedClass()("ParseTsconfigTextCommand", { text: S.String }) {
306
+ static [Workflow.InstrumentationBrand] = {};
307
+ };
308
+ const ContextualTypeFacts = S.Struct({
309
+ text: S.String,
310
+ isError: S.Boolean,
311
+ instantiable: S.Boolean
312
+ });
313
+ const DeclaredContext = S.TaggedStruct("DeclaredContext", {});
314
+ const CallArgument = S.TaggedStruct("CallArgument", {
315
+ signatureCount: S.Int,
316
+ declaredGeneric: S.Boolean
317
+ });
318
+ const UnenforcedContext = S.TaggedStruct("UnenforcedContext", {});
319
+ const ContextOrigin = S.Union([
320
+ DeclaredContext,
321
+ CallArgument,
322
+ UnenforcedContext
323
+ ]);
324
+ const SiteMissing = S.TaggedStruct("SiteMissing", {});
325
+ const SiteNotExpression = S.TaggedStruct("SiteNotExpression", {});
326
+ const SiteExpression = S.TaggedStruct("SiteExpression", {
327
+ contextualType: S.OptionFromNullOr(ContextualTypeFacts),
328
+ origin: ContextOrigin
329
+ });
330
+ const FunctionBodyKind = S.Literals([
331
+ "getter",
332
+ "setter",
333
+ "constructor",
334
+ "other"
335
+ ]);
336
+ const SiteNotFunctionBody = S.TaggedStruct("SiteNotFunctionBody", {});
337
+ const SiteFunctionBody = S.TaggedStruct("SiteFunctionBody", {
338
+ functionKind: FunctionBodyKind,
339
+ generator: S.Boolean,
340
+ async: S.Boolean,
341
+ returnTypeDeclared: S.Boolean,
342
+ asyncReturnIsPromise: S.Boolean,
343
+ target: S.OptionFromNullOr(ContextualTypeFacts),
344
+ undefinedAssignable: S.Boolean,
345
+ targetAllowsImplicitReturn: S.Boolean
346
+ });
347
+ const SiteFacts = S.Union([
348
+ SiteMissing,
349
+ SiteNotExpression,
350
+ SiteExpression,
351
+ SiteNotFunctionBody,
352
+ SiteFunctionBody
353
+ ]);
354
+ const CandidateNotContextFree = S.TaggedStruct("CandidateNotContextFree", {});
355
+ const CandidateMissing = S.TaggedStruct("CandidateMissing", {});
356
+ const CandidateTyped = S.TaggedStruct("CandidateTyped", {
357
+ candidateType: S.String,
358
+ assignable: S.Boolean
359
+ });
360
+ const CandidateBodyText = S.TaggedStruct("CandidateBodyText", { text: S.String });
361
+ const CandidateFacts = S.Union([
362
+ CandidateNotContextFree,
363
+ CandidateMissing,
364
+ CandidateTyped,
365
+ CandidateBodyText
366
+ ]);
367
+ var ClassifyCandidateCommand = class extends S.TaggedClass()("ClassifyCandidateCommand", { text: S.String }) {
368
+ static [Workflow.InstrumentationBrand] = {};
369
+ };
370
+ var AnswerTypeQueryCommand = class extends S.TaggedClass()("AnswerTypeQueryCommand", {
371
+ site: SiteFacts,
372
+ candidate: CandidateFacts
373
+ }) {
374
+ static [Workflow.InstrumentationBrand] = {};
375
+ };
376
+ var DecideImporterShortcutCommand = class extends S.TaggedClass()("DecideImporterShortcutCommand", {
377
+ original: EditSiteFacts,
378
+ mutated: EditSiteFacts,
379
+ compiledElsewhere: S.Boolean
380
+ }) {
381
+ static [Workflow.InstrumentationBrand] = {};
382
+ };
383
+ var ConcludeSharedRoundCommand = class extends S.TaggedClass()("ConcludeSharedRoundCommand", { decisions: ImporterShortcutDecision.pipe(S.Option, S.Array) }) {
384
+ static [Workflow.InstrumentationBrand] = {};
385
+ };
386
+ const RoundCandidate = S.Struct({
387
+ id: Mutant.MutantId,
388
+ fileName: S.String,
389
+ eligible: S.Boolean
390
+ });
391
+ const roundCandidateIdsAreDistinct = S.makeFilter((candidates) => Option.getOrUndefined(Option.map(Option.fromUndefinedOr(Mutant.duplicatedValue(candidates.map((candidate) => candidate.id))), (duplicated) => `round candidate ids must identify distinct mutants, got "${duplicated}"`)), { arbitraryConstraint: { uniqueBy: (candidate) => candidate.id } });
392
+ var PlanCheckRoundsCommand = class extends S.TaggedClass()("PlanCheckRoundsCommand", { candidates: S.Array(RoundCandidate).check(roundCandidateIdsAreDistinct) }) {
393
+ static [Workflow.InstrumentationBrand] = {};
394
+ };
395
+ S.is(MutantBound), S.is(PlanCheckRoundsCommand.fields.candidates);
396
+ //#endregion
397
+ //#region src/admit-importer-shortcut.workflow.ts
398
+ const editableEndOf = (facts) => Boolean.match(facts.blockBody, {
399
+ onTrue: () => facts.bodyEnd - 1,
400
+ onFalse: () => facts.bodyEnd
401
+ });
402
+ const spanInsideBody = (span, facts) => Boolean.and(facts.bodyStart <= span.start, span.start + span.length <= editableEndOf(facts));
403
+ const bodiesContaining = (site) => Arr.filter(site.enclosing, (facts) => spanInsideBody(site.span, facts));
404
+ const bodyIndependentOf = (facts) => Arr.filter(facts, (facts) => facts.bodyIndependentSignature);
405
+ const matchesMutated = (original, mutated) => Boolean.and(Boolean.and(mutated.kind === original.kind, mutated.start === original.start), Boolean.and(mutated.header === original.header, mutated.bodyIndependentSignature));
406
+ const matchedPairOf = (original, mutated) => Boolean.match(matchesMutated(original, mutated), {
407
+ onTrue: () => Result.succeed({
408
+ original,
409
+ mutated
410
+ }),
411
+ onFalse: () => Result.failVoid
412
+ });
413
+ const matchedPairs = (command, candidates) => Arr.flatMap(candidates, (original) => Arr.filterMap(command.mutated.enclosing, (mutated) => matchedPairOf(original, mutated)));
414
+ const deltaOf = (command) => command.mutated.span.length - command.original.span.length;
415
+ const bodyLengthAgrees = (pair, delta) => pair.mutated.bodyEnd - pair.mutated.bodyStart === pair.original.bodyEnd - pair.original.bodyStart + delta;
416
+ const pairAdmitsShortcut = (command, pair) => Boolean.and(spanInsideBody(command.mutated.span, pair.mutated), bodyLengthAgrees(pair, deltaOf(command)));
417
+ const notTypescriptModule = (site) => Boolean.or(Boolean.not(site.typescriptModule), site.declaresGlobal);
418
+ const rulesOf$1 = (command) => {
419
+ const originalBodies = bodiesContaining(command.original);
420
+ const candidates = bodyIndependentOf(originalBodies);
421
+ const pairs = matchedPairs(command, candidates);
422
+ return [
423
+ {
424
+ verdict: {
425
+ clause: "outside-function-body",
426
+ tree: "original"
427
+ },
428
+ fails: !Arr.isArrayNonEmpty(originalBodies)
429
+ },
430
+ {
431
+ verdict: {
432
+ clause: "body-dependent-signature",
433
+ tree: "original"
434
+ },
435
+ fails: !Arr.isArrayNonEmpty(candidates)
436
+ },
437
+ {
438
+ verdict: {
439
+ clause: "not-typescript-module",
440
+ tree: "original"
441
+ },
442
+ fails: notTypescriptModule(command.original)
443
+ },
444
+ {
445
+ verdict: {
446
+ clause: "module-reference",
447
+ tree: "original"
448
+ },
449
+ fails: command.original.moduleReference
450
+ },
451
+ {
452
+ verdict: {
453
+ clause: "syntax-error",
454
+ tree: "original"
455
+ },
456
+ fails: command.original.syntaxErrors
457
+ },
458
+ {
459
+ verdict: {
460
+ clause: "shared-file",
461
+ tree: "original"
462
+ },
463
+ fails: command.compiledElsewhere
464
+ },
465
+ {
466
+ verdict: {
467
+ clause: "not-typescript-module",
468
+ tree: "mutated"
469
+ },
470
+ fails: notTypescriptModule(command.mutated)
471
+ },
472
+ {
473
+ verdict: {
474
+ clause: "module-reference",
475
+ tree: "mutated"
476
+ },
477
+ fails: command.mutated.moduleReference
478
+ },
479
+ {
480
+ verdict: {
481
+ clause: "syntax-error",
482
+ tree: "mutated"
483
+ },
484
+ fails: command.mutated.syntaxErrors
485
+ },
486
+ {
487
+ verdict: {
488
+ clause: "body-dependent-signature",
489
+ tree: "mutated"
490
+ },
491
+ fails: !Arr.isArrayNonEmpty(pairs)
492
+ },
493
+ {
494
+ verdict: {
495
+ clause: "outside-function-body",
496
+ tree: "mutated"
497
+ },
498
+ fails: !Arr.some(pairs, (pair) => pairAdmitsShortcut(command, pair))
499
+ }
500
+ ];
501
+ };
502
+ const decide$15 = (command) => Result.succeed(Option.match(Arr.findFirst(rulesOf$1(command), (rule) => rule.fails), {
503
+ onNone: () => ShortcutTaken.make({}),
504
+ onSome: (rule) => ImportersRechecked.make({
505
+ clause: rule.verdict.clause,
506
+ tree: rule.verdict.tree
507
+ })
508
+ }));
509
+ const admitImporterShortcut = Workflow.make({
510
+ command: DecideImporterShortcutCommand,
511
+ decision: ImporterShortcutDecision,
512
+ error: S.Never,
513
+ decide: decide$15
514
+ });
515
+ //#endregion
516
+ //#region src/capture-alias-specifier.workflow.ts
517
+ const CaptureTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/AliasCapture");
518
+ var AliasSpecifierCaptured = class extends S.TaggedClass()("AliasSpecifierCaptured", { capture: S.String }) {
519
+ [CaptureTypeId] = CaptureTypeId;
520
+ };
521
+ var AliasSpecifierUnmatched = class extends S.TaggedClass()("AliasSpecifierUnmatched", {}) {
522
+ [CaptureTypeId] = CaptureTypeId;
523
+ };
524
+ const AliasCapture = S.Union([AliasSpecifierCaptured, AliasSpecifierUnmatched]);
525
+ const prefixOf = (pattern) => pattern.slice(0, pattern.indexOf("*"));
526
+ const suffixOf = (pattern) => pattern.slice(pattern.indexOf("*") + 1);
527
+ const stripPrefix = (specifier, prefix) => Option.map(Option.liftPredicate(specifier, (candidate) => candidate.startsWith(prefix)), (candidate) => candidate.slice(prefix.length));
528
+ const stripSuffix = (specifier, suffix) => Option.map(Option.liftPredicate(specifier, (candidate) => candidate.endsWith(suffix)), (candidate) => candidate.slice(0, candidate.length - suffix.length));
529
+ const wildcardCaptureOf = (pattern, specifier) => Option.flatMap(stripPrefix(specifier, prefixOf(pattern)), (rest) => stripSuffix(rest, suffixOf(pattern)));
530
+ const exactCaptureOf = (pattern, specifier) => Option.map(Option.liftPredicate(specifier, (candidate) => candidate === pattern), () => "");
531
+ const captureOf = (pattern, specifier) => Boolean.match(pattern.includes("*"), {
532
+ onTrue: () => wildcardCaptureOf(pattern, specifier),
533
+ onFalse: () => exactCaptureOf(pattern, specifier)
534
+ });
535
+ const decide$14 = (command) => Result.succeed(Option.match(captureOf(command.pattern, command.specifier), {
536
+ onNone: () => AliasSpecifierUnmatched.make({}),
537
+ onSome: (capture) => AliasSpecifierCaptured.make({ capture })
538
+ }));
539
+ const captureAliasSpecifier = Workflow.make({
540
+ command: CaptureAliasSpecifierCommand,
541
+ decision: AliasCapture,
542
+ error: S.Never,
543
+ decide: decide$14
544
+ });
545
+ //#endregion
546
+ //#region src/CheckMutants.schema.ts
547
+ const TceOutcome = S.Literals(["original", "sibling"]);
548
+ const tceFieldOf = (tce) => Option.match(Option.fromUndefinedOr(tce), {
549
+ onNone: () => ({}),
550
+ onSome: (present) => ({ tce: present })
551
+ });
552
+ const SourceFileSchema = S.NonEmptyString.pipe(S.check(S.isPattern(/\.[^./\\]+$/u)));
553
+ const DiagnosticSeveritySchema = S.Literals([
554
+ "error",
555
+ "warning",
556
+ "suggestion",
557
+ "message"
558
+ ]);
559
+ var DiagnosticLine = class extends S.Class("DiagnosticLine")({
560
+ fileName: S.optional(SourceFileSchema),
561
+ position: S.String,
562
+ severity: DiagnosticSeveritySchema,
563
+ code: S.Finite,
564
+ text: S.String
565
+ }) {
566
+ get rendered() {
567
+ return this.position + this.severity + " TS" + this.code + ": " + this.text;
568
+ }
569
+ };
570
+ var MutantVerdict = class extends S.Class("MutantVerdict")({
571
+ id: Mutant.MutantId,
572
+ diagnostics: S.Array(DiagnosticLine),
573
+ tce: S.optional(TceOutcome)
574
+ }) {};
575
+ var CheckMutantsInput = class extends S.TaggedClass()("CheckMutantsInput", {
576
+ mutants: S.Array(Checker.CheckerMutantWire),
577
+ verdicts: S.Array(MutantVerdict)
578
+ }) {
579
+ static [Workflow.InstrumentationBrand] = {};
580
+ };
581
+ S.is(SourceFileSchema);
582
+ //#endregion
583
+ //#region src/classify-tce.workflow.ts
584
+ const TceDecisionTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TceDecision");
585
+ const TceClassification = S.Literals(["original", "sibling"]);
586
+ const TceCandidate = S.Struct({
587
+ id: S.String,
588
+ site: S.String,
589
+ emit: S.String
590
+ });
591
+ const candidateIdsAreDistinct = S.makeFilter((candidates) => Option.getOrUndefined(Option.map(Option.fromUndefinedOr(Mutant.duplicatedValue(candidates.map((candidate) => candidate.id))), (duplicated) => `candidate ids must identify distinct mutants, got "${duplicated}"`)), { arbitraryConstraint: { uniqueBy: (candidate) => candidate.id } });
592
+ const DistinctCandidates = S.Array(TceCandidate).check(candidateIdsAreDistinct);
593
+ var TceDecision = class extends S.TaggedClass()("TceDecision", {
594
+ id: S.String,
595
+ classification: TceClassification
596
+ }) {
597
+ [TceDecisionTypeId] = TceDecisionTypeId;
598
+ };
599
+ var ClassifyTceCommand = class extends S.TaggedClass()("ClassifyTceCommand", {
600
+ originalEmit: S.String,
601
+ candidates: DistinctCandidates
602
+ }) {
603
+ static [Workflow.InstrumentationBrand] = {};
604
+ };
605
+ const matchesEarlierSibling = (candidates, index) => Option.match(Option.fromUndefinedOr(candidates[index]), {
606
+ onNone: () => false,
607
+ onSome: (candidate) => Arr.some(Arr.take(candidates, index), (earlier) => Boolean.and(earlier.site === candidate.site, earlier.emit === candidate.emit))
608
+ });
609
+ const indexedOf = (command) => Arr.map(command.candidates, (candidate, index) => ({
610
+ candidate,
611
+ original: candidate.emit === command.originalEmit,
612
+ sibling: matchesEarlierSibling(command.candidates, index)
613
+ }));
614
+ const classifyOf$1 = (command) => Arr.filterMap(indexedOf(command), (entry) => Boolean.match(entry.original, {
615
+ onTrue: () => Result.succeed(TceDecision.make({
616
+ id: entry.candidate.id,
617
+ classification: "original"
618
+ })),
619
+ onFalse: () => Boolean.match(entry.sibling, {
620
+ onTrue: () => Result.succeed(TceDecision.make({
621
+ id: entry.candidate.id,
622
+ classification: "sibling"
623
+ })),
624
+ onFalse: () => Result.failVoid
625
+ })
626
+ }));
627
+ const classifyTce = Workflow.make({
628
+ command: ClassifyTceCommand,
629
+ decision: S.Array(TceDecision),
630
+ error: S.Never,
631
+ decide: (command) => Result.succeed(classifyOf$1(command))
632
+ });
633
+ //#endregion
634
+ //#region src/Compiler.schema.ts
635
+ /**
636
+ * Compiler — declarations for the TypeScript compiler and version guard.
637
+ *
638
+ * The error vocabulary every compiler operation refuses with; decoded and
639
+ * reported at the checker boundary, no I/O.
640
+ */
641
+ /** The installed TypeScript version is below the supported floor. */
642
+ var UnsupportedTypeScriptVersionError = class extends Schema.TaggedError()("UnsupportedTypeScriptVersionError", { version: Schema.String }) {
643
+ get message() {
644
+ return `@systemfsoftware/stryker-js-typescript-checker only supports typescript@7.0.0 or higher. Found typescript@${this.version}`;
645
+ }
646
+ };
647
+ /** Requested file is not present in the hybrid in-memory file map. */
648
+ var HybridFileNotFoundError = class extends Schema.TaggedError()("HybridFileNotFoundError", { fileName: Schema.String }) {
649
+ get message() {
650
+ return `'${this.fileName}' is part of your TypeScript project but could not be found on disk`;
651
+ }
652
+ };
653
+ var HybridMutantOutsideFileError = class extends Schema.TaggedError()("HybridMutantOutsideFileError", { fileName: Schema.String }) {
654
+ get message() {
655
+ return `A mutant's location falls outside '${this.fileName}'`;
656
+ }
657
+ };
658
+ /**
659
+ * Every way the TypeScript compiler can fail while serving a check.
660
+ * One tagged error — callers branch only on failure itself; `reason` keeps
661
+ * cases distinguishable in reports.
662
+ */
663
+ var CompilerFailed = class extends Schema.TaggedError()("CompilerFailed", {
664
+ reason: Schema.Literals([
665
+ "not-initialized",
666
+ "no-projects",
667
+ "unknown-file-node",
668
+ "file-not-in-project",
669
+ "mutant-outside-file",
670
+ "program-digest-unavailable"
671
+ ]),
672
+ subject: Schema.optional(Schema.String)
673
+ }) {
674
+ get message() {
675
+ 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.when("program-digest-unavailable", () => `The loaded TypeScript program could not be identified: ${this.subject ?? "unknown input"}`), Match.exhaustive);
676
+ }
677
+ };
678
+ var InvalidCheckerOptions = class extends Schema.TaggedError()("InvalidCheckerOptions", { detail: Schema.String }) {
679
+ code = "invalid-checker-options";
680
+ nextAction = "Set typescriptChecker.importerCheck to 'location-rule' or 'always', or remove it, and remove every other key from the typescriptChecker block";
681
+ get message() {
682
+ return `typescript checker (${this.code}): the typescriptChecker options are invalid: ${this.detail}. ${this.nextAction}`;
683
+ }
684
+ };
685
+ var DuplicateMutantIds = class extends Schema.TaggedError()("DuplicateMutantIds", { detail: Schema.String }) {
686
+ code = "duplicate-mutant-ids";
687
+ nextAction = "Send each mutant id once per check call";
688
+ get message() {
689
+ return `typescript checker (${this.code}): one check call named the same mutant more than once: ${this.detail}. ${this.nextAction}`;
690
+ }
691
+ };
692
+ var DryRunCompileErrors = class extends Schema.TaggedError()("DryRunCompileErrors", { text: Schema.String }) {
693
+ get message() {
694
+ return `Typescript error(s) found in dry run compilation: ${this.text}`;
695
+ }
696
+ };
697
+ //#endregion
698
+ //#region src/CheckRound.schema.ts
699
+ const RoundsTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/CheckRounds");
700
+ var SoloRound = class extends S.TaggedClass()("SoloRound", { id: Mutant.MutantId }) {
701
+ [RoundsTypeId] = RoundsTypeId;
702
+ };
703
+ var SharedRound = class extends S.TaggedClass()("SharedRound", { ids: S.Array(Mutant.MutantId).check(S.isMinLength(2)) }) {
704
+ [RoundsTypeId] = RoundsTypeId;
705
+ };
706
+ const CheckRound = S.Union([SoloRound, SharedRound]);
707
+ const CheckRounds = S.Array(CheckRound);
708
+ const roundOfLayer = ([id, ...others]) => Arr.match(others, {
709
+ onEmpty: () => SoloRound.make({ id }),
710
+ onNonEmpty: (rest) => SharedRound.make({ ids: [id, ...rest] })
711
+ });
712
+ const ConclusionTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/SharedRoundConclusion");
713
+ var SharedRoundKept = class extends S.TaggedClass()("SharedRoundKept", {}) {
714
+ [ConclusionTypeId] = ConclusionTypeId;
715
+ };
716
+ var SharedRoundRedone = class extends S.TaggedClass()("SharedRoundRedone", {}) {
717
+ [ConclusionTypeId] = ConclusionTypeId;
718
+ };
719
+ const SharedRoundConclusion = S.Union([SharedRoundKept, SharedRoundRedone]);
720
+ S.is(SharedRound.fields.ids);
721
+ //#endregion
722
+ //#region src/conclude-shared-round.workflow.ts
723
+ const everyMemberTakesShortcut = (command) => Boolean.and(Arr.isReadonlyArrayNonEmpty(command.decisions), Arr.every(command.decisions, (decision) => Option.exists(decision, takesShortcut)));
724
+ const decide$13 = (command) => Result.succeed(Boolean.match(everyMemberTakesShortcut(command), {
725
+ onTrue: () => SharedRoundKept.make({}),
726
+ onFalse: () => SharedRoundRedone.make({})
727
+ }));
728
+ const concludeSharedRound = Workflow.make({
729
+ command: ConcludeSharedRoundCommand,
730
+ decision: SharedRoundConclusion,
731
+ error: S.Never,
732
+ decide: decide$13
733
+ });
734
+ //#endregion
735
+ //#region src/FileIds.schema.ts
736
+ const FileIdsTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/FileIds");
737
+ const FileMutant = S.Struct({
738
+ fileName: S.String,
739
+ id: Mutant.MutantId
740
+ });
741
+ S.Array(FileMutant);
742
+ var FileIds = class extends S.TaggedClass()("FileIds", {
743
+ fileName: S.String,
744
+ ids: S.NonEmptyArray(Mutant.MutantId)
745
+ }) {
746
+ [FileIdsTypeId] = FileIdsTypeId;
747
+ };
748
+ S.Array(FileIds);
749
+ const emptyGrouping = {
750
+ files: [],
751
+ idsByFile: HashMap.empty()
752
+ };
753
+ const adding = (grouping, mutant) => Option.match(HashMap.get(grouping.idsByFile, mutant.fileName), {
754
+ onNone: () => ({
755
+ files: [...grouping.files, mutant.fileName],
756
+ idsByFile: HashMap.set(grouping.idsByFile, mutant.fileName, [mutant.id])
757
+ }),
758
+ onSome: (ids) => ({
759
+ ...grouping,
760
+ idsByFile: HashMap.set(grouping.idsByFile, mutant.fileName, Arr.append(ids, mutant.id))
761
+ })
762
+ });
763
+ const fileIdsOf = (mutants) => {
764
+ const grouping = Arr.reduce(mutants, emptyGrouping, adding);
765
+ return Arr.getSomes(Arr.map(grouping.files, (fileName) => Option.map(HashMap.get(grouping.idsByFile, fileName), (ids) => FileIds.make({
766
+ fileName,
767
+ ids
768
+ }))));
769
+ };
770
+ //#endregion
771
+ //#region src/group-mutants.workflow.ts
772
+ const GroupingTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/Grouping");
773
+ var MutantGroup = class extends S.TaggedClass()("MutantGroup", { ids: S.Array(S.String) }) {
774
+ [GroupingTypeId] = GroupingTypeId;
775
+ };
776
+ const MutantGroups = S.Array(MutantGroup);
777
+ const fileBatchesOf = (mutants) => Arr.map(fileIdsOf(mutants), (file) => file.ids);
778
+ const emptyPacking = {
779
+ groups: [],
780
+ current: [],
781
+ currentSize: 0
782
+ };
783
+ const fitsWithin = (packing, bound, ids) => Boolean.or(packing.current.length === 0, packing.currentSize + ids.length <= bound);
784
+ const packFile = (bound) => (packing, ids) => Boolean.match(fitsWithin(packing, bound, ids), {
785
+ onTrue: () => ({
786
+ ...packing,
787
+ current: [...packing.current, ...ids],
788
+ currentSize: packing.currentSize + ids.length
789
+ }),
790
+ onFalse: () => ({
791
+ groups: [...packing.groups, packing.current],
792
+ current: ids,
793
+ currentSize: ids.length
794
+ })
795
+ });
796
+ const closePacking = (packing) => Boolean.match(packing.current.length === 0, {
797
+ onTrue: () => packing.groups,
798
+ onFalse: () => [...packing.groups, packing.current]
799
+ });
800
+ const packBatches = (bound, batches) => closePacking(Arr.reduce(batches, emptyPacking, packFile(bound)));
801
+ const decide$12 = (command) => Result.succeed(Arr.map(packBatches(command.bound, fileBatchesOf(command.mutants)), (ids) => MutantGroup.make({ ids })));
802
+ const groupMutants = Workflow.make({
803
+ command: GroupMutantsCommand,
804
+ decision: MutantGroups,
805
+ error: S.Never,
806
+ decide: decide$12
807
+ });
808
+ //#endregion
809
+ //#region src/program-digest.schema.ts
810
+ const ProgramFile = S.Struct({
811
+ fileName: S.String,
812
+ digest: S.String
813
+ });
814
+ const entryLineOf = (kind, entry) => `${kind}\u0000${entry.fileName}\u0000${entry.digest}`;
815
+ const programKeyOf = (input) => [
816
+ `typescript\u0000${input.typescriptVersion}`,
817
+ `checker\u0000${input.checkerVersion}`,
818
+ `options\u0000${input.checkerOptionsJson}`,
819
+ ...Arr.sort(Arr.map(input.sourceFiles, (entry) => entryLineOf("source", entry)), Order.String),
820
+ ...Arr.sort(Arr.map(input.tsconfigs, (entry) => entryLineOf("tsconfig", entry)), Order.String)
821
+ ].join("\n");
822
+ //#endregion
823
+ //#region src/identify-program.workflow.ts
824
+ var IdentifyProgramCommand = class extends S.TaggedClass()("IdentifyProgramCommand", {
825
+ typescriptVersion: S.String,
826
+ checkerVersion: S.String,
827
+ checkerOptionsJson: S.String,
828
+ sourceFiles: S.Array(ProgramFile),
829
+ tsconfigs: S.Array(ProgramFile)
830
+ }) {
831
+ static [Workflow.InstrumentationBrand] = {};
832
+ };
833
+ const IdentifyTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/IdentifyProgram");
834
+ var ProgramIdentified = class extends S.TaggedClass()("ProgramIdentified", { key: S.String }) {
835
+ [IdentifyTypeId] = IdentifyTypeId;
836
+ };
837
+ var ProgramUnidentified = class extends S.TaggedClass()("ProgramUnidentified", { reason: S.String }) {
838
+ [IdentifyTypeId] = IdentifyTypeId;
839
+ };
840
+ const ProgramIdentity = S.Union([ProgramIdentified, ProgramUnidentified]);
841
+ const decide$11 = (command) => Boolean.match(command.sourceFiles.length === 0, {
842
+ onTrue: () => Result.succeed(ProgramUnidentified.make({ reason: "the program has no source files" })),
843
+ onFalse: () => Result.succeed(ProgramIdentified.make({ key: programKeyOf(command) }))
844
+ });
845
+ const identifyProgram = Workflow.make({
846
+ command: IdentifyProgramCommand,
847
+ decision: ProgramIdentity,
848
+ error: S.Never,
849
+ decide: decide$11
850
+ });
851
+ //#endregion
852
+ //#region src/override-tsconfig-options.workflow.ts
853
+ const OverrideTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TsconfigOverride");
854
+ var ProjectReferencesOverride = class extends S.TaggedClass()("ProjectReferencesOverride", { text: S.String }) {
855
+ [OverrideTypeId] = OverrideTypeId;
856
+ };
857
+ var SingleProjectOverride = class extends S.TaggedClass()("SingleProjectOverride", { text: S.String }) {
858
+ [OverrideTypeId] = OverrideTypeId;
859
+ };
860
+ const TsconfigOverride = S.Union([ProjectReferencesOverride, SingleProjectOverride]);
861
+ const COMPILER_OPTIONS_OVERRIDES = Object.freeze({
862
+ allowUnreachableCode: true,
863
+ noUnusedLocals: false,
864
+ noUnusedParameters: false,
865
+ skipLibCheck: true
866
+ });
867
+ const NO_EMIT_OPTIONS_FOR_SINGLE_PROJECT = Object.freeze({
868
+ noEmit: true,
869
+ incremental: false,
870
+ tsBuildInfoFile: void 0,
871
+ composite: false
872
+ });
873
+ const LOW_EMIT_OPTIONS_FOR_PROJECT_REFERENCES = Object.freeze({
874
+ emitDeclarationOnly: true,
875
+ noEmit: false,
876
+ declarationMap: true,
877
+ declaration: true,
878
+ composite: true
879
+ });
880
+ const compilerOptionsOf$2 = (document) => Option.getOrElse(Option.fromUndefinedOr(document.compilerOptions), () => ({}));
881
+ const withCompilerOverrides = (document, extraOptions) => ({
882
+ ...compilerOptionsOf$2(document),
883
+ ...COMPILER_OPTIONS_OVERRIDES,
884
+ ...extraOptions
885
+ });
886
+ const projectReferencesJson = (document) => {
887
+ const compilerOptions = withCompilerOverrides(document, LOW_EMIT_OPTIONS_FOR_PROJECT_REFERENCES);
888
+ delete compilerOptions["inlineSourceMap"];
889
+ delete compilerOptions["inlineSources"];
890
+ delete compilerOptions["mapRoute"];
891
+ delete compilerOptions["sourceRoot"];
892
+ delete compilerOptions["outFile"];
893
+ return JSON.stringify({
894
+ ...document,
895
+ compilerOptions
896
+ });
897
+ };
898
+ const singleProjectJson = (document) => {
899
+ const compilerOptions = withCompilerOverrides(document, NO_EMIT_OPTIONS_FOR_SINGLE_PROJECT);
900
+ Boolean.match(compilerOptions["declarationDir"] !== null, {
901
+ onTrue: () => {
902
+ delete compilerOptions["declarationDir"];
903
+ },
904
+ onFalse: () => void 0
905
+ });
906
+ const { references: _references, ...withoutReferences } = document;
907
+ return JSON.stringify({
908
+ ...withoutReferences,
909
+ compilerOptions
910
+ });
911
+ };
912
+ const decide$10 = (command) => Result.succeed(Boolean.match(command.buildMode, {
913
+ onTrue: () => ProjectReferencesOverride.make({ text: projectReferencesJson(command.document) }),
914
+ onFalse: () => SingleProjectOverride.make({ text: singleProjectJson(command.document) })
915
+ }));
916
+ const overrideTsconfigOptions = Workflow.make({
917
+ command: OverrideTsconfigOptionsCommand,
918
+ decision: TsconfigOverride,
919
+ error: S.Never,
920
+ decide: decide$10
921
+ });
922
+ //#endregion
923
+ //#region ../../node_modules/.pnpm/@jsr+std__jsonc@1.0.2/node_modules/@jsr/std__jsonc/parse.js
924
+ /**
925
+ * Converts a JSON with Comments (JSONC) string into an object.
926
+ *
927
+ * @example Usage
928
+ * ```ts
929
+ * import { parse } from "@std/jsonc";
930
+ * import { assertEquals } from "@std/assert";
931
+ *
932
+ * assertEquals(parse('{"foo": "bar"}'), { foo: "bar" });
933
+ * assertEquals(parse('{"foo": "bar", }'), { foo: "bar" });
934
+ * assertEquals(parse('{"foo": "bar", } /* comment *\/'), { foo: "bar" });
935
+ * ```
936
+ *
937
+ * @throws {SyntaxError} If the JSONC string is invalid.
938
+ * @param text A valid JSONC string.
939
+ * @returns The parsed JsonValue from the JSONC string.
940
+ */ function parse(text) {
941
+ if (new.target) throw new TypeError("Cannot create an instance: parse is not a constructor");
942
+ return new JsoncParser(text).parse();
943
+ }
944
+ var JsoncParser = class {
945
+ #whitespace = /* @__PURE__ */ new Set(" \r\n");
946
+ #numberEndToken = /* @__PURE__ */ new Set([..."[]{}:,/", ...this.#whitespace]);
947
+ #text;
948
+ #length;
949
+ #tokenized;
950
+ constructor(text) {
951
+ this.#text = `${text}`;
952
+ this.#length = this.#text.length;
953
+ this.#tokenized = this.#tokenize();
954
+ }
955
+ parse() {
956
+ const token = this.#getNext();
957
+ const res = this.#parseJsonValue(token);
958
+ const { done, value } = this.#tokenized.next();
959
+ if (!done) throw new SyntaxError(buildErrorMessage(value));
960
+ return res;
961
+ }
962
+ /** Read the next token. If the token is read to the end, it throws a SyntaxError. */ #getNext() {
963
+ const { done, value } = this.#tokenized.next();
964
+ if (done) throw new SyntaxError("Cannot parse JSONC: unexpected end of JSONC input");
965
+ return value;
966
+ }
967
+ /** Split the JSONC string into token units. Whitespace and comments are skipped. */ *#tokenize() {
968
+ for (let i = 0; i < this.#length; i++) {
969
+ if (this.#whitespace.has(this.#text[i])) continue;
970
+ if (this.#text[i] === "/" && this.#text[i + 1] === "*") {
971
+ i += 2;
972
+ let hasEndOfComment = false;
973
+ for (; i < this.#length; i++) if (this.#text[i] === "*" && this.#text[i + 1] === "/") {
974
+ hasEndOfComment = true;
975
+ break;
976
+ }
977
+ if (!hasEndOfComment) throw new SyntaxError("Cannot parse JSONC: unexpected end of JSONC input");
978
+ i++;
979
+ continue;
980
+ }
981
+ if (this.#text[i] === "/" && this.#text[i + 1] === "/") {
982
+ i += 2;
983
+ for (; i < this.#length; i++) if (this.#text[i] === "\n" || this.#text[i] === "\r") break;
984
+ continue;
985
+ }
986
+ switch (this.#text[i]) {
987
+ case "{":
988
+ yield {
989
+ type: "BeginObject",
990
+ position: i
991
+ };
992
+ break;
993
+ case "}":
994
+ yield {
995
+ type: "EndObject",
996
+ position: i
997
+ };
998
+ break;
999
+ case "[":
1000
+ yield {
1001
+ type: "BeginArray",
1002
+ position: i
1003
+ };
1004
+ break;
1005
+ case "]":
1006
+ yield {
1007
+ type: "EndArray",
1008
+ position: i
1009
+ };
1010
+ break;
1011
+ case ":":
1012
+ yield {
1013
+ type: "NameSeparator",
1014
+ position: i
1015
+ };
1016
+ break;
1017
+ case ",":
1018
+ yield {
1019
+ type: "ValueSeparator",
1020
+ position: i
1021
+ };
1022
+ break;
1023
+ case "\"": {
1024
+ const startIndex = i;
1025
+ let shouldEscapeNext = false;
1026
+ i++;
1027
+ for (; i < this.#length; i++) {
1028
+ if (this.#text[i] === "\"" && !shouldEscapeNext) break;
1029
+ shouldEscapeNext = this.#text[i] === "\\" && !shouldEscapeNext;
1030
+ }
1031
+ yield {
1032
+ type: "String",
1033
+ sourceText: this.#text.substring(startIndex, i + 1),
1034
+ position: startIndex
1035
+ };
1036
+ break;
1037
+ }
1038
+ default: {
1039
+ const startIndex = i;
1040
+ for (; i < this.#length; i++) if (this.#numberEndToken.has(this.#text[i])) break;
1041
+ i--;
1042
+ yield {
1043
+ type: "NullOrTrueOrFalseOrNumber",
1044
+ sourceText: this.#text.substring(startIndex, i + 1),
1045
+ position: startIndex
1046
+ };
1047
+ }
1048
+ }
1049
+ }
1050
+ }
1051
+ #parseJsonValue(value) {
1052
+ switch (value.type) {
1053
+ case "BeginObject": return this.#parseObject();
1054
+ case "BeginArray": return this.#parseArray();
1055
+ case "NullOrTrueOrFalseOrNumber": return this.#parseNullOrTrueOrFalseOrNumber(value);
1056
+ case "String": return this.#parseString(value);
1057
+ default: throw new SyntaxError(buildErrorMessage(value));
1058
+ }
1059
+ }
1060
+ #parseObject() {
1061
+ const target = {};
1062
+ while (true) {
1063
+ const token1 = this.#getNext();
1064
+ if (token1.type === "EndObject") return target;
1065
+ if (token1.type !== "String") throw new SyntaxError(buildErrorMessage(token1));
1066
+ const key = this.#parseString(token1);
1067
+ const token2 = this.#getNext();
1068
+ if (token2.type !== "NameSeparator") throw new SyntaxError(buildErrorMessage(token2));
1069
+ const token3 = this.#getNext();
1070
+ Object.defineProperty(target, key, {
1071
+ value: this.#parseJsonValue(token3),
1072
+ writable: true,
1073
+ enumerable: true,
1074
+ configurable: true
1075
+ });
1076
+ const token4 = this.#getNext();
1077
+ if (token4.type === "EndObject") return target;
1078
+ if (token4.type !== "ValueSeparator") throw new SyntaxError(buildErrorMessage(token4));
1079
+ }
1080
+ }
1081
+ #parseArray() {
1082
+ const target = [];
1083
+ while (true) {
1084
+ const token1 = this.#getNext();
1085
+ if (token1.type === "EndArray") return target;
1086
+ target.push(this.#parseJsonValue(token1));
1087
+ const token2 = this.#getNext();
1088
+ if (token2.type === "EndArray") return target;
1089
+ if (token2.type !== "ValueSeparator") throw new SyntaxError(buildErrorMessage(token2));
1090
+ }
1091
+ }
1092
+ #parseString(value) {
1093
+ let parsed;
1094
+ try {
1095
+ parsed = JSON.parse(value.sourceText);
1096
+ } catch {
1097
+ throw new SyntaxError(buildErrorMessage(value));
1098
+ }
1099
+ if (typeof parsed !== "string") throw new TypeError(`Parsed value is not a string: ${parsed}`);
1100
+ return parsed;
1101
+ }
1102
+ #parseNullOrTrueOrFalseOrNumber(value) {
1103
+ if (value.sourceText === "null") return null;
1104
+ if (value.sourceText === "true") return true;
1105
+ if (value.sourceText === "false") return false;
1106
+ let parsed;
1107
+ try {
1108
+ parsed = JSON.parse(value.sourceText);
1109
+ } catch {
1110
+ throw new SyntaxError(buildErrorMessage(value));
1111
+ }
1112
+ if (typeof parsed !== "number") throw new TypeError(`Parsed value is not a number: ${parsed}`);
1113
+ return parsed;
1114
+ }
1115
+ };
1116
+ function buildErrorMessage({ type, sourceText, position }) {
1117
+ let token = "";
1118
+ switch (type) {
1119
+ case "BeginObject":
1120
+ token = "{";
1121
+ break;
1122
+ case "EndObject":
1123
+ token = "}";
1124
+ break;
1125
+ case "BeginArray":
1126
+ token = "[";
1127
+ break;
1128
+ case "EndArray":
1129
+ token = "]";
1130
+ break;
1131
+ case "NameSeparator":
1132
+ token = ":";
1133
+ break;
1134
+ case "ValueSeparator":
1135
+ token = ",";
1136
+ break;
1137
+ case "NullOrTrueOrFalseOrNumber":
1138
+ case "String": token = 30 < sourceText.length ? `${sourceText.slice(0, 30)}...` : sourceText;
1139
+ }
1140
+ return `Cannot parse JSONC: unexpected token "${token}" in JSONC at position ${position}`;
1141
+ }
1142
+ //#endregion
1143
+ //#region src/parse-tsconfig-text.workflow.ts
1144
+ const TsconfigTextTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TsconfigText");
1145
+ var TsconfigParsed = class extends S.TaggedClass()("TsconfigParsed", { document: TsConfigDocumentSchema }) {
1146
+ [TsconfigTextTypeId] = TsconfigTextTypeId;
1147
+ };
1148
+ var TsconfigRefused = class extends S.TaggedClass()("TsconfigRefused", { reason: S.String }) {
1149
+ [TsconfigTextTypeId] = TsconfigTextTypeId;
1150
+ };
1151
+ const TsconfigTextDecision = S.Union([TsconfigParsed, TsconfigRefused]);
1152
+ const reasonOfThrown = (cause) => Option.getOrElse(Option.map(Option.liftPredicate(cause, (error) => error instanceof Error), (error) => error.message), () => "a non-Error value was thrown");
1153
+ const documentIssueOf = (value) => new SchemaIssue.InvalidValue({ message: Result.match(S.decodeUnknownResult(TsConfigDocumentSchema)(value), {
1154
+ onFailure: (error) => error.message,
1155
+ onSuccess: () => "expected a TypeScript configuration object"
1156
+ }) });
1157
+ const parseJsonc = (jsonText) => Result.match(Result.try({
1158
+ try: () => parse(jsonText.replace(/^\uFEFF/, "")),
1159
+ catch: (cause) => cause
1160
+ }), {
1161
+ onFailure: (cause) => Result.fail(new SchemaIssue.InvalidValue({ message: reasonOfThrown(cause) })),
1162
+ onSuccess: (value) => Result.mapError(S.decodeUnknownResult(S.Json)(value), (error) => new SchemaIssue.InvalidValue({ message: error.message }))
1163
+ });
1164
+ const documentOf = (value) => Option.match(Option.liftPredicate(value, S.is(TsConfigDocumentSchema)), {
1165
+ onNone: () => Result.fail(documentIssueOf(value)),
1166
+ onSome: () => Result.mapError(S.decodeUnknownResult(TsConfigDocumentSchema)(value), (error) => new SchemaIssue.InvalidValue({ message: error.message }))
1167
+ });
1168
+ const decodeText = (jsonText) => Result.flatMap(parseJsonc(jsonText), documentOf);
1169
+ const TsConfigText = S.String.pipe(S.decodeTo(TsConfigDocumentSchema, SchemaTransformation.transformEffect({
1170
+ decode: (jsonText) => Result.match(decodeText(jsonText), {
1171
+ onFailure: (issue) => Effect.fail(issue),
1172
+ onSuccess: (document) => Effect.succeed(document)
1173
+ }),
1174
+ encode: (document) => Effect.succeed(JSON.stringify(document))
1175
+ })));
1176
+ const decide$9 = (command) => Result.succeed(Result.match(S.decodeResult(TsConfigText)(command.text), {
1177
+ onFailure: (error) => TsconfigRefused.make({ reason: error.message }),
1178
+ onSuccess: (document) => TsconfigParsed.make({ document })
1179
+ }));
1180
+ const parseTsconfigText = Workflow.make({
1181
+ command: ParseTsconfigTextCommand,
1182
+ decision: TsconfigTextDecision,
1183
+ error: S.Never,
1184
+ decide: decide$9
1185
+ });
1186
+ //#endregion
1187
+ //#region src/plan-check-rounds.workflow.ts
1188
+ const layerAt = (files, layer) => Option.liftPredicate(Arr.isReadonlyArrayNonEmpty)(Arr.getSomes(Arr.map(files, (file) => Arr.get(file.ids, layer))));
1189
+ const layerCountOf = (files) => Arr.reduce(files, 0, (count, file) => Order.max(Order.Number)(count, file.ids.length));
1190
+ const layerRounds = (files) => Arr.getSomes(Arr.map(Arr.range(0, layerCountOf(files) - 1), (layer) => Option.map(layerAt(files, layer), roundOfLayer)));
1191
+ const ineligibleSolos = (candidates) => Arr.map(Arr.filter(candidates, (candidate) => !candidate.eligible), (candidate) => SoloRound.make({ id: candidate.id }));
1192
+ const planRounds = (candidates) => Arr.appendAll(ineligibleSolos(candidates), layerRounds(fileIdsOf(Arr.filter(candidates, (candidate) => candidate.eligible))));
1193
+ const decide$8 = (command) => Result.succeed(planRounds(command.candidates));
1194
+ const planCheckRounds = Workflow.make({
1195
+ command: PlanCheckRoundsCommand,
1196
+ decision: CheckRounds,
1197
+ error: S.Never,
1198
+ decide: decide$8
1199
+ });
1200
+ //#endregion
1201
+ //#region src/plan-diagnostic-batches.workflow.ts
1202
+ const DiagnosticBatchSize = 64;
1203
+ const BatchesTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/DiagnosticBatches");
1204
+ var DiagnosticBatchesPlanned = class extends S.TaggedClass()("DiagnosticBatchesPlanned", { batches: S.String.pipe(S.Array, S.Array) }) {
1205
+ [BatchesTypeId] = BatchesTypeId;
1206
+ };
1207
+ var NoDiagnosticBatches = class extends S.TaggedClass()("NoDiagnosticBatches", {}) {
1208
+ [BatchesTypeId] = BatchesTypeId;
1209
+ };
1210
+ const DiagnosticBatches = S.Union([DiagnosticBatchesPlanned, NoDiagnosticBatches]);
1211
+ const diagnosticBatchesOf = (fileNames) => Arr.chunksOf(fileNames, DiagnosticBatchSize);
1212
+ const decide$7 = (command) => Result.succeed(Boolean.match(command.fileNames.length === 0, {
1213
+ onTrue: () => NoDiagnosticBatches.make({}),
1214
+ onFalse: () => DiagnosticBatchesPlanned.make({ batches: diagnosticBatchesOf(command.fileNames) })
1215
+ }));
1216
+ const planDiagnosticBatches = Workflow.make({
1217
+ command: PlanDiagnosticBatchesCommand,
1218
+ decision: DiagnosticBatches,
1219
+ error: S.Never,
1220
+ decide: decide$7
1221
+ });
1222
+ //#endregion
1223
+ //#region src/plan-resolution-candidates.workflow.ts
1224
+ const ExtensionlessTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/ResolutionCandidates");
1225
+ var ExtensionNamedPath = class extends S.TaggedClass()("ExtensionNamedPath", { candidates: S.Array(S.String) }) {
1226
+ [ExtensionlessTypeId] = ExtensionlessTypeId;
1227
+ };
1228
+ var ExtensionlessPath = class extends S.TaggedClass()("ExtensionlessPath", { candidates: S.Array(S.String) }) {
1229
+ [ExtensionlessTypeId] = ExtensionlessTypeId;
1230
+ };
1231
+ const ResolutionCandidates = S.Union([ExtensionNamedPath, ExtensionlessPath]);
1232
+ const withoutExtensionCandidates = (resolved) => [
1233
+ resolved,
1234
+ resolved + ".ts",
1235
+ resolved + ".tsx",
1236
+ resolved + ".d.ts",
1237
+ resolved + "/index.ts",
1238
+ resolved + "/index.tsx",
1239
+ resolved + "/index.d.ts",
1240
+ resolved + ".js",
1241
+ resolved + ".jsx",
1242
+ resolved + ".mjs",
1243
+ resolved + ".cjs",
1244
+ resolved + "/index.js",
1245
+ resolved + "/index.jsx",
1246
+ resolved + "/index.mjs",
1247
+ resolved + "/index.cjs"
1248
+ ];
1249
+ const withExtensionCandidates = (resolved, extension) => {
1250
+ const withoutExtension = resolved.slice(0, -extension.length);
1251
+ return [
1252
+ resolved,
1253
+ withoutExtension + ".ts",
1254
+ withoutExtension + ".tsx",
1255
+ withoutExtension + ".d.ts",
1256
+ withoutExtension + ".js",
1257
+ withoutExtension + ".jsx",
1258
+ withoutExtension + ".mjs",
1259
+ withoutExtension + ".cjs"
1260
+ ];
1261
+ };
1262
+ const decide$6 = (command) => Result.succeed(Boolean.match(command.extension === "", {
1263
+ onTrue: () => ExtensionlessPath.make({ candidates: withoutExtensionCandidates(command.resolved) }),
1264
+ onFalse: () => ExtensionNamedPath.make({ candidates: withExtensionCandidates(command.resolved, command.extension) })
1265
+ }));
1266
+ const planResolutionCandidates = Workflow.make({
1267
+ command: PlanResolutionCandidatesCommand,
1268
+ decision: ResolutionCandidates,
1269
+ error: S.Never,
1270
+ decide: decide$6
1271
+ });
1272
+ //#endregion
1273
+ //#region src/request-affected-files.workflow.ts
1274
+ const RequestTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/RequestAffectedFiles");
1275
+ var AffectedFilesRequested = class extends S.TaggedClass()("AffectedFilesRequested", { fileNames: S.Array(S.String) }) {
1276
+ [RequestTypeId] = RequestTypeId;
1277
+ };
1278
+ var NoAffectedFileRequested = class extends S.TaggedClass()("NoAffectedFileRequested", {}) {
1279
+ [RequestTypeId] = RequestTypeId;
1280
+ };
1281
+ const RequestedFiles = S.Union([AffectedFilesRequested, NoAffectedFileRequested]);
1282
+ const requestedFileNames = (presentFileNames, affectedFileNames) => Arr.filter(presentFileNames, (fileName) => HashSet.has(affectedFileNames, fileName));
1283
+ const decide$5 = (command) => {
1284
+ const requested = requestedFileNames(command.presentFileNames, HashSet.fromIterable(command.affectedFileNames));
1285
+ return Result.succeed(Boolean.match(requested.length === 0, {
1286
+ onTrue: () => NoAffectedFileRequested.make({}),
1287
+ onFalse: () => AffectedFilesRequested.make({ fileNames: requested })
1288
+ }));
1289
+ };
1290
+ const requestAffectedFiles = Workflow.make({
1291
+ command: RequestAffectedFilesCommand,
1292
+ decision: RequestedFiles,
1293
+ error: S.Never,
1294
+ decide: decide$5
1295
+ });
1296
+ //#endregion
1297
+ //#region src/resolve-package-exports.workflow.ts
1298
+ const PackageExportsTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/PackageExports");
1299
+ var ResolvePackageExportsCommand = class extends S.TaggedClass()("ResolvePackageExportsCommand", {
1300
+ exports: S.Json,
1301
+ subpath: S.String
1302
+ }) {
1303
+ static [Workflow.InstrumentationBrand] = {};
1304
+ };
1305
+ var PackageExportsResolved = class extends S.TaggedClass()("PackageExportsResolved", {
1306
+ targets: S.Array(S.String),
1307
+ terminal: S.Boolean
1308
+ }) {
1309
+ [PackageExportsTypeId] = PackageExportsTypeId;
1310
+ };
1311
+ var PackageExportsExcluded = class extends S.TaggedClass()("PackageExportsExcluded", {}) {
1312
+ [PackageExportsTypeId] = PackageExportsTypeId;
1313
+ };
1314
+ var PackageExportsUnresolved = class extends S.TaggedClass()("PackageExportsUnresolved", {}) {
1315
+ [PackageExportsTypeId] = PackageExportsTypeId;
1316
+ };
1317
+ const PackageExportsResolution = S.Union([
1318
+ PackageExportsResolved,
1319
+ PackageExportsExcluded,
1320
+ PackageExportsUnresolved
1321
+ ]);
1322
+ const ACTIVE_CONDITIONS = [
1323
+ "require",
1324
+ "types",
1325
+ "node",
1326
+ "default"
1327
+ ];
1328
+ const isString$1 = (value) => typeof value === "string";
1329
+ const isJsonArray$1 = (value) => Array.isArray(value);
1330
+ const isJsonObject$1 = (value) => Predicate.isObject(value);
1331
+ const isActiveCondition = (key) => ACTIVE_CONDITIONS.includes(key);
1332
+ const starPartsOf = (key) => {
1333
+ const parts = key.split("*");
1334
+ return Option.map(Option.filter(Option.all([Arr.head(parts), Arr.get(parts, 1)]), () => parts.length === 2), ([prefix, suffix]) => [prefix, suffix]);
1335
+ };
1336
+ const substituteStar = (target, star) => Option.match(star, {
1337
+ onNone: () => target,
1338
+ onSome: (capture) => target.replaceAll("*", capture)
1339
+ });
1340
+ const TargetsResolved = S.TaggedStruct("TargetsResolved", {
1341
+ targets: S.Array(S.String),
1342
+ terminated: S.Boolean
1343
+ });
1344
+ const SubpathExcluded = S.TaggedStruct("SubpathExcluded", {});
1345
+ const TryNextEntry = S.TaggedStruct("TryNextEntry", {});
1346
+ S.Union([
1347
+ TargetsResolved,
1348
+ SubpathExcluded,
1349
+ TryNextEntry
1350
+ ]);
1351
+ const targetsResolved = (targets, terminated) => TargetsResolved.make({
1352
+ targets,
1353
+ terminated
1354
+ });
1355
+ const SUBPATH_EXCLUDED = SubpathExcluded.make({});
1356
+ const TRY_NEXT_ENTRY = TryNextEntry.make({});
1357
+ const resolutionOf = (step) => Match.value(step).pipe(Match.tag("TargetsResolved", ({ targets, terminated }) => PackageExportsResolved.make({
1358
+ targets,
1359
+ terminal: terminated
1360
+ })), Match.tag("SubpathExcluded", () => PackageExportsExcluded.make({})), Match.tag("TryNextEntry", () => PackageExportsUnresolved.make({})), Match.exhaustive);
1361
+ const appendTargets = (entries, star, accumulated) => Option.match(Arr.head(entries), {
1362
+ onNone: () => Boolean.match(accumulated.length === 0, {
1363
+ onTrue: () => TRY_NEXT_ENTRY,
1364
+ onFalse: () => targetsResolved(accumulated, false)
1365
+ }),
1366
+ onSome: (entry) => Match.value(resolveTarget(entry, star)).pipe(Match.tag("TargetsResolved", ({ targets, terminated }) => Boolean.match(terminated, {
1367
+ onTrue: () => targetsResolved([...accumulated, ...targets], true),
1368
+ onFalse: () => appendTargets(Arr.drop(entries, 1), star, [...accumulated, ...targets])
1369
+ })), Match.tag("SubpathExcluded", (excluded) => Boolean.match(accumulated.length === 0, {
1370
+ onTrue: () => excluded,
1371
+ onFalse: () => targetsResolved(accumulated, true)
1372
+ })), Match.tag("TryNextEntry", () => appendTargets(Arr.drop(entries, 1), star, accumulated)), Match.exhaustive)
1373
+ });
1374
+ const resolveConditional = (conditions, star) => appendTargets(Arr.map(Arr.filter(Object.entries(conditions), ([key]) => isActiveCondition(key)), ([, entry]) => entry), star, []);
1375
+ const INVALID_TARGET_SEGMENTS = [
1376
+ ".",
1377
+ "..",
1378
+ "node_modules"
1379
+ ];
1380
+ const hasInvalidTargetSegment = (target) => Arr.some(target.split("/").slice(1), (segment) => INVALID_TARGET_SEGMENTS.includes(segment));
1381
+ const isResolvableTarget = (target) => Boolean.and(target.startsWith("./"), Boolean.not(hasInvalidTargetSegment(target)));
1382
+ const resolveStringTarget = (target) => Boolean.match(isResolvableTarget(target), {
1383
+ onTrue: () => targetsResolved([target], false),
1384
+ onFalse: () => TRY_NEXT_ENTRY
1385
+ });
1386
+ function resolveTarget(value, star) {
1387
+ return Boolean.match(value === null, {
1388
+ onTrue: () => SUBPATH_EXCLUDED,
1389
+ onFalse: () => Option.match(Option.liftPredicate(value, isString$1), {
1390
+ onSome: (target) => resolveStringTarget(substituteStar(target, star)),
1391
+ onNone: () => Option.match(Option.liftPredicate(value, isJsonArray$1), {
1392
+ onSome: (entries) => appendTargets(entries, star, []),
1393
+ onNone: () => Option.match(Option.liftPredicate(value, isJsonObject$1), {
1394
+ onSome: (conditions) => resolveConditional(conditions, star),
1395
+ onNone: () => TRY_NEXT_ENTRY
1396
+ })
1397
+ })
1398
+ })
1399
+ });
1400
+ }
1401
+ const patternCaptureOf = (key, subpath) => Option.flatMap(starPartsOf(key), ([prefix, suffix]) => Option.map(Option.liftPredicate(subpath, (candidate) => Boolean.and(Boolean.and(candidate.startsWith(prefix), candidate.endsWith(suffix)), candidate.length >= prefix.length + suffix.length)), (candidate) => candidate.slice(prefix.length, candidate.length - suffix.length)));
1402
+ const patternKeyBaseLengthOf = (key) => Boolean.match(key.indexOf("*") === -1, {
1403
+ onTrue: () => key.length,
1404
+ onFalse: () => key.indexOf("*") + 1
1405
+ });
1406
+ const comparePatternKeysOf = (left, right) => Boolean.match(patternKeyBaseLengthOf(left) === patternKeyBaseLengthOf(right), {
1407
+ onTrue: () => right.length - left.length,
1408
+ onFalse: () => patternKeyBaseLengthOf(right) - patternKeyBaseLengthOf(left)
1409
+ });
1410
+ const bestPatternMatchOf = (map, subpath) => Option.map(Arr.reduce(Object.entries(map), Option.none(), (best, [key, value]) => Option.match(patternCaptureOf(key, subpath), {
1411
+ onNone: () => best,
1412
+ onSome: (star) => Option.match(best, {
1413
+ onNone: () => Option.some([
1414
+ key,
1415
+ value,
1416
+ star
1417
+ ]),
1418
+ onSome: (current) => Boolean.match(comparePatternKeysOf(key, current[0]) < 0, {
1419
+ onTrue: () => Option.some([
1420
+ key,
1421
+ value,
1422
+ star
1423
+ ]),
1424
+ onFalse: () => best
1425
+ })
1426
+ })
1427
+ })), ([, value, star]) => [value, star]);
1428
+ const subpathTargetOf = (map, subpath) => Option.match(Option.fromUndefinedOr(map[subpath]), {
1429
+ onSome: (value) => Option.some([value, Option.none()]),
1430
+ onNone: () => Option.map(bestPatternMatchOf(map, subpath), ([value, star]) => [value, Option.some(star)])
1431
+ });
1432
+ const hasSubpathKeys = (map) => Arr.some(Object.keys(map), (key) => key.startsWith("."));
1433
+ const whenRootSubpath = (subpath, atRoot) => Boolean.match(subpath === ".", {
1434
+ onTrue: atRoot,
1435
+ onFalse: () => Option.none()
1436
+ });
1437
+ const resolveExports = (exports, subpath) => Option.match(Option.filter(Option.liftPredicate(exports, isJsonObject$1), hasSubpathKeys), {
1438
+ onSome: (map) => Option.map(subpathTargetOf(map, subpath), ([value, star]) => resolveTarget(value, star)),
1439
+ onNone: () => whenRootSubpath(subpath, () => Option.some(resolveTarget(exports, Option.none())))
1440
+ });
1441
+ const decide$4 = (command) => Result.succeed(resolveExports(command.exports, command.subpath).pipe(Option.getOrElse(() => TRY_NEXT_ENTRY), resolutionOf));
1442
+ const resolvePackageExports = Workflow.make({
1443
+ command: ResolvePackageExportsCommand,
1444
+ decision: PackageExportsResolution,
1445
+ error: S.Never,
1446
+ decide: decide$4
1447
+ });
1448
+ //#endregion
1449
+ //#region src/emit-text.ts
1450
+ const SOURCE_MAP_COMMENT = /^\/\/# sourceMappingURL=.*$/gmu;
1451
+ const normalizeEmit = (emit) => emit.replace(/^\uFEFF/u, "").replace(/\r\n?/gu, "\n").replace(SOURCE_MAP_COMMENT, "").split("\n").map((line) => line.replace(/[ \t]+$/u, "")).filter((line) => line.length > 0).join("\n").trim();
1452
+ //#endregion
1453
+ //#region src/tce-emit.ts
1454
+ const sourceFileName = (index, extension) => `tce-input-${index}${extension}`;
1455
+ const EMITTED_EXTENSION = {
1456
+ ".mts": ".mjs",
1457
+ ".cts": ".cjs"
1458
+ };
1459
+ const emittedExtensionOf = (extension) => EMITTED_EXTENSION[extension] ?? ".js";
1460
+ const compilerOptionsOf$1 = (outDir, rootDir) => ({
1461
+ noEmit: false,
1462
+ noCheck: true,
1463
+ noEmitOnError: false,
1464
+ emitDeclarationOnly: false,
1465
+ declaration: false,
1466
+ declarationMap: false,
1467
+ sourceMap: false,
1468
+ composite: false,
1469
+ incremental: false,
1470
+ outDir,
1471
+ rootDir,
1472
+ skipLibCheck: true
1473
+ });
1474
+ const cliPathOf = Effect.gen(function* () {
1475
+ const path = yield* Path.Path;
1476
+ const packageFile = yield* path.fromFileUrl(new URL(import.meta.resolve("typescript/package.json")));
1477
+ return path.join(path.dirname(packageFile), "bin", "tsc");
1478
+ });
1479
+ const writeInputs = (request, directory) => Effect.gen(function* () {
1480
+ const fs = yield* FileSystem.FileSystem;
1481
+ const path = yield* Path.Path;
1482
+ const originalName = sourceFileName(0, request.sourceExtension);
1483
+ yield* fs.writeFileString(path.join(directory, originalName), request.originalContent);
1484
+ const names = Arr.map(request.mutants, (_, index) => sourceFileName(index + 1, request.sourceExtension));
1485
+ yield* Effect.forEach(request.mutants, (mutant, index) => fs.writeFileString(path.join(directory, sourceFileName(index + 1, request.sourceExtension)), mutant.content), { discard: true });
1486
+ return [originalName, ...names];
1487
+ }).pipe(Effect.orDie);
1488
+ const everyEmitUnderOutDir = (path, directory) => {
1489
+ const outDir = path.join(directory, "out");
1490
+ const filesystemRoot = path.parse(directory).root;
1491
+ return {
1492
+ outDir,
1493
+ filesystemRoot,
1494
+ inputsOutDir: path.join(outDir, path.relative(filesystemRoot, directory))
1495
+ };
1496
+ };
1497
+ const tsconfigTextOf = (request, layout, files) => S.encodeEffect(S.fromJsonString(S.Unknown))({
1498
+ extends: request.tsconfigFile,
1499
+ compilerOptions: compilerOptionsOf$1(layout.outDir, layout.filesystemRoot),
1500
+ references: [],
1501
+ files,
1502
+ include: [],
1503
+ exclude: []
1504
+ });
1505
+ const runEmit = (request, directory) => Effect.gen(function* () {
1506
+ const fs = yield* FileSystem.FileSystem;
1507
+ const path = yield* Path.Path;
1508
+ const cli = yield* cliPathOf;
1509
+ const files = yield* writeInputs(request, directory);
1510
+ const layout = everyEmitUnderOutDir(path, directory);
1511
+ yield* fs.writeFileString(path.join(directory, "tsconfig.json"), yield* tsconfigTextOf(request, layout, files));
1512
+ yield* Effect.scoped(ChildProcess.make(cli, ["-p", path.join(directory, "tsconfig.json")], {
1513
+ cwd: directory,
1514
+ stdout: "ignore",
1515
+ stderr: "ignore"
1516
+ }).pipe(Effect.flatMap((handle) => handle.exitCode)));
1517
+ const readEmitted = (index) => Effect.map(fs.readFileString(path.join(layout.inputsOutDir, `tce-input-${index}${emittedExtensionOf(request.sourceExtension)}`)), normalizeEmit);
1518
+ const original = yield* readEmitted(0);
1519
+ const emits = yield* Effect.forEach(request.mutants, (_, index) => readEmitted(index + 1));
1520
+ return {
1521
+ original,
1522
+ byKey: HashMap.fromIterable(Arr.map(Arr.zip(request.mutants, emits), ([mutant, emit]) => [mutant.key, emit]))
1523
+ };
1524
+ }).pipe(Effect.orDie);
1525
+ const emitNormalized = (request) => Effect.flatMap(FileSystem.FileSystem, (fs) => Effect.flatMap(fs.makeTempDirectory({ prefix: "stryker-tce-" }), (directory) => runEmit(request, directory).pipe(Effect.ensuring(fs.remove(directory, {
1526
+ recursive: true,
1527
+ force: true
1528
+ }).pipe(Effect.ignore)), Effect.asSome))).pipe(Effect.orElseSucceed(() => Option.none()));
1529
+ //#endregion
1530
+ //#region src/trace-affected-files.workflow.ts
1531
+ const TraceTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TraceAffectedFiles");
1532
+ var MutatedFileAffected = class extends S.TaggedClass()("MutatedFileAffected", { fileName: S.String }) {
1533
+ [TraceTypeId] = TraceTypeId;
1534
+ };
1535
+ var DependentFileAffected = class extends S.TaggedClass()("DependentFileAffected", { fileName: S.String }) {
1536
+ [TraceTypeId] = TraceTypeId;
1537
+ };
1538
+ const AffectedFiles = S.Array(S.Union([MutatedFileAffected, DependentFileAffected]));
1539
+ 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))));
1540
+ const dependentsOfFile = (dependents, fileName) => Option.getOrElse(HashMap.get(dependents, fileName), () => HashSet.empty());
1541
+ const closeOverDependents = (dependents, affected) => {
1542
+ const grown = HashSet.union(affected, HashSet.fromIterable(Arr.flatMap(Arr.fromIterable(affected), (fileName) => Arr.fromIterable(dependentsOfFile(dependents, fileName)))));
1543
+ return Boolean.match(HashSet.size(grown) === HashSet.size(affected), {
1544
+ onTrue: () => grown,
1545
+ onFalse: () => closeOverDependents(dependents, grown)
1546
+ });
1547
+ };
1548
+ const affectedEvents = (seed, affected) => Arr.map(Arr.fromIterable(affected), (fileName) => Boolean.match(HashSet.has(seed, fileName), {
1549
+ onTrue: () => MutatedFileAffected.make({ fileName }),
1550
+ onFalse: () => DependentFileAffected.make({ fileName })
1551
+ }));
1552
+ const decide$3 = (command) => {
1553
+ const seed = HashSet.fromIterable(command.mutatedFileNames);
1554
+ return Result.succeed(affectedEvents(seed, closeOverDependents(dependentsOf(command.importsByFile), seed)));
1555
+ };
1556
+ const traceAffectedFiles = Workflow.make({
1557
+ command: TraceAffectedFilesCommand,
1558
+ decision: AffectedFiles,
1559
+ error: S.Never,
1560
+ decide: decide$3
1561
+ });
1562
+ //#endregion
1563
+ //#region src/ts-files.handle.ts
1564
+ const TypeId$2 = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TSFiles");
1565
+ const normalizeFileName$2 = (fileName) => fileName.replace(/\\/g, "/");
1566
+ const isBuildInfoFile = (fileName) => normalizeFileName$2(fileName).endsWith(".tsbuildinfo");
1567
+ const TSFiles = Handle.make()(TypeId$2);
1568
+ TSFiles.is;
1569
+ const stateOf = (self) => TSFiles.slot(self);
1570
+ const emptySources = {
1571
+ files: HashMap.empty(),
1572
+ overrides: HashMap.empty()
1573
+ };
1574
+ const make$1 = (host) => TSFiles.make({}, {
1575
+ host,
1576
+ snapshot: { current: emptySources }
1577
+ });
1578
+ const publish = (state, next) => Effect.sync(() => {
1579
+ state.snapshot.current = next(state.snapshot.current);
1580
+ });
1581
+ const makeScriptFile = (content, fileName, now) => ({
1582
+ content,
1583
+ fileName,
1584
+ originalContent: content,
1585
+ modifiedTime: now,
1586
+ lineStarts: lineStartsOf(content)
1587
+ });
1588
+ const withContent = (file, content, now) => ({
1589
+ ...file,
1590
+ content,
1591
+ modifiedTime: now
1592
+ });
1593
+ 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));
1594
+ const resetScriptFile = (file, now) => ({
1595
+ ...file,
1596
+ content: file.originalContent,
1597
+ modifiedTime: now
1598
+ });
1599
+ const now = Effect.map(Clock.currentTimeMillis, DateTime.makeUnsafe);
1600
+ const readFromDisk = Effect.fnUntraced(function* (state, fileName) {
1601
+ const at = yield* now;
1602
+ const file = Option.map(yield* Effect.option(state.host.readFileString(fileName)), (content) => makeScriptFile(content, fileName, at));
1603
+ yield* publish(state, (sources) => ({
1604
+ ...sources,
1605
+ files: HashMap.set(sources.files, fileName, file)
1606
+ }));
1607
+ return file;
1608
+ });
1609
+ const getFile = dual(2, (self, fileName) => {
1610
+ const state = stateOf(self);
1611
+ const normalized = normalizeFileName$2(fileName);
1612
+ return Option.match(HashMap.get(state.snapshot.current.files, normalized), {
1613
+ onNone: () => readFromDisk(state, normalized),
1614
+ onSome: Effect.succeed
1615
+ });
1616
+ });
1617
+ const mutateFile = dual(3, Effect.fnUntraced(function* (self, fileName, mutant) {
1618
+ const state = stateOf(self);
1619
+ const at = yield* now;
1620
+ const file = yield* getFile(self, fileName);
1621
+ yield* Option.match(file, {
1622
+ onNone: () => Effect.fail(HybridFileNotFoundError.make({ fileName })),
1623
+ onSome: (found) => Option.match(mutateScriptFile(found, mutant, at), {
1624
+ onNone: () => Effect.fail(HybridMutantOutsideFileError.make({ fileName })),
1625
+ onSome: (mutated) => publish(state, (sources) => ({
1626
+ ...sources,
1627
+ files: HashMap.set(sources.files, normalizeFileName$2(fileName), Option.some(mutated))
1628
+ }))
1629
+ })
1630
+ });
1631
+ }));
1632
+ const resetFile = dual(2, Effect.fnUntraced(function* (self, fileName) {
1633
+ const state = stateOf(self);
1634
+ const at = yield* now;
1635
+ const normalized = normalizeFileName$2(fileName);
1636
+ yield* Option.match(HashMap.get(state.snapshot.current.files, normalized), {
1637
+ onNone: () => Effect.void,
1638
+ onSome: Option.match({
1639
+ onNone: () => Effect.void,
1640
+ onSome: (file) => publish(state, (sources) => ({
1641
+ ...sources,
1642
+ files: HashMap.set(sources.files, normalized, Option.some(resetScriptFile(file, at)))
1643
+ }))
1644
+ })
1645
+ });
1646
+ }));
1647
+ const setOverrides = dual(2, (self, overrides) => publish(stateOf(self), (sources) => ({
1648
+ ...sources,
1649
+ overrides
1650
+ })));
1651
+ const tsFileSystem = (self) => {
1652
+ const state = stateOf(self);
1653
+ const contentFromSources = (fileName) => Option.match(HashMap.get(state.snapshot.current.overrides, fileName), {
1654
+ onSome: (override) => override,
1655
+ onNone: () => Option.match(HashMap.get(state.snapshot.current.files, fileName), {
1656
+ onNone: () => void 0,
1657
+ onSome: Option.match({
1658
+ onNone: () => null,
1659
+ onSome: (file) => file.content
1660
+ })
1661
+ })
1662
+ });
1663
+ const existsInSources = (fileName) => Option.match(HashMap.get(state.snapshot.current.overrides, fileName), {
1664
+ onSome: () => true,
1665
+ onNone: () => Option.match(HashMap.get(state.snapshot.current.files, fileName), {
1666
+ onNone: () => void 0,
1667
+ onSome: Option.isSome
1668
+ })
1669
+ });
1670
+ return {
1671
+ readFile: (fileName) => Boolean.match(isBuildInfoFile(fileName), {
1672
+ onTrue: () => null,
1673
+ onFalse: () => contentFromSources(normalizeFileName$2(fileName))
1674
+ }),
1675
+ fileExists: (fileName) => Boolean.match(isBuildInfoFile(fileName), {
1676
+ onTrue: () => false,
1677
+ onFalse: () => existsInSources(normalizeFileName$2(fileName))
1678
+ }),
1679
+ directoryExists: () => void 0,
1680
+ getAccessibleEntries: () => void 0,
1681
+ realpath: () => void 0
1682
+ };
1683
+ };
1684
+ //#endregion
1685
+ //#region src/ts-compiler.handle.ts
1686
+ const TypeId$1 = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TSCompiler");
1687
+ const normalizeFileName$1 = (fileName) => fileName.replace(/\\/g, "/");
1688
+ const findSourceMapRegex = /\/\/# sourceMappingURL=(.+)$/m;
1689
+ const getSourceMappingURL = (content) => findSourceMapRegex.exec(content)?.[1];
1690
+ const isString = (value) => typeof value === "string";
1691
+ const isNonEmptyString = (value) => value !== void 0 && value !== "";
1692
+ const relativeSpecifierPattern = /^\.\.?\//;
1693
+ const CLEAN_SPECIFIER_PATTERN = /^["']|["']$/g;
1694
+ const ignoredGraphFileNamePattern = /\.d\.ts$|node_modules/;
1695
+ const emptyTally = {
1696
+ snapshotUpdates: 0,
1697
+ resplices: 0,
1698
+ tceBuilds: 0,
1699
+ tceMs: 0
1700
+ };
1701
+ const TSCompiler = Handle.make()(TypeId$1);
1702
+ TSCompiler.is;
1703
+ const runtimeOf = (self) => TSCompiler.slot(self);
1704
+ const decided = (result) => Result.match(result, {
1705
+ onFailure: (refused) => refused,
1706
+ onSuccess: (decision) => decision
1707
+ });
1708
+ const make = dual(2, Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerMake.name)(function* (options, services) {
1709
+ const files = make$1(services.host);
1710
+ const tsconfigFile = normalizeFileName$1(options.tsconfigFile);
1711
+ const state = yield* SynchronizedRef.make({
1712
+ api: void 0,
1713
+ snapshot: void 0,
1714
+ sourceFiles: HashMap.empty(),
1715
+ nodes: HashMap.empty(),
1716
+ lastMutants: [],
1717
+ lastMutatedFileNames: [],
1718
+ aliases: [],
1719
+ references: {},
1720
+ allTSConfigFiles: HashSet.fromIterable([tsconfigFile]),
1721
+ tsconfigFile
1722
+ });
1723
+ const tally = yield* Ref.make(emptyTally);
1724
+ return TSCompiler.make({}, {
1725
+ options,
1726
+ host: services.host,
1727
+ pathService: services.pathService,
1728
+ spawner: services.spawner,
1729
+ files,
1730
+ sourceFileSystem: tsFileSystem(files),
1731
+ state,
1732
+ tally
1733
+ });
1734
+ }));
1735
+ const minimumTypeScriptVersion = {
1736
+ major: 7,
1737
+ minor: 0,
1738
+ patch: 0
1739
+ };
1740
+ const versionComponent = (parts, index) => Number.parseInt(parts[index] ?? "0", 10);
1741
+ const splitVersion = (version) => {
1742
+ const parts = version.replace(/[-+][\s\S]*$/, "").split(".");
1743
+ return {
1744
+ major: versionComponent(parts, 0),
1745
+ minor: versionComponent(parts, 1),
1746
+ patch: versionComponent(parts, 2)
1747
+ };
1748
+ };
1749
+ const isNewerOrSame = (left, right) => {
1750
+ return ([
1751
+ left.major - right.major,
1752
+ left.minor - right.minor,
1753
+ left.patch - right.patch
1754
+ ].find((difference) => difference !== 0) ?? 0) >= 0;
1755
+ };
1756
+ const isSupportedTypeScriptVersion = (version) => {
1757
+ const parsed = splitVersion(version);
1758
+ return [
1759
+ parsed.major,
1760
+ parsed.minor,
1761
+ parsed.patch
1762
+ ].every((part) => !Number.isNaN(part)) && isNewerOrSame(parsed, minimumTypeScriptVersion);
1763
+ };
1764
+ const readPackageVersion = Effect.fnUntraced(function* (rt, packageUrl) {
1765
+ const packagePath = yield* rt.pathService.fromFileUrl(new URL(packageUrl)).pipe(Effect.orElseSucceed(() => ""));
1766
+ const text = yield* rt.host.readFileString(packagePath).pipe(Effect.orElseSucceed(() => ""));
1767
+ return Result.match(S.decodeResult(S.fromJsonString(S.Struct({ version: S.String })))(text), {
1768
+ onFailure: () => "",
1769
+ onSuccess: (pkg) => pkg.version
1770
+ });
1771
+ });
1772
+ const readTypescriptVersion = (rt) => readPackageVersion(rt, import.meta.resolve("typescript/package.json"));
1773
+ const readCheckerVersion = (rt) => readPackageVersion(rt, new URL("../package.json", import.meta.url));
1774
+ const isNonNullObjectOf = (value) => typeof value === "object" && value !== null;
1775
+ const isJsonObject = (value) => isNonNullObjectOf(value) && !Array.isArray(value);
1776
+ const isJsonArray = (value) => typeof value === "object" && Array.isArray(value);
1777
+ const canonicalEntriesOf = (object) => Arr.map(Arr.sort(Object.keys(object), Order.String), (key) => `${JSON.stringify(key)}:${canonicalJsonOf(object[key] ?? null)}`).join(",");
1778
+ const canonicalObjectOf = (value) => Option.match(Option.liftPredicate(value, isJsonObject), {
1779
+ onNone: () => JSON.stringify(value),
1780
+ onSome: (object) => `{${canonicalEntriesOf(object)}}`
1781
+ });
1782
+ const canonicalJsonOf = (value) => Option.match(Option.liftPredicate(value, isJsonArray), {
1783
+ onNone: () => canonicalObjectOf(value),
1784
+ onSome: (array) => `[${Arr.map(array, canonicalJsonOf).join(",")}]`
1785
+ });
1786
+ const checkerOptionsJsonOf = (options) => Option.match(Option.fromUndefinedOr(options["typescriptChecker"]), {
1787
+ onNone: () => Effect.succeed("{}"),
1788
+ onSome: (configured) => Result.match(S.decodeUnknownResult(S.Json)(configured), {
1789
+ onFailure: () => Effect.fail(CompilerFailed.make({
1790
+ reason: "program-digest-unavailable",
1791
+ subject: "checker options"
1792
+ })),
1793
+ onSuccess: (value) => Effect.succeed(canonicalJsonOf(value))
1794
+ })
1795
+ });
1796
+ const DIGEST_READ_CONCURRENCY = 32;
1797
+ const readProgramFiles = (rt, root, fileNames) => Effect.forEach(fileNames, (fileName) => Effect.map(Effect.mapError(rt.host.readFileString(fileName), () => CompilerFailed.make({
1798
+ reason: "program-digest-unavailable",
1799
+ subject: fileName
1800
+ })), (content) => ({
1801
+ fileName: normalizeFileName$1(rt.pathService.relative(root, fileName)),
1802
+ digest: sha256HexOf(content)
1803
+ })), { concurrency: DIGEST_READ_CONCURRENCY });
1804
+ const sortedSourceFileNamesOf = (programs) => Effect.map(Effect.forEach(programs, (program) => Effect.promise(() => program.getSourceFileNames())), (perProgram) => Arr.sort(Arr.dedupe(Arr.map(Arr.flatten(perProgram), normalizeFileName$1)), Order.String));
1805
+ const sha256HexOf = (content) => bytesToHex(sha256(utf8ToBytes(content)));
1806
+ const decidedProgramIdentity = (command) => {
1807
+ const identity = decided(identifyProgram(command));
1808
+ return Match.value(identity).pipe(Match.tag("ProgramIdentified", ({ key }) => Effect.succeed(Checker.ProgramDigest.make(sha256HexOf(key)))), Match.tag("ProgramUnidentified", ({ reason }) => Effect.fail(CompilerFailed.make({
1809
+ reason: "program-digest-unavailable",
1810
+ subject: reason
1811
+ }))), Match.exhaustive);
1812
+ };
1813
+ const programDigest = Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerProgramDigest.name)(function* (self) {
1814
+ const rt = runtimeOf(self);
1815
+ const programs = yield* programsOf(rt);
1816
+ const state = yield* SynchronizedRef.get(rt.state);
1817
+ const typescriptVersion = yield* readTypescriptVersion(rt);
1818
+ const checkerVersion = yield* readCheckerVersion(rt);
1819
+ yield* Boolean.match(Boolean.or(typescriptVersion === "", checkerVersion === ""), {
1820
+ onTrue: () => Effect.fail(CompilerFailed.make({
1821
+ reason: "program-digest-unavailable",
1822
+ subject: "toolchain version"
1823
+ })),
1824
+ onFalse: () => Effect.void
1825
+ });
1826
+ const checkerOptionsJson = yield* checkerOptionsJsonOf(rt.options);
1827
+ const root = rt.pathService.dirname(state.tsconfigFile);
1828
+ const sourceFiles = yield* readProgramFiles(rt, root, yield* sortedSourceFileNamesOf(programs));
1829
+ const tsconfigs = yield* readProgramFiles(rt, root, yield* tsConfigChainOf(rt, Arr.sort(Arr.fromIterable(state.allTSConfigFiles), Order.String)));
1830
+ return yield* decidedProgramIdentity(IdentifyProgramCommand.make({
1831
+ typescriptVersion,
1832
+ checkerVersion,
1833
+ checkerOptionsJson,
1834
+ sourceFiles,
1835
+ tsconfigs
1836
+ }));
1837
+ });
1838
+ const guardTypescriptVersion = (rt) => Effect.flatMap(readTypescriptVersion(rt), (version) => Boolean.match(isSupportedTypeScriptVersion(version), {
1839
+ onFalse: () => Effect.fail(UnsupportedTypeScriptVersionError.make({ version })),
1840
+ onTrue: () => Effect.void
1841
+ }));
1842
+ 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({
1843
+ file: fileName,
1844
+ reason
1845
+ }))), Match.exhaustive);
1846
+ const tsconfigDeclaresReferences = (fileName, jsonText) => Result.match(parseTsConfig(fileName, jsonText), {
1847
+ onFailure: () => false,
1848
+ onSuccess: (config) => config["references"] !== void 0
1849
+ });
1850
+ const overrideTextOf = (document, buildMode) => decided(overrideTsconfigOptions(OverrideTsconfigOptionsCommand.make({
1851
+ document,
1852
+ buildMode
1853
+ }))).text;
1854
+ const tsConfigReferencesOf = (config) => Option.getOrElse(Option.fromUndefinedOr(config.references), () => []);
1855
+ const referencedProjectsOf = (rt, config, fromDirName) => Arr.map(tsConfigReferencesOf(config), (reference) => {
1856
+ const resolved = rt.pathService.resolve(fromDirName, reference.path);
1857
+ return normalizeFileName$1(Boolean.match(rt.pathService.basename(resolved).endsWith(".json"), {
1858
+ onTrue: () => resolved,
1859
+ onFalse: () => rt.pathService.join(resolved, "tsconfig.json")
1860
+ }));
1861
+ });
1862
+ const TS_CONFIG_JSON_EXTENSION = ".json";
1863
+ const NODE_MODULES_DIRECTORY = "node_modules";
1864
+ const tsConfigExtendsOf = (config) => Option.match(Option.fromUndefinedOr(config["extends"]), {
1865
+ onNone: () => [],
1866
+ onSome: (declared) => typeof declared === "string" ? [declared] : [...declared]
1867
+ });
1868
+ const ancestorDirectoriesOf = (pathService, from) => {
1869
+ const directories = [from];
1870
+ let current = from;
1871
+ let parent = pathService.dirname(current);
1872
+ while (parent !== current) {
1873
+ directories.push(parent);
1874
+ current = parent;
1875
+ parent = pathService.dirname(current);
1876
+ }
1877
+ return directories;
1878
+ };
1879
+ const isRelativeSpecifier = (specifier) => specifier.startsWith("./") || specifier.startsWith("../");
1880
+ const withJsonExtension = (base) => base.endsWith(TS_CONFIG_JSON_EXTENSION) ? [base] : [base, `${base}${TS_CONFIG_JSON_EXTENSION}`];
1881
+ const SCOPE_SEGMENT_COUNT = 2;
1882
+ const packageNameLengthOf = (specifier) => Boolean.match(specifier.startsWith("@"), {
1883
+ onTrue: () => SCOPE_SEGMENT_COUNT,
1884
+ onFalse: () => 1
1885
+ });
1886
+ const subpathOf = (rest) => Boolean.match(rest === "", {
1887
+ onTrue: () => ".",
1888
+ onFalse: () => `./${rest}`
1889
+ });
1890
+ const packageSpecifierOf = (specifier) => {
1891
+ const segments = specifier.split("/");
1892
+ const nameLength = packageNameLengthOf(specifier);
1893
+ const packageName = segments.slice(0, nameLength).join("/");
1894
+ const rest = segments.slice(nameLength).join("/");
1895
+ return Option.map(Option.liftPredicate(packageName, (name) => name !== ""), (name) => ({
1896
+ packageName: name,
1897
+ subpath: subpathOf(rest)
1898
+ }));
1899
+ };
1900
+ const ABSENT_EXPORTS = [
1901
+ null,
1902
+ false,
1903
+ ""
1904
+ ];
1905
+ const declaresExports = (value) => !ABSENT_EXPORTS.includes(value);
1906
+ const readPackageManifestOf = (rt, packageDirectory) => rt.host.readFileString(normalizeFileName$1(rt.pathService.join(packageDirectory, "package.json"))).pipe(Effect.orElseSucceed(() => ""), Effect.map(S.decodeOption(S.fromJsonString(S.Struct({
1907
+ exports: S.optional(S.Json),
1908
+ tsconfig: S.optional(S.Json)
1909
+ })))));
1910
+ const readPackageExportsOf = (rt, directory, packageName) => Effect.map(readPackageManifestOf(rt, rt.pathService.join(directory, NODE_MODULES_DIRECTORY, packageName)), Option.flatMap((manifest) => Option.filter(Option.fromUndefinedOr(manifest.exports), declaresExports)));
1911
+ const readTsconfigFieldOf = (rt, packageDirectory) => Effect.map(readPackageManifestOf(rt, packageDirectory), Option.flatMap((manifest) => Option.filter(Option.liftPredicate(manifest.tsconfig, isString), isNonEmptyString)));
1912
+ const fileCandidatesOf = (fileName) => [...Arr.filter([fileName], (candidate) => candidate.endsWith(TS_CONFIG_JSON_EXTENSION)), `${fileName}${TS_CONFIG_JSON_EXTENSION}`];
1913
+ const directoryConfigOf = (pathService, directory) => normalizeFileName$1(pathService.join(directory, "tsconfig.json"));
1914
+ const legacyAncestorCandidatesOf = (rt, directory, specifier) => {
1915
+ const target = normalizeFileName$1(rt.pathService.join(directory, NODE_MODULES_DIRECTORY, specifier));
1916
+ return Effect.map(readTsconfigFieldOf(rt, target), (field) => ({
1917
+ candidates: [
1918
+ ...fileCandidatesOf(target),
1919
+ ...Option.match(field, {
1920
+ onNone: () => [],
1921
+ onSome: (named) => {
1922
+ const fieldTarget = normalizeFileName$1(rt.pathService.join(target, named));
1923
+ return [...fileCandidatesOf(fieldTarget), directoryConfigOf(rt.pathService, fieldTarget)];
1924
+ }
1925
+ }),
1926
+ directoryConfigOf(rt.pathService, target)
1927
+ ],
1928
+ stops: false
1929
+ }));
1930
+ };
1931
+ const exportsCandidatesOf = (pathService, directory, spec, exportsValue) => Match.value(resolvePackageExports(ResolvePackageExportsCommand.make({
1932
+ exports: exportsValue,
1933
+ subpath: spec.subpath
1934
+ })).pipe(decided)).pipe(Match.tag("PackageExportsResolved", ({ targets, terminal }) => ({
1935
+ candidates: Arr.map(targets, (target) => normalizeFileName$1(pathService.join(directory, NODE_MODULES_DIRECTORY, spec.packageName, target))),
1936
+ stops: terminal
1937
+ })), Match.tag("PackageExportsExcluded", () => ({
1938
+ candidates: [],
1939
+ stops: true
1940
+ })), Match.tag("PackageExportsUnresolved", () => ({
1941
+ candidates: [],
1942
+ stops: false
1943
+ })), Match.exhaustive);
1944
+ const bareAncestorCandidatesOf = (rt, directory, specifier, maybeSpec) => Option.match(maybeSpec, {
1945
+ onNone: () => legacyAncestorCandidatesOf(rt, directory, specifier),
1946
+ onSome: (spec) => readPackageExportsOf(rt, directory, spec.packageName).pipe(Effect.flatMap((maybeExports) => Option.match(maybeExports, {
1947
+ onNone: () => legacyAncestorCandidatesOf(rt, directory, specifier),
1948
+ onSome: (exportsValue) => Effect.succeed(exportsCandidatesOf(rt.pathService, directory, spec, exportsValue))
1949
+ })))
1950
+ });
1951
+ const throughFirstStopOf = (ancestors) => Arr.flatMap(Option.match(Arr.findFirstIndex(ancestors, (ancestor) => ancestor.stops), {
1952
+ onNone: () => ancestors,
1953
+ onSome: (index) => Arr.take(ancestors, index + 1)
1954
+ }), (ancestor) => ancestor.candidates);
1955
+ const tsConfigExtendsCandidatesOf = (rt, fromDirName, specifier) => Boolean.match(rt.pathService.isAbsolute(specifier) || isRelativeSpecifier(specifier), {
1956
+ onTrue: () => Effect.succeed(withJsonExtension(normalizeFileName$1(rt.pathService.resolve(fromDirName, specifier)))),
1957
+ onFalse: () => {
1958
+ const maybeSpec = packageSpecifierOf(specifier);
1959
+ return Effect.map(Effect.forEach(ancestorDirectoriesOf(rt.pathService, fromDirName), (directory) => bareAncestorCandidatesOf(rt, directory, specifier, maybeSpec)), throughFirstStopOf);
1960
+ }
1961
+ });
1962
+ const isFileOf = (rt, fileName) => rt.host.stat(fileName).pipe(Effect.map((info) => info.type === "File"), Effect.orElseSucceed(() => false));
1963
+ const firstExistingOf = (rt, candidates) => Option.match(Arr.head(candidates), {
1964
+ onNone: () => Effect.succeedNone,
1965
+ onSome: (candidate) => Effect.flatMap(isFileOf(rt, candidate), (present) => Boolean.match(present, {
1966
+ onTrue: () => Effect.succeedSome(candidate),
1967
+ onFalse: () => firstExistingOf(rt, Arr.drop(candidates, 1))
1968
+ }))
1969
+ });
1970
+ const resolveTsConfigExtends = (rt, fromDirName, specifier) => Effect.flatMap(tsConfigExtendsCandidatesOf(rt, fromDirName, specifier), (candidates) => Effect.flatMap(firstExistingOf(rt, candidates), (found) => Effect.fromOption(found, () => CompilerFailed.make({
1971
+ reason: "program-digest-unavailable",
1972
+ subject: `tsconfig extends "${specifier}"`
1973
+ }))));
1974
+ const extendedConfigsOf = (rt, fileName) => Effect.flatMap(readTsConfigText(rt, HashMap.empty(), fileName), (jsonText) => Result.match(parseTsConfig(fileName, jsonText), {
1975
+ onFailure: (failure) => Effect.fail(failure),
1976
+ onSuccess: (config) => Effect.forEach(tsConfigExtendsOf(config), (specifier) => resolveTsConfigExtends(rt, rt.pathService.dirname(fileName), specifier))
1977
+ }));
1978
+ const visitTsConfigChain = (rt, pending, visited, chain) => Option.match(Arr.head(pending), {
1979
+ onNone: () => Effect.succeed(chain),
1980
+ onSome: (fileName) => Boolean.match(HashSet.has(visited, fileName), {
1981
+ onTrue: () => visitTsConfigChain(rt, Arr.drop(pending, 1), visited, chain),
1982
+ onFalse: () => Effect.flatMap(extendedConfigsOf(rt, fileName), (extended) => visitTsConfigChain(rt, [...Arr.drop(pending, 1), ...extended], HashSet.add(visited, fileName), [...chain, fileName]))
1983
+ })
1984
+ });
1985
+ const tsConfigChainOf = (rt, seeds) => visitTsConfigChain(rt, seeds, HashSet.empty(), []);
1986
+ const compilerOptionsOf = (config) => Option.getOrElse(Option.fromUndefinedOr(config.compilerOptions), () => ({}));
1987
+ const aliasEntriesOf = (compilerOptions) => Object.entries(Option.getOrElse(S.decodeUnknownOption(PathAliasesSchema)(compilerOptions["paths"]), () => ({})));
1988
+ const pathAliasesOf = (pathService, fileName, config) => aliasEntriesOf(compilerOptionsOf(config)).map(([pattern, targets]) => ({
1989
+ pattern,
1990
+ targets,
1991
+ baseDir: pathService.dirname(fileName)
1992
+ }));
1993
+ const recordTsConfig = (rt, buildMode, walk, fileName, jsonText) => Result.match(parseTsConfig(fileName, jsonText), {
1994
+ onFailure: () => ({
1995
+ ...walk,
1996
+ overrides: HashMap.set(walk.overrides, fileName, jsonText)
1997
+ }),
1998
+ onSuccess: (config) => {
1999
+ const referenced = referencedProjectsOf(rt, config, rt.pathService.dirname(fileName));
2000
+ return {
2001
+ overrides: HashMap.set(walk.overrides, fileName, overrideTextOf(config, buildMode)),
2002
+ aliases: [...walk.aliases, ...pathAliasesOf(rt.pathService, fileName, config)],
2003
+ references: {
2004
+ ...walk.references,
2005
+ [fileName]: referenced
2006
+ },
2007
+ files: Arr.reduce(referenced, walk.files, (files, project) => HashSet.add(files, normalizeFileName$1(project))),
2008
+ processed: walk.processed
2009
+ };
2010
+ }
2011
+ });
2012
+ const enqueueUnseen = (walk, pending) => Arr.reduce(Arr.fromIterable(walk.files), pending, (queued, fileName) => Boolean.match(HashSet.has(walk.processed, fileName) || queued.includes(fileName), {
2013
+ onTrue: () => queued,
2014
+ onFalse: () => [...queued, fileName]
2015
+ }));
2016
+ const readTsConfigText = (rt, preRead, fileName) => Option.match(HashMap.get(preRead, fileName), {
2017
+ onNone: () => rt.host.readFileString(fileName).pipe(Effect.mapError(() => TsConfigNotFoundError.make({ file: fileName }))),
2018
+ onSome: (jsonText) => Effect.succeed(jsonText)
2019
+ });
2020
+ const walkTsConfigs = (rt, buildMode, walk, pending, preRead) => Option.match(Option.filter(Arr.head(pending), (fileName) => !HashSet.has(walk.processed, fileName)), {
2021
+ onNone: () => Effect.succeed(walk),
2022
+ onSome: (fileName) => Effect.flatMap(readTsConfigText(rt, preRead, fileName), (jsonText) => {
2023
+ const recorded = recordTsConfig(rt, buildMode, {
2024
+ ...walk,
2025
+ processed: HashSet.add(walk.processed, fileName)
2026
+ }, fileName, jsonText);
2027
+ return walkTsConfigs(rt, buildMode, recorded, enqueueUnseen(recorded, pending.slice(1)), preRead);
2028
+ })
2029
+ });
2030
+ const snapshotOf = (state) => Effect.fromOption(Option.fromUndefinedOr(state.snapshot), () => CompilerFailed.make({ reason: "not-initialized" }));
2031
+ const projectsOf = (rt) => Effect.flatMap(SynchronizedRef.get(rt.state), (state) => Effect.flatMap(snapshotOf(state), (snapshot) => {
2032
+ const projects = snapshot.getProjects();
2033
+ return Boolean.match(projects.length === 0, {
2034
+ onTrue: () => Effect.fail(CompilerFailed.make({
2035
+ reason: "no-projects",
2036
+ subject: state.tsconfigFile
2037
+ })),
2038
+ onFalse: () => Effect.succeed(projects)
2039
+ });
2040
+ }));
2041
+ const programsOf = (rt) => Effect.map(projectsOf(rt), (projects) => Arr.map(projects, (project) => project.program));
2042
+ const resolveFileName = (rt, fileName) => normalizeFileName$1(rt.pathService.resolve(fileName));
2043
+ const nodeSpanOf$1 = (node) => ({
2044
+ start: node.getStart(node.getSourceFile()),
2045
+ end: node.end
2046
+ });
2047
+ const childrenOf$1 = (node) => {
2048
+ const children = [];
2049
+ node.forEachChild((child) => {
2050
+ children.push(child);
2051
+ });
2052
+ return children;
2053
+ };
2054
+ const spanEqualsOf = (node, start, end) => {
2055
+ const span = nodeSpanOf$1(node);
2056
+ return span.start === start && span.end === end;
2057
+ };
2058
+ const spanContainsOf = (node, start, end) => {
2059
+ const span = nodeSpanOf$1(node);
2060
+ return span.start <= start && end <= span.end;
2061
+ };
2062
+ const hasSpanOf = (node, start, end) => {
2063
+ if (spanEqualsOf(node, start, end)) return true;
2064
+ return Arr.some(childrenOf$1(node), (child) => Boolean.and(spanContainsOf(child, start, end), hasSpanOf(child, start, end)));
2065
+ };
2066
+ const parseHeldOf = (sourceFile, file, mutant) => Option.match(offsetAt(file.lineStarts, mutant.location.start), {
2067
+ onNone: () => true,
2068
+ onSome: (start) => hasSpanOf(sourceFile, start, start + mutant.replacement.length)
2069
+ });
2070
+ const currentSourceFileOf = (rt, fileName) => Effect.flatMap(projectsOf(rt), (projects) => Effect.map(projectOfFile(projects, fileName), (owned) => Option.map(owned, (found) => found.sourceFile)));
2071
+ const editTreeOf = (rt, fileName) => Effect.flatMap(projectsOf(rt), (projects) => Effect.flatMap(projectOfFile(projects, fileName), (owned) => Option.match(owned, {
2072
+ onNone: () => Effect.succeedNone,
2073
+ onSome: (found) => Effect.asSome(Effect.map(Effect.promise(() => found.project.program.getSyntacticDiagnostics(fileName)), (diagnostics) => ({
2074
+ sourceFile: found.sourceFile,
2075
+ syntaxErrors: errorDiagnosticsOf(diagnostics).length > 0
2076
+ })))
2077
+ })));
2078
+ const parseHeldAfterSpliceOf = (rt, file, mutant, fileName) => Effect.gen(function* () {
2079
+ const sourceFile = yield* currentSourceFileOf(rt, fileName);
2080
+ return Option.match(Option.all([file, sourceFile]), {
2081
+ onNone: () => true,
2082
+ onSome: ([spliced, mutated]) => parseHeldOf(mutated, spliced, mutant)
2083
+ });
2084
+ });
2085
+ const parenthesizedSpliceOf = (rt, mutant, fileName, changedFiles) => Effect.flatMap(applyMutant(rt, mutant, "(" + mutant.replacement + ")"), () => Effect.andThen(Ref.update(rt.tally, (tally) => ({
2086
+ ...tally,
2087
+ resplices: tally.resplices + 1
2088
+ })), refreshSnapshot(rt, changedFiles)));
2089
+ const applyMutant = (rt, mutant, replacement) => Effect.flatMap(getFile(rt.files, resolveFileName(rt, mutant.fileName)), (file) => Effect.flatMap(Effect.fromOption(file, () => CompilerFailed.make({
2090
+ reason: "file-not-in-project",
2091
+ subject: mutant.fileName
2092
+ })), () => Effect.mapError(mutateFile(rt.files, resolveFileName(rt, mutant.fileName), {
2093
+ location: mutant.location,
2094
+ replacement
2095
+ }), (error) => Match.value(error).pipe(Match.tag("HybridFileNotFoundError", () => CompilerFailed.make({
2096
+ reason: "file-not-in-project",
2097
+ subject: mutant.fileName
2098
+ })), Match.tag("HybridMutantOutsideFileError", () => CompilerFailed.make({
2099
+ reason: "mutant-outside-file",
2100
+ subject: mutant.fileName
2101
+ })), Match.exhaustive))));
2102
+ const resetMutatedFiles = (rt, mutants) => Effect.forEach(mutants, (mutant) => resetFile(rt.files, resolveFileName(rt, mutant.fileName)), { discard: true });
2103
+ const hasOpenSnapshot = (state) => state.api !== void 0 && state.snapshot !== void 0;
2104
+ const updateSnapshot = Effect.fnUntraced(function* (rt, initialized, changedFiles) {
2105
+ const next = yield* Effect.promise(() => initialized.api.updateSnapshot({
2106
+ openProjects: Array.from(initialized.allTSConfigFiles),
2107
+ fileChanges: { changed: [...changedFiles] }
2108
+ }));
2109
+ yield* Effect.promise(() => initialized.snapshot.dispose());
2110
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
2111
+ ...prev,
2112
+ snapshot: next
2113
+ }));
2114
+ yield* Ref.update(rt.tally, (tally) => ({
2115
+ ...tally,
2116
+ snapshotUpdates: tally.snapshotUpdates + 1
2117
+ }));
2118
+ });
2119
+ const refreshSnapshot = (rt, changedFiles) => Effect.flatMap(SynchronizedRef.get(rt.state), (current) => Option.match(Option.liftPredicate(current, hasOpenSnapshot), {
2120
+ onNone: () => Effect.void,
2121
+ onSome: (initialized) => updateSnapshot(rt, initialized, changedFiles)
2122
+ }));
2123
+ const annotateDiagnosticSample = (diagnostics) => Boolean.match(diagnostics.length === 0, {
2124
+ onTrue: () => Effect.void,
2125
+ onFalse: () => Effect.annotateCurrentSpan({ "typescript.diagnostics.sample": Arr.map(Arr.take(diagnostics, 10), (diagnostic) => String(diagnostic.fileName) + ":" + diagnostic.code + ": " + diagnostic.text).join("; ") })
2126
+ });
2127
+ const carriesModuleSpecifier = (statement) => statement.kind === SyntaxKind.ImportDeclaration || statement.kind === SyntaxKind.ExportDeclaration;
2128
+ const moduleSpecifierOf = (statement, sourceFile) => Boolean.match(carriesModuleSpecifier(statement), {
2129
+ onTrue: () => {
2130
+ const children = [];
2131
+ statement.forEachChild((child) => {
2132
+ children.push(child);
2133
+ });
2134
+ return Option.map(Arr.findLast(children, (child) => child.kind === SyntaxKind.StringLiteral), (literal) => literal.getText(sourceFile));
2135
+ },
2136
+ onFalse: () => Option.none()
2137
+ });
2138
+ const keepSome = (option) => Option.match(option, {
2139
+ onNone: () => Result.failVoid,
2140
+ onSome: Result.succeed
2141
+ });
2142
+ const importsOf = (sourceFile) => [
2143
+ ...Arr.filterMap(sourceFile.statements, (statement) => keepSome(moduleSpecifierOf(statement, sourceFile))),
2144
+ ...Arr.map(sourceFile.referencedFiles, (reference) => reference.fileName),
2145
+ ...Arr.map(sourceFile.typeReferenceDirectives, (reference) => reference.fileName)
2146
+ ];
2147
+ const aliasTargetPaths = (pathService, aliases, specifier) => Arr.flatMap(aliases, (alias) => {
2148
+ const command = CaptureAliasSpecifierCommand.make({
2149
+ pattern: alias.pattern,
2150
+ specifier
2151
+ });
2152
+ const decision = decided(captureAliasSpecifier(command));
2153
+ return Match.value(decision).pipe(Match.tag("AliasSpecifierCaptured", ({ capture }) => Arr.map(alias.targets, (target) => normalizeFileName$1(pathService.resolve(alias.baseDir, target.replace("*", capture))))), Match.tag("AliasSpecifierUnmatched", () => []), Match.exhaustive);
2154
+ });
2155
+ const candidatePathsOf = (pathService, resolved) => {
2156
+ const command = PlanResolutionCandidatesCommand.make({
2157
+ resolved,
2158
+ extension: pathService.extname(resolved)
2159
+ });
2160
+ const decision = decided(planResolutionCandidates(command));
2161
+ return Match.value(decision).pipe(Match.tag("ExtensionNamedPath", ({ candidates }) => candidates), Match.tag("ExtensionlessPath", ({ candidates }) => candidates), Match.exhaustive);
2162
+ };
2163
+ const existingCandidateOf = (pathService, sourceFiles, resolved) => Arr.findFirst(candidatePathsOf(pathService, resolved), (candidate) => HashMap.has(sourceFiles, candidate));
2164
+ const resolveAliasedSpecifier = (pathService, aliases, sourceFiles, specifier) => Option.firstSomeOf(Arr.map(aliasTargetPaths(pathService, aliases, specifier), (target) => existingCandidateOf(pathService, sourceFiles, target)));
2165
+ const resolveSpecifier = (pathService, aliases, sourceFiles, fileName, specifier) => {
2166
+ const cleaned = specifier.replace(CLEAN_SPECIFIER_PATTERN, "");
2167
+ return Boolean.match(relativeSpecifierPattern.test(cleaned), {
2168
+ onFalse: () => resolveAliasedSpecifier(pathService, aliases, sourceFiles, cleaned),
2169
+ onTrue: () => Option.filter(existingCandidateOf(pathService, sourceFiles, normalizeFileName$1(pathService.resolve(pathService.dirname(fileName), cleaned))), (candidate) => candidate !== "")
2170
+ });
2171
+ };
2172
+ const readFileText = (rt, fileName) => Option.liftPredicate(rt.sourceFileSystem.readFile?.(fileName), isString);
2173
+ const onlySourceOf = (sources) => Boolean.match(sources.length !== 1, {
2174
+ onTrue: () => Option.none(),
2175
+ onFalse: () => Option.fromUndefinedOr(sources[0])
2176
+ });
2177
+ const sourceMapSourcesOf = (rt, content) => Result.match(S.decodeResult(S.fromJsonString(S.Struct({ sources: S.Array(S.String) })))(content), {
2178
+ onFailure: () => Option.none(),
2179
+ onSuccess: (map) => onlySourceOf(map.sources)
2180
+ });
2181
+ const sourceMappedFileName = (rt, declarationFileName) => Option.flatMap(Option.flatMap(readFileText(rt, declarationFileName), (content) => Option.liftPredicate(getSourceMappingURL(content), isNonEmptyString)), (reference) => {
2182
+ const sourceMapFileName = normalizeFileName$1(rt.pathService.resolve(rt.pathService.dirname(declarationFileName), reference));
2183
+ return Option.flatMap(Option.flatMap(readFileText(rt, sourceMapFileName), (content) => sourceMapSourcesOf(rt, content)), (source) => Option.some(normalizeFileName$1(rt.pathService.resolve(rt.pathService.dirname(sourceMapFileName), source))));
2184
+ });
2185
+ const resolveTSInputFile = (rt, dependencyFileName) => Boolean.match(dependencyFileName.endsWith(".d.ts"), {
2186
+ onFalse: () => dependencyFileName,
2187
+ onTrue: () => Option.getOrElse(sourceMappedFileName(rt, dependencyFileName), () => dependencyFileName)
2188
+ });
2189
+ const registeredEntry = (fileName) => Boolean.match(ignoredGraphFileNamePattern.test(fileName), {
2190
+ onTrue: () => Option.none(),
2191
+ onFalse: () => {
2192
+ const normalized = normalizeFileName$1(fileName);
2193
+ return Option.some([normalized, {
2194
+ fileName: normalized,
2195
+ imports: HashSet.empty()
2196
+ }]);
2197
+ }
2198
+ });
2199
+ const registerOwners = (owners, program, fileNames) => Arr.reduce(fileNames, owners, (accumulated, fileName) => {
2200
+ const normalized = normalizeFileName$1(fileName);
2201
+ return Boolean.match(HashMap.has(accumulated, normalized), {
2202
+ onTrue: () => accumulated,
2203
+ onFalse: () => HashMap.set(accumulated, normalized, program)
2204
+ });
2205
+ });
2206
+ const sourceFileIn$1 = (program, fileName) => Effect.map(Effect.promise(() => program.getSourceFile(fileName)), (found) => Option.fromUndefinedOr(found));
2207
+ const sourceFileOf = (programs, fileName) => Option.match(Arr.head(programs), {
2208
+ onNone: () => Effect.succeed(Option.none()),
2209
+ onSome: (program) => Effect.filterOrElse(sourceFileIn$1(program, fileName), Option.isSome, () => sourceFileOf(Arr.drop(programs, 1), fileName))
2210
+ });
2211
+ const linkImport = (rt, aliases, sourceFiles, fileName, specifier) => Option.match(Option.filter(resolveSpecifier(rt.pathService, aliases, sourceFiles, fileName, specifier), (resolved) => resolved !== ""), {
2212
+ onNone: () => sourceFiles,
2213
+ onSome: (resolved) => {
2214
+ const imported = resolveTSInputFile(rt, resolved);
2215
+ return Boolean.match(HashMap.has(sourceFiles, imported), {
2216
+ onFalse: () => sourceFiles,
2217
+ onTrue: () => Option.match(HashMap.get(sourceFiles, fileName), {
2218
+ onNone: () => sourceFiles,
2219
+ onSome: (entry) => HashMap.set(sourceFiles, fileName, {
2220
+ ...entry,
2221
+ imports: HashSet.add(entry.imports, imported)
2222
+ })
2223
+ })
2224
+ });
2225
+ }
2226
+ });
2227
+ const ownedSourceFileOf = (owners, programs, fileName) => Option.match(HashMap.get(owners, fileName), {
2228
+ onNone: () => sourceFileOf(programs, fileName),
2229
+ onSome: (owner) => Effect.filterOrElse(sourceFileIn$1(owner, fileName), Option.isSome, () => sourceFileOf(programs, fileName))
2230
+ });
2231
+ const buildGraph = Effect.fnUntraced(function* (rt, programs) {
2232
+ const state = yield* SynchronizedRef.get(rt.state);
2233
+ const owners = yield* Effect.reduce(programs, () => HashMap.empty(), (accumulated, program) => Effect.map(Effect.promise(() => program.getSourceFileNames()), (fileNames) => registerOwners(accumulated, program, fileNames)));
2234
+ const registered = owners.pipe(Arr.fromIterable, Arr.filterMap(([fileName]) => keepSome(registeredEntry(fileName))), HashMap.fromIterable);
2235
+ const linked = yield* Effect.reduce(Arr.fromIterable(registered), () => registered, (sourceFiles, [fileName]) => Effect.map(ownedSourceFileOf(owners, programs, fileName), (found) => Option.match(found, {
2236
+ onNone: () => sourceFiles,
2237
+ onSome: (sourceFile) => Arr.reduce(importsOf(sourceFile), sourceFiles, (accumulated, specifier) => linkImport(rt, state.aliases, accumulated, fileName, specifier))
2238
+ })));
2239
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
2240
+ ...prev,
2241
+ sourceFiles: linked
2242
+ }));
2243
+ });
2244
+ const fileNode = (fileName, children, parents = []) => ({
2245
+ children,
2246
+ fileName,
2247
+ parents
2248
+ });
2249
+ 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])));
2250
+ const graphNodesOf = (sourceFiles) => {
2251
+ const entries = Arr.fromIterable(sourceFiles);
2252
+ const importers = importersOf(sourceFiles);
2253
+ const leaves = HashMap.fromIterable(Arr.map(entries, ([fileName]) => [fileName, fileNode(fileName, [])]));
2254
+ 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))))]));
2255
+ };
2256
+ const nodesOf = (rt) => Effect.flatMap(SynchronizedRef.get(rt.state), (state) => Boolean.match(HashMap.isEmpty(state.nodes), {
2257
+ onFalse: () => Effect.succeed(state.nodes),
2258
+ onTrue: () => {
2259
+ const nodes = graphNodesOf(state.sourceFiles);
2260
+ return Effect.as(SynchronizedRef.update(rt.state, (prev) => ({
2261
+ ...prev,
2262
+ nodes
2263
+ })), nodes);
2264
+ }
2265
+ }));
2266
+ const init = Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerInit.name)(function* (self) {
2267
+ const rt = runtimeOf(self);
2268
+ yield* guardTypescriptVersion(rt);
2269
+ const tsconfigFile = normalizeFileName$1(rt.pathService.resolve(rt.options.tsconfigFile));
2270
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
2271
+ ...prev,
2272
+ tsconfigFile,
2273
+ allTSConfigFiles: HashSet.fromIterable([tsconfigFile])
2274
+ }));
2275
+ const tsconfigText = yield* Effect.mapError(rt.host.readFileString(tsconfigFile), () => TsConfigNotFoundError.make({ file: tsconfigFile }));
2276
+ const buildMode = tsconfigDeclaresReferences(tsconfigFile, tsconfigText);
2277
+ const walk = yield* walkTsConfigs(rt, buildMode, {
2278
+ files: HashSet.fromIterable([tsconfigFile]),
2279
+ overrides: HashMap.empty(),
2280
+ processed: HashSet.empty(),
2281
+ aliases: [],
2282
+ references: {}
2283
+ }, [tsconfigFile], HashMap.fromIterable([[tsconfigFile, tsconfigText]]));
2284
+ yield* setOverrides(rt.files, walk.overrides);
2285
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
2286
+ ...prev,
2287
+ allTSConfigFiles: walk.files,
2288
+ aliases: walk.aliases,
2289
+ references: walk.references
2290
+ }));
2291
+ const api = new API({ fs: rt.sourceFileSystem });
2292
+ const snapshot = yield* Effect.promise(() => api.updateSnapshot({ openProjects: Array.from(walk.files) }));
2293
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
2294
+ ...prev,
2295
+ api,
2296
+ snapshot
2297
+ }));
2298
+ const programs = yield* programsOf(rt);
2299
+ yield* buildGraph(rt, programs);
2300
+ return yield* dryRunDiagnostics(programs);
2301
+ });
2302
+ const semanticDiagnosticsOf = Effect.fnUntraced(function* (program, affectedFileNames) {
2303
+ const presentFileNames = yield* Effect.promise(() => program.getSourceFileNames());
2304
+ const request = RequestAffectedFilesCommand.make({
2305
+ affectedFileNames: Arr.fromIterable(affectedFileNames),
2306
+ presentFileNames: [...presentFileNames]
2307
+ });
2308
+ const requested = decided(requestAffectedFiles(request));
2309
+ const batchPlan = PlanDiagnosticBatchesCommand.make({ fileNames: Match.value(requested).pipe(Match.tag("AffectedFilesRequested", ({ fileNames }) => fileNames), Match.tag("NoAffectedFileRequested", () => []), Match.exhaustive) });
2310
+ const batches = decided(planDiagnosticBatches(batchPlan));
2311
+ const plannedBatches = Match.value(batches).pipe(Match.tag("DiagnosticBatchesPlanned", ({ batches }) => batches), Match.tag("NoDiagnosticBatches", () => []), Match.exhaustive);
2312
+ 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();
2313
+ });
2314
+ const programWideDiagnosticsOf = (program) => Effect.map(Effect.promise(() => Promise.all([program.getConfigFileParsingDiagnostics(), program.getProgramDiagnostics()])), ([config, programWide]) => [...config, ...programWide]);
2315
+ const wholeProgramDiagnosticsOf = (program) => Effect.all([programWideDiagnosticsOf(program), Effect.promise(() => program.getSemanticDiagnostics())], { concurrency: 2 }).pipe(Effect.map(([programWide, semantic]) => [...semantic, ...programWide]));
2316
+ const dryRunDiagnostics = Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerDryRun.name)(function* (programs) {
2317
+ yield* Effect.annotateCurrentSpan({ "typescript.projects.count": programs.length });
2318
+ return errorDiagnosticsOf(Arr.flatten(yield* Effect.forEach(programs, (program) => wholeProgramDiagnosticsOf(program))));
2319
+ });
2320
+ const errorDiagnosticsOf = (diagnostics) => Arr.filter(diagnostics, (diagnostic) => diagnostic.category === DiagnosticCategory.Error);
2321
+ const firstHolderOf = (projects, fileName) => Option.match(Arr.head(projects), {
2322
+ onNone: () => Effect.succeedNone,
2323
+ onSome: (project) => Effect.flatMap(Effect.promise(() => project.program.getSourceFile(fileName)), (sourceFile) => Option.match(Option.fromUndefinedOr(sourceFile), {
2324
+ onNone: () => firstHolderOf(Arr.drop(projects, 1), fileName),
2325
+ onSome: (found) => Effect.succeedSome({
2326
+ project,
2327
+ sourceFile: found
2328
+ })
2329
+ }))
2330
+ });
2331
+ const listsAsRootFile = (fileName) => (project) => Arr.some(project.rootFiles, (rootFile) => normalizeFileName$1(rootFile) === fileName);
2332
+ const projectOfFile = (projects, fileName) => firstHolderOf([...Arr.filter(projects, listsAsRootFile(fileName)), ...Arr.filter(projects, (project) => Boolean.not(listsAsRootFile(fileName)(project)))], fileName);
2333
+ const importerErrorsOf = (projects, fileNames) => Effect.map(Effect.forEach(projects, (project) => semanticDiagnosticsOf(project.program, fileNames), { concurrency: 1 }), (perProject) => errorDiagnosticsOf(Arr.flatten(perProject)));
2334
+ const wholeProgramErrorsOf = (projects) => Effect.map(Effect.forEach(projects, (project) => wholeProgramDiagnosticsOf(project.program), { concurrency: 1 }), (perProject) => errorDiagnosticsOf(Arr.flatten(perProject)));
2335
+ const ownErrorsOf = (owned, fileName) => Effect.map(Effect.promise(() => owned.project.program.getSemanticDiagnostics(fileName)), errorDiagnosticsOf);
2336
+ const affectedFileNamesOf = (state, mutatedFileNames) => {
2337
+ const command = TraceAffectedFilesCommand.make({
2338
+ importsByFile: Object.fromEntries(Arr.map(Arr.fromIterable(state.sourceFiles), ([fileName, entry]) => [fileName, Arr.fromIterable(entry.imports)])),
2339
+ mutatedFileNames: [...mutatedFileNames]
2340
+ });
2341
+ const affected = decided(traceAffectedFiles(command));
2342
+ return HashSet.fromIterable(Arr.map(affected, (affectedFile) => affectedFile.fileName));
2343
+ };
2344
+ const declaresGlobalScope = (sourceFile) => Boolean.or(sourceFile.externalModuleIndicator === void 0, fileFactsOf(sourceFile).declaresGlobal);
2345
+ const beyondOwnErrorsOf = (state, projects, owned, fileName) => Boolean.match(declaresGlobalScope(owned.sourceFile), {
2346
+ onTrue: () => wholeProgramErrorsOf(projects),
2347
+ onFalse: () => importerErrorsOf(projects, affectedFileNamesOf(state, [fileName]))
2348
+ });
2349
+ const checkedIn = (state, projects, owned, fileName) => Effect.flatMap(ownErrorsOf(owned, fileName), (own) => Boolean.match(own.length > 0, {
2350
+ onTrue: () => Effect.succeed(own),
2351
+ onFalse: () => beyondOwnErrorsOf(state, projects, owned, fileName)
2352
+ }));
2353
+ const errorsOfOwned = (rt, fileName, errorsOf) => Effect.flatMap(projectsOf(rt), (projects) => Effect.flatMap(projectOfFile(projects, fileName), (owned) => Option.match(owned, {
2354
+ onNone: () => Effect.succeed([]),
2355
+ onSome: (found) => errorsOf(projects, found)
2356
+ })));
2357
+ const configKeyOf = (project) => normalizeFileName$1(project.configFileName);
2358
+ const holdersOf = (projects, fileName) => Effect.map(Effect.forEach(projects, (project) => Effect.map(Effect.promise(() => project.program.getSourceFile(fileName)), (sourceFile) => ({
2359
+ project,
2360
+ held: sourceFile !== void 0
2361
+ })), { concurrency: 1 }), (checked) => Arr.map(Arr.filter(checked, (entry) => entry.held), (entry) => entry.project));
2362
+ const compiledElsewhereIn = (rt, fileName) => Effect.flatMap(SynchronizedRef.get(rt.state), (state) => Effect.flatMap(projectsOf(rt), (projects) => Effect.flatMap(projectOfFile(projects, fileName), (owned) => Option.match(owned, {
2363
+ onNone: () => Effect.succeed(false),
2364
+ onSome: (found) => Effect.map(holdersOf(projects, fileName), (holders) => Arr.isReadonlyArrayNonEmpty(otherCompilersOf({
2365
+ references: state.references,
2366
+ owner: configKeyOf(found.project),
2367
+ holders: Arr.map(holders, configKeyOf)
2368
+ })))
2369
+ }))));
2370
+ const checkStepsOf = (rt) => ({
2371
+ resolveFileName: (fileName) => resolveFileName(rt, fileName),
2372
+ fileOf: (fileName) => getFile(rt.files, fileName),
2373
+ editTreeOf: (fileName) => editTreeOf(rt, fileName),
2374
+ parseHeldAfterSplice: (file, mutant, fileName) => parseHeldAfterSpliceOf(rt, file, mutant, fileName),
2375
+ parenthesizedSplice: (mutant, fileName, changedFiles) => parenthesizedSpliceOf(rt, mutant, fileName, changedFiles),
2376
+ applyMutant: (mutant, replacement) => applyMutant(rt, mutant, replacement),
2377
+ resetMutatedFiles: (mutants) => Effect.asVoid(resetMutatedFiles(rt, [...mutants])),
2378
+ refreshSnapshot: (changedFiles) => refreshSnapshot(rt, changedFiles),
2379
+ ownErrorsIn: (fileName) => errorsOfOwned(rt, fileName, (_, owned) => ownErrorsOf(owned, fileName)),
2380
+ allErrorsIn: (state, fileName) => errorsOfOwned(rt, fileName, (projects, owned) => checkedIn(state, projects, owned, fileName)),
2381
+ compiledElsewhereIn: (fileName) => compiledElsewhereIn(rt, fileName)
2382
+ });
2383
+ const siteKeyOf = (mutant) => `${mutant.fileName}:${mutant.location.start.line}:${mutant.location.start.column}:${mutant.location.end.line}:${mutant.location.end.column}`;
2384
+ const splicedContentOf = (file, mutant) => Option.map(Option.all([offsetAt(file.lineStarts, mutant.location.start), offsetAt(file.lineStarts, mutant.location.end)]), ([start, end]) => file.originalContent.slice(0, start) + mutant.replacement + file.originalContent.slice(end));
2385
+ const tceEntriesOf = (script, fileMutants) => Arr.getSomes(Arr.map(fileMutants, (mutant) => Option.map(splicedContentOf(script, mutant), (content) => ({
2386
+ key: mutant.id,
2387
+ content,
2388
+ site: siteKeyOf(mutant)
2389
+ }))));
2390
+ const tceCandidatesOf = (entries, byKey) => Arr.getSomes(Arr.map(entries, (entry) => Option.map(HashMap.get(byKey, entry.key), (emit) => ({
2391
+ id: entry.key,
2392
+ site: entry.site,
2393
+ emit
2394
+ }))));
2395
+ const emitForFile = (rt, tsconfigFile, fileName, script, entries) => emitNormalized({
2396
+ tsconfigFile,
2397
+ sourceExtension: rt.pathService.extname(fileName),
2398
+ originalContent: script.originalContent,
2399
+ mutants: Arr.map(entries, (entry) => ({
2400
+ key: entry.key,
2401
+ content: entry.content
2402
+ }))
2403
+ }).pipe(Effect.provideService(FileSystem.FileSystem, rt.host), Effect.provideService(Path.Path, rt.pathService), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, rt.spawner), Effect.timed, Effect.flatMap(([elapsed, emitted]) => Effect.as(Ref.update(rt.tally, (tally) => ({
2404
+ ...tally,
2405
+ tceBuilds: tally.tceBuilds + 1,
2406
+ tceMs: tally.tceMs + Duration.toMillis(elapsed)
2407
+ })), emitted)));
2408
+ const tceScriptOf = (file, fileName) => Option.match(file, {
2409
+ onNone: () => Result.fail(CompilerFailed.make({
2410
+ reason: "file-not-in-project",
2411
+ subject: fileName
2412
+ })),
2413
+ onSome: (script) => Result.succeed(script)
2414
+ });
2415
+ const decisionsOfFile = Effect.fnUntraced(function* (rt, tsconfigFile, fileName, fileMutants) {
2416
+ const file = yield* getFile(rt.files, fileName);
2417
+ const script = yield* Effect.fromResult(tceScriptOf(file, fileName));
2418
+ const entries = tceEntriesOf(script, fileMutants);
2419
+ const emitted = yield* Option.match(Option.liftPredicate(entries, (present) => present.length > 0), {
2420
+ onNone: () => Effect.succeedNone,
2421
+ onSome: (present) => emitForFile(rt, tsconfigFile, fileName, script, present)
2422
+ });
2423
+ return Option.match(emitted, {
2424
+ onNone: () => [],
2425
+ onSome: (result) => decided(classifyTce(ClassifyTceCommand.make({
2426
+ originalEmit: result.original,
2427
+ candidates: tceCandidatesOf(entries, result.byKey)
2428
+ })))
2429
+ });
2430
+ });
2431
+ const classifyBatchTce = Effect.fnUntraced(function* (rt, tsconfigFile, mutants, checked) {
2432
+ const passedIds = HashSet.fromIterable(Arr.map(Arr.filter(checked, (entry) => entry.diagnostics.length === 0), (entry) => entry.mutantId));
2433
+ const passedMutants = Arr.filter(mutants, (mutant) => HashSet.has(passedIds, mutant.id));
2434
+ const fileNames = Arr.dedupe(Arr.map(passedMutants, (mutant) => resolveFileName(rt, mutant.fileName)));
2435
+ const perFile = yield* Effect.forEach(fileNames, (fileName) => decisionsOfFile(rt, tsconfigFile, fileName, Arr.filter(passedMutants, (mutant) => resolveFileName(rt, mutant.fileName) === fileName)));
2436
+ const decisions = Arr.flatten(perFile);
2437
+ return Arr.map(checked, (entry) => Option.match(Arr.findFirst(decisions, (decision) => decision.id === entry.mutantId), {
2438
+ onNone: () => entry,
2439
+ onSome: (decision) => ({
2440
+ ...entry,
2441
+ tce: decision.classification
2442
+ })
2443
+ }));
2444
+ });
2445
+ const nodes = Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerNodes.name)(function* (self) {
2446
+ return yield* self.pipe(runtimeOf, nodesOf);
2447
+ });
2448
+ const groupedMutants = (mutants) => Arr.map(decided(groupMutants(GroupMutantsCommand.make({
2449
+ mutants: [...mutants],
2450
+ bound: 256
2451
+ }))), (group) => group.ids);
2452
+ const groups = (mutants) => Effect.sync(() => groupedMutants(mutants)).pipe(Effect.withSpan(SpanTaxonomy.Spans.typescriptCheckerCompilerGroups.name));
2453
+ const getLineAndCharacterOfPosition = dual(3, Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerLineAndCharacter.name)(function* (self, fileName, position) {
2454
+ const rt = runtimeOf(self);
2455
+ const programs = yield* programsOf(rt).pipe(Effect.orElseSucceed(() => []));
2456
+ const found = yield* sourceFileOf(programs, fileName);
2457
+ return Option.getOrUndefined(Option.map(found, (sourceFile) => sourceFile.getLineAndCharacterOfPosition(position)));
2458
+ }));
2459
+ 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"));
2460
+ const renderPosition = (fileName, at) => Option.match(Option.fromUndefinedOr(at), {
2461
+ onNone: () => fileName + "(1,1): ",
2462
+ onSome: (position) => fileName + "(" + (position.line + 1) + "," + (position.character + 1) + "): "
2463
+ });
2464
+ const positionOf = (self, diagnostic) => Option.match(Option.filter(Option.fromUndefinedOr(diagnostic.fileName), (fileName) => fileName !== ""), {
2465
+ onNone: () => Effect.succeed(""),
2466
+ onSome: (fileName) => getLineAndCharacterOfPosition(self, fileName, diagnostic.pos).pipe(Effect.orElseSucceed(() => void 0), Effect.map((at) => renderPosition(fileName, at)))
2467
+ });
2468
+ const describedOf = (self, diagnostic) => Effect.map(positionOf(self, diagnostic), (position) => DiagnosticLine.make({
2469
+ position,
2470
+ severity: severityOf(diagnostic.category),
2471
+ code: diagnostic.code,
2472
+ text: diagnostic.text,
2473
+ ...diagnostic.fileName === void 0 ? {} : { fileName: diagnostic.fileName }
2474
+ }));
2475
+ const describeDiagnostics = dual(2, (self, diagnostics) => Effect.forEach(diagnostics, (diagnostic) => describedOf(self, diagnostic)));
2476
+ const CLOSE_GRACE$1 = "1 second";
2477
+ const close = Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerClose.name)(function* (self) {
2478
+ const rt = runtimeOf(self);
2479
+ const state = yield* SynchronizedRef.getAndUpdate(rt.state, (prev) => ({
2480
+ ...prev,
2481
+ snapshot: void 0,
2482
+ api: void 0
2483
+ }));
2484
+ const released = yield* Option.match(Option.fromUndefinedOr(state.api), {
2485
+ onNone: () => Effect.succeed(true),
2486
+ onSome: (api) => Effect.tryPromise(() => api.close()).pipe(Effect.timeoutOption(CLOSE_GRACE$1), Effect.tapError((error) => Effect.annotateCurrentSpan("typescript.server.close_error", error.message)), Effect.match({
2487
+ onFailure: () => false,
2488
+ onSuccess: Option.isSome
2489
+ }))
2490
+ });
2491
+ yield* Effect.annotateCurrentSpan("typescript.server.released", released);
2492
+ });
2493
+ const readCheckerBlock = S.decodeUnknownEffect(UndecodedCheckerBlock);
2494
+ const decodeCheckerBlock = S.decodeUnknownEffect(S.UndefinedOr(TypescriptCheckerBlock), { onExcessProperty: "error" });
2495
+ const importerCheckOfOptions = (options) => readCheckerBlock(options).pipe(Effect.flatMap(({ typescriptChecker }) => decodeCheckerBlock(typescriptChecker)), Effect.mapBoth({
2496
+ onFailure: (issue) => InvalidCheckerOptions.make({ detail: issue.message }),
2497
+ onSuccess: (typescriptChecker) => importerCheckOf(typescriptChecker === void 0 ? {} : { typescriptChecker })
2498
+ }));
2499
+ const admitted = (original, mutated) => decided(admitImporterShortcut(DecideImporterShortcutCommand.make({
2500
+ original: original.facts,
2501
+ mutated,
2502
+ compiledElsewhere: original.compiledElsewhere
2503
+ })));
2504
+ const eligibleOn = (original) => takesShortcut(admitted(original, original.facts));
2505
+ const fileNamesOf = (steps, mutants) => Arr.dedupe(Arr.map(mutants, (mutant) => steps.resolveFileName(mutant.fileName)));
2506
+ const spanOf = (script, mutant) => Option.map(Option.all([offsetAt(script.lineStarts, mutant.location.start), offsetAt(script.lineStarts, mutant.location.end)]), ([start, end]) => ({
2507
+ start,
2508
+ end
2509
+ }));
2510
+ const fileOriginalsOf = (steps, fileName, fileMutants) => Effect.gen(function* () {
2511
+ const file = yield* steps.fileOf(fileName);
2512
+ const tree = yield* steps.editTreeOf(fileName);
2513
+ const compiledElsewhere = yield* steps.compiledElsewhereIn(fileName);
2514
+ return Option.match(Option.all([file, tree]), {
2515
+ onNone: () => [],
2516
+ onSome: ([script, edited]) => Arr.getSomes(Arr.map(fileMutants, (mutant) => Option.map(spanOf(script, mutant), (span) => [mutant.id, {
2517
+ facts: editSiteFactsOf(edited.sourceFile, span, edited.syntaxErrors),
2518
+ compiledElsewhere
2519
+ }])))
2520
+ });
2521
+ });
2522
+ const locationRuleOriginalsOf = (steps, mutants) => Effect.map(Effect.forEach(fileNamesOf(steps, mutants), (fileName) => fileOriginalsOf(steps, fileName, Arr.filter(mutants, (mutant) => steps.resolveFileName(mutant.fileName) === fileName))), (perFile) => HashMap.fromIterable(Arr.flatten(perFile)));
2523
+ const originalsOf = (steps, mode, mutants) => Boolean.match(readsEditSites(mode), {
2524
+ onFalse: () => Effect.succeed(HashMap.empty()),
2525
+ onTrue: () => locationRuleOriginalsOf(steps, mutants)
2526
+ });
2527
+ const appliedOf = (mutant, held) => Boolean.match(held, {
2528
+ onTrue: () => mutant.replacement,
2529
+ onFalse: () => `(${mutant.replacement})`
2530
+ });
2531
+ const mutatedFactsOf = (steps, fileName, original, applied) => Effect.map(steps.editTreeOf(fileName), Option.map((edited) => editSiteFactsOf(edited.sourceFile, {
2532
+ start: original.facts.span.start,
2533
+ end: original.facts.span.start + applied.length
2534
+ }, edited.syntaxErrors)));
2535
+ const decisionAfterApplyOf = (ctx, mutant, fileName, applied) => Option.match(HashMap.get(ctx.originals, mutant.id), {
2536
+ onNone: () => Effect.succeedNone,
2537
+ onSome: (original) => Boolean.match(eligibleOn(original), {
2538
+ onFalse: () => Effect.succeedSome(admitted(original, original.facts)),
2539
+ onTrue: () => Effect.map(mutatedFactsOf(ctx.steps, fileName, original, applied), Option.map((mutated) => admitted(original, mutated)))
2540
+ })
2541
+ });
2542
+ const renderedOf = (ctx, mutant, diagnostics, decision) => Effect.map(describeDiagnostics(ctx.self, diagnostics), (rendered) => ({
2543
+ check: {
2544
+ mutantId: mutant.id,
2545
+ diagnostics: rendered
2546
+ },
2547
+ decision
2548
+ }));
2549
+ const decidedOutcomeOf = (ctx, mutant, fileName, decision) => Effect.flatMap(Boolean.match(Option.exists(decision, takesShortcut), {
2550
+ onTrue: () => ctx.steps.ownErrorsIn(fileName),
2551
+ onFalse: () => ctx.steps.allErrorsIn(ctx.state, fileName)
2552
+ }), (diagnostics) => renderedOf(ctx, mutant, diagnostics, decision));
2553
+ const soloOutcomeOf = (ctx, mutant, previous) => Effect.gen(function* () {
2554
+ yield* ctx.steps.resetMutatedFiles(previous);
2555
+ const fileName = ctx.steps.resolveFileName(mutant.fileName);
2556
+ const changedFiles = Arr.dedupe([...fileNamesOf(ctx.steps, previous), fileName]);
2557
+ const file = yield* ctx.steps.fileOf(fileName);
2558
+ yield* ctx.steps.applyMutant(mutant, mutant.replacement);
2559
+ yield* ctx.steps.refreshSnapshot(changedFiles);
2560
+ const held = yield* ctx.steps.parseHeldAfterSplice(file, mutant, fileName);
2561
+ yield* Boolean.match(held, {
2562
+ onTrue: () => Effect.void,
2563
+ onFalse: () => ctx.steps.parenthesizedSplice(mutant, fileName, changedFiles)
2564
+ });
2565
+ const decision = yield* decisionAfterApplyOf(ctx, mutant, fileName, appliedOf(mutant, held));
2566
+ return yield* decidedOutcomeOf(ctx, mutant, fileName, decision);
2567
+ });
2568
+ const respliceAll = (ctx, unheld, changedFiles) => Boolean.match(unheld.length === 0, {
2569
+ onTrue: () => Effect.void,
2570
+ onFalse: () => Effect.andThen(Effect.forEach(unheld, (mutant) => ctx.steps.applyMutant(mutant, `(${mutant.replacement})`), { discard: true }), Effect.andThen(Ref.update(ctx.rt.tally, (tally) => ({
2571
+ ...tally,
2572
+ resplices: tally.resplices + unheld.length
2573
+ })), ctx.steps.refreshSnapshot(changedFiles)))
2574
+ });
2575
+ const memberOf = (steps, mutant) => {
2576
+ const fileName = steps.resolveFileName(mutant.fileName);
2577
+ return Effect.map(steps.fileOf(fileName), (file) => ({
2578
+ mutant,
2579
+ fileName,
2580
+ file
2581
+ }));
2582
+ };
2583
+ const decidedOutcomesOf = (ctx, members) => Effect.forEach(members, (member) => decidedOutcomeOf(ctx, member.mutant, member.fileName, member.decision));
2584
+ const sharedOutcomesOf = (ctx, mutants, previous) => Effect.gen(function* () {
2585
+ yield* ctx.steps.resetMutatedFiles(previous);
2586
+ const members = yield* Effect.forEach(mutants, (mutant) => memberOf(ctx.steps, mutant));
2587
+ const changedFiles = Arr.dedupe([...fileNamesOf(ctx.steps, previous), ...fileNamesOf(ctx.steps, mutants)]);
2588
+ yield* Effect.forEach(mutants, (mutant) => ctx.steps.applyMutant(mutant, mutant.replacement), { discard: true });
2589
+ yield* ctx.steps.refreshSnapshot(changedFiles);
2590
+ const applied = yield* Effect.forEach(members, (member) => Effect.map(ctx.steps.parseHeldAfterSplice(member.file, member.mutant, member.fileName), (held) => ({
2591
+ ...member,
2592
+ held
2593
+ })));
2594
+ yield* respliceAll(ctx, Arr.map(Arr.filter(applied, (member) => Boolean.not(member.held)), (member) => member.mutant), changedFiles);
2595
+ const decidedMembers = yield* Effect.forEach(applied, (member) => Effect.map(decisionAfterApplyOf(ctx, member.mutant, member.fileName, appliedOf(member.mutant, member.held)), (decision) => ({
2596
+ ...member,
2597
+ decision
2598
+ })));
2599
+ return yield* Match.valueTags(decided(concludeSharedRound(ConcludeSharedRoundCommand.make({ decisions: Arr.map(decidedMembers, (member) => member.decision) }))), {
2600
+ SharedRoundRedone: () => Effect.succeedNone,
2601
+ SharedRoundKept: () => Effect.asSome(decidedOutcomesOf(ctx, decidedMembers))
2602
+ });
2603
+ });
2604
+ const soloChainOf = (ctx, mutants, start) => Effect.reduce(mutants, () => start, (progress, mutant) => Effect.map(soloOutcomeOf(ctx, mutant, progress.previous), (outcome) => ({
2605
+ previous: [mutant],
2606
+ outcomes: [...progress.outcomes, outcome]
2607
+ })));
2608
+ const sharedProgressOf = (ctx, mutants, progress) => Effect.flatMap(sharedOutcomesOf(ctx, mutants, progress.previous), (outcomes) => Option.match(outcomes, {
2609
+ onNone: () => soloChainOf(ctx, mutants, {
2610
+ previous: mutants,
2611
+ outcomes: progress.outcomes
2612
+ }),
2613
+ onSome: (shared) => Effect.succeed({
2614
+ previous: mutants,
2615
+ outcomes: [...progress.outcomes, ...shared]
2616
+ })
2617
+ }));
2618
+ const mutantsOf = (byId, ids) => Arr.getSomes(Arr.map(ids, (id) => HashMap.get(byId, id)));
2619
+ const roundProgressOf = (ctx, byId, progress, round) => Match.valueTags(round, {
2620
+ SoloRound: (solo) => soloChainOf(ctx, mutantsOf(byId, [solo.id]), progress),
2621
+ SharedRound: (shared) => sharedProgressOf(ctx, mutantsOf(byId, shared.ids), progress)
2622
+ });
2623
+ const decodePlanCheckRoundsCommand = S.decodeEffect(PlanCheckRoundsCommand);
2624
+ const roundsOf = (ctx, mutants) => Effect.mapBoth(decodePlanCheckRoundsCommand({
2625
+ _tag: "PlanCheckRoundsCommand",
2626
+ candidates: Arr.map(mutants, (mutant) => ({
2627
+ id: mutant.id,
2628
+ fileName: ctx.steps.resolveFileName(mutant.fileName),
2629
+ eligible: Option.exists(HashMap.get(ctx.originals, mutant.id), eligibleOn)
2630
+ }))
2631
+ }), {
2632
+ onFailure: (issue) => DuplicateMutantIds.make({ detail: issue.message }),
2633
+ onSuccess: (command) => decided(planCheckRounds(command))
2634
+ });
2635
+ const inInputOrder = (mutants, outcomes) => {
2636
+ const byId = HashMap.fromIterable(Arr.map(outcomes, (outcome) => [outcome.check.mutantId, outcome]));
2637
+ return Arr.getSomes(Arr.map(mutants, (mutant) => HashMap.get(byId, mutant.id)));
2638
+ };
2639
+ const check = dual(2, Effect.fn(SpanTaxonomy.Spans.typescriptCheckerCompilerCheck.name)(function* (self, mutants) {
2640
+ const rt = runtimeOf(self);
2641
+ const steps = checkStepsOf(rt);
2642
+ yield* Effect.annotateCurrentSpan({
2643
+ "stryker.mutants.count": mutants.length,
2644
+ "stryker.mutants.ids": Arr.map(mutants, (mutant) => mutant.id).join(",")
2645
+ });
2646
+ yield* Ref.set(rt.tally, emptyTally);
2647
+ const state = yield* SynchronizedRef.get(rt.state);
2648
+ const mode = yield* importerCheckOfOptions(rt.options);
2649
+ yield* steps.resetMutatedFiles(state.lastMutants);
2650
+ yield* steps.refreshSnapshot(Arr.dedupe([...state.lastMutatedFileNames, ...fileNamesOf(steps, mutants)]));
2651
+ const ctx = {
2652
+ self,
2653
+ rt,
2654
+ steps,
2655
+ state,
2656
+ originals: yield* originalsOf(steps, mode, mutants)
2657
+ };
2658
+ const byId = HashMap.fromIterable(Arr.map(mutants, (mutant) => [mutant.id, mutant]));
2659
+ const rounds = yield* roundsOf(ctx, mutants);
2660
+ const progress = yield* Effect.reduce(rounds, () => ({
2661
+ previous: [],
2662
+ outcomes: []
2663
+ }), (current, round) => roundProgressOf(ctx, byId, current, round));
2664
+ const outcomes = inInputOrder(mutants, progress.outcomes);
2665
+ const checked = yield* classifyBatchTce(rt, state.tsconfigFile, mutants, Arr.map(outcomes, (outcome) => outcome.check));
2666
+ yield* SynchronizedRef.update(rt.state, (prev) => ({
2667
+ ...prev,
2668
+ lastMutants: [...progress.previous],
2669
+ lastMutatedFileNames: fileNamesOf(steps, progress.previous)
2670
+ }));
2671
+ const failed = Arr.filter(checked, (entry) => entry.diagnostics.length > 0);
2672
+ const equivalentToOriginal = Arr.filter(checked, (entry) => entry.tce === "original").length;
2673
+ const duplicateAtSite = Arr.filter(checked, (entry) => entry.tce === "sibling").length;
2674
+ const tally = yield* Ref.get(rt.tally);
2675
+ yield* Effect.annotateCurrentSpan({
2676
+ "typescript.diagnostics.count": Arr.reduce(checked, 0, (total, entry) => total + entry.diagnostics.length),
2677
+ "typescript.compile_errors.count": failed.length,
2678
+ "typescript.tce.equivalent_to_original.count": equivalentToOriginal,
2679
+ "typescript.tce.duplicate_at_site.count": duplicateAtSite,
2680
+ "typescript.counts.schema_version": 1,
2681
+ "typescript.snapshot_updates.count": tally.snapshotUpdates,
2682
+ "typescript.resplices.count": tally.resplices,
2683
+ "typescript.tce_builds.count": tally.tceBuilds,
2684
+ "typescript.tce.ms": tally.tceMs,
2685
+ ...shortcutCountsOf({
2686
+ importerCheck: mode,
2687
+ decisions: Arr.map(outcomes, (outcome) => outcome.decision)
2688
+ })
2689
+ });
2690
+ yield* annotateDiagnosticSample(Arr.flatten(Arr.map(failed, (entry) => entry.diagnostics)));
2691
+ return checked;
2692
+ }));
2693
+ //#endregion
2694
+ //#region src/answer-type-query.workflow.ts
2695
+ const AnswerTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/AnswerDecision");
2696
+ var AnswerAssignable = class extends S.TaggedClass()("AnswerAssignable", { candidateType: S.String }) {
2697
+ [AnswerTypeId] = AnswerTypeId;
2698
+ };
2699
+ var AnswerNotAssignable = class extends S.TaggedClass()("AnswerNotAssignable", {
2700
+ candidateType: S.String,
2701
+ contextualType: S.String
2702
+ }) {
2703
+ [AnswerTypeId] = AnswerTypeId;
2704
+ };
2705
+ var AnswerUnknown = class extends S.TaggedClass()("AnswerUnknown", { reason: TypeQuery.UnknownReason }) {
2706
+ [AnswerTypeId] = AnswerTypeId;
2707
+ };
2708
+ const AnswerDecision = S.Union([
2709
+ AnswerAssignable,
2710
+ AnswerNotAssignable,
2711
+ AnswerUnknown
2712
+ ]);
2713
+ const unknownAnswer = (reason) => AnswerUnknown.make({ reason });
2714
+ const assignableAnswer = (candidateType) => AnswerAssignable.make({ candidateType });
2715
+ const notAssignableAnswer = (candidateType, contextualType) => AnswerNotAssignable.make({
2716
+ candidateType,
2717
+ contextualType
2718
+ });
2719
+ const typedAnswerOf = (candidate, contextualType) => Boolean.match(candidate.assignable, {
2720
+ onTrue: () => assignableAnswer(candidate.candidateType),
2721
+ onFalse: () => notAssignableAnswer(candidate.candidateType, contextualType.text)
2722
+ });
2723
+ const originAnswerOf = (candidate, origin, contextualType) => Match.value(origin).pipe(Match.tag("DeclaredContext", () => typedAnswerOf(candidate, contextualType)), Match.tag("CallArgument", (argument) => Boolean.match(Boolean.or(argument.signatureCount > 1, argument.declaredGeneric), {
2724
+ onTrue: () => unknownAnswer("overloaded-or-generic-call"),
2725
+ onFalse: () => typedAnswerOf(candidate, contextualType)
2726
+ })), Match.tag("UnenforcedContext", () => unknownAnswer("context-not-enforced")), Match.exhaustive);
2727
+ const contextualAnswerOf = (candidate, origin, contextualType) => Boolean.match(contextualType.isError, {
2728
+ onTrue: () => unknownAnswer("error-type"),
2729
+ onFalse: () => Boolean.match(contextualType.instantiable, {
2730
+ onTrue: () => unknownAnswer("instantiable-target"),
2731
+ onFalse: () => originAnswerOf(candidate, origin, contextualType)
2732
+ })
2733
+ });
2734
+ const reasonIf = (condition, reason) => Boolean.match(condition, {
2735
+ onTrue: () => Option.some(reason),
2736
+ onFalse: () => Option.none()
2737
+ });
2738
+ const targetReasonOf = (target) => Option.firstSomeOf([reasonIf(target.isError, "error-type"), reasonIf(target.instantiable, "instantiable-target")]);
2739
+ const functionBodyUnknownOf = (site) => Option.firstSomeOf([
2740
+ reasonIf(Option.isNone(site.target), "no-contextual-type"),
2741
+ reasonIf(site.generator, "generator-body"),
2742
+ reasonIf(site.functionKind === "constructor", "constructor-body"),
2743
+ reasonIf(Boolean.and(Boolean.not(site.returnTypeDeclared), site.functionKind !== "setter"), "return-type-not-declared"),
2744
+ reasonIf(Boolean.and(site.async, Boolean.not(site.asyncReturnIsPromise)), "async-return-not-promise"),
2745
+ Option.flatMap(site.target, targetReasonOf)
2746
+ ]);
2747
+ const targetTextOf = (site) => Option.getOrElse(Option.map(site.target, (target) => target.text), () => "");
2748
+ const functionBodyTypedOf = (site) => Boolean.match(site.undefinedAssignable, {
2749
+ onFalse: () => notAssignableAnswer("undefined", targetTextOf(site)),
2750
+ onTrue: () => Boolean.match(site.functionKind === "getter", {
2751
+ onTrue: () => unknownAnswer("getter-requires-return"),
2752
+ onFalse: () => Boolean.match(site.targetAllowsImplicitReturn, {
2753
+ onTrue: () => assignableAnswer("undefined"),
2754
+ onFalse: () => unknownAnswer("implicit-return-rejected")
2755
+ })
2756
+ })
2757
+ });
2758
+ const functionBodyAnswerOf = (site, text) => Boolean.match(text === "{}", {
2759
+ onFalse: () => unknownAnswer("candidate-not-empty-body"),
2760
+ onTrue: () => Option.match(functionBodyUnknownOf(site), {
2761
+ onNone: () => functionBodyTypedOf(site),
2762
+ onSome: unknownAnswer
2763
+ })
2764
+ });
2765
+ const bodySiteAnswerOf = (text, site) => Match.value(site).pipe(Match.tag("SiteMissing", () => unknownAnswer("site-not-found")), Match.tag("SiteNotExpression", () => unknownAnswer("site-not-expression")), Match.tag("SiteNotFunctionBody", () => unknownAnswer("site-not-function-body")), Match.tag("SiteFunctionBody", (body) => functionBodyAnswerOf(body, text)), Match.tag("SiteExpression", () => unknownAnswer("site-not-function-body")), Match.exhaustive);
2766
+ const siteAnswerOf = (candidate, site) => Match.value(site).pipe(Match.tag("SiteMissing", () => unknownAnswer("site-not-found")), Match.tag("SiteNotExpression", () => unknownAnswer("site-not-expression")), Match.tag("SiteNotFunctionBody", () => unknownAnswer("site-not-function-body")), Match.tag("SiteFunctionBody", () => unknownAnswer("candidate-not-empty-body")), Match.tag("SiteExpression", (expression) => Option.match(expression.contextualType, {
2767
+ onNone: () => unknownAnswer("no-contextual-type"),
2768
+ onSome: (contextualType) => contextualAnswerOf(candidate, expression.origin, contextualType)
2769
+ })), Match.exhaustive);
2770
+ const answerOf = (command) => Match.value(command.candidate).pipe(Match.tag("CandidateNotContextFree", () => unknownAnswer("candidate-not-context-free")), Match.tag("CandidateMissing", () => unknownAnswer("candidate-not-found")), Match.tag("CandidateBodyText", (body) => bodySiteAnswerOf(body.text, command.site)), Match.tag("CandidateTyped", (candidate) => siteAnswerOf(candidate, command.site)), Match.exhaustive);
2771
+ const decide$2 = (command) => Result.succeed(answerOf(command));
2772
+ const answerTypeQuery = Workflow.make({
2773
+ command: AnswerTypeQueryCommand,
2774
+ decision: AnswerDecision,
2775
+ error: S.Never,
2776
+ decide: decide$2
2777
+ });
2778
+ //#endregion
2779
+ //#region src/classify-candidate.workflow.ts
2780
+ const ContextFreenessTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/CandidateContextFreeness");
2781
+ var ContextFree = class extends S.TaggedClass()("ContextFree", {}) {
2782
+ [ContextFreenessTypeId] = ContextFreenessTypeId;
2783
+ };
2784
+ var NotContextFree = class extends S.TaggedClass()("NotContextFree", {}) {
2785
+ [ContextFreenessTypeId] = ContextFreenessTypeId;
2786
+ };
2787
+ const CandidateContextFreeness = S.Union([ContextFree, NotContextFree]);
2788
+ const DOUBLE_QUOTED_STRING_LITERAL = /^"(?:[^"\\]|\\.)*"$/;
2789
+ const SINGLE_QUOTED_STRING_LITERAL = /^'(?:[^'\\]|\\.)*'$/;
2790
+ const NO_SUBSTITUTION_TEMPLATE_LITERAL = /^`[^`\\$]*`$/;
2791
+ const NUMERIC_LITERAL = /^-?[0-9]+$/;
2792
+ const BIGINT_LITERAL = /^-?[0-9]+n$/;
2793
+ const LITERAL_KEYWORDS = {
2794
+ true: true,
2795
+ false: true,
2796
+ null: true,
2797
+ undefined: true,
2798
+ "{}": true,
2799
+ "() => undefined": true,
2800
+ "() => {}": true
2801
+ };
2802
+ const CONTEXT_FREE_PATTERNS = [
2803
+ DOUBLE_QUOTED_STRING_LITERAL,
2804
+ SINGLE_QUOTED_STRING_LITERAL,
2805
+ NO_SUBSTITUTION_TEMPLATE_LITERAL,
2806
+ NUMERIC_LITERAL,
2807
+ BIGINT_LITERAL
2808
+ ];
2809
+ const isContextFree$1 = (text) => Boolean.or(LITERAL_KEYWORDS[text] === true, Arr.some(CONTEXT_FREE_PATTERNS, (pattern) => pattern.test(text)));
2810
+ const classifyOf = (text) => Boolean.match(isContextFree$1(text), {
2811
+ onTrue: () => ContextFree.make({}),
2812
+ onFalse: () => NotContextFree.make({})
2813
+ });
2814
+ const decide$1 = (command) => Result.succeed(classifyOf(command.text));
2815
+ const classifyCandidate = Workflow.make({
2816
+ command: ClassifyCandidateCommand,
2817
+ decision: CandidateContextFreeness,
2818
+ error: S.Never,
2819
+ decide: decide$1
2820
+ });
2821
+ //#endregion
2822
+ //#region src/classify-context-link.workflow.ts
2823
+ const ContextSlot = S.Literals([
2824
+ "operand",
2825
+ "element",
2826
+ "member",
2827
+ "value",
2828
+ "name",
2829
+ "condition",
2830
+ "branch",
2831
+ "left",
2832
+ "right",
2833
+ "argument",
2834
+ "callee",
2835
+ "body",
2836
+ "initializer",
2837
+ "other"
2838
+ ]);
2839
+ const LeftOperandMember = S.Literals([
2840
+ "any",
2841
+ "unknown",
2842
+ "nullish",
2843
+ "primitive",
2844
+ "falsy-literal",
2845
+ "truthy-literal",
2846
+ "always-truthy",
2847
+ "unrecognized"
2848
+ ]);
2849
+ const ReturnTarget = S.Literals([
2850
+ "none",
2851
+ "annotated",
2852
+ "unannotated-expression",
2853
+ "unannotated-declaration"
2854
+ ]);
2855
+ var ClassifyContextLinkCommand = class extends S.TaggedClass()("ClassifyContextLinkCommand", {
2856
+ parentKind: S.Enum(SyntaxKind),
2857
+ slot: ContextSlot,
2858
+ operator: S.Enum(SyntaxKind),
2859
+ constAssertion: S.Boolean,
2860
+ annotated: S.Boolean,
2861
+ returnTarget: ReturnTarget,
2862
+ leftOperand: S.Array(LeftOperandMember)
2863
+ }) {
2864
+ static [Workflow.InstrumentationBrand] = {};
2865
+ };
2866
+ const ContextLinkTypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/ContextLink");
2867
+ var LinkClimb = class extends S.TaggedClass()("LinkClimb", {}) {
2868
+ [ContextLinkTypeId] = ContextLinkTypeId;
2869
+ };
2870
+ var LinkClimbFunction = class extends S.TaggedClass()("LinkClimbFunction", {}) {
2871
+ [ContextLinkTypeId] = ContextLinkTypeId;
2872
+ };
2873
+ var LinkDeclared = class extends S.TaggedClass()("LinkDeclared", {}) {
2874
+ [ContextLinkTypeId] = ContextLinkTypeId;
2875
+ };
2876
+ var LinkCallArgument = class extends S.TaggedClass()("LinkCallArgument", {}) {
2877
+ [ContextLinkTypeId] = ContextLinkTypeId;
2878
+ };
2879
+ var LinkUnenforced = class extends S.TaggedClass()("LinkUnenforced", {}) {
2880
+ [ContextLinkTypeId] = ContextLinkTypeId;
2881
+ };
2882
+ const ContextLink = S.Union([
2883
+ LinkClimb,
2884
+ LinkClimbFunction,
2885
+ LinkDeclared,
2886
+ LinkCallArgument,
2887
+ LinkUnenforced
2888
+ ]);
2889
+ const climb = () => LinkClimb.make({});
2890
+ const climbFunction = () => LinkClimbFunction.make({});
2891
+ const declared$1 = () => LinkDeclared.make({});
2892
+ const callArgument = () => LinkCallArgument.make({});
2893
+ const unenforced$1 = () => LinkUnenforced.make({});
2894
+ const RIGHT_OPERAND_RULES = /* @__PURE__ */ new Map([
2895
+ [SyntaxKind.EqualsToken, declared$1],
2896
+ [SyntaxKind.QuestionQuestionToken, reachingWhenLeftIs(["unknown", "nullish"])],
2897
+ [SyntaxKind.BarBarToken, reachingWhenLeftIs([
2898
+ "unknown",
2899
+ "nullish",
2900
+ "primitive",
2901
+ "falsy-literal"
2902
+ ])],
2903
+ [SyntaxKind.AmpersandAmpersandToken, reachingWhenLeftIs([
2904
+ "unknown",
2905
+ "primitive",
2906
+ "truthy-literal",
2907
+ "always-truthy"
2908
+ ])]
2909
+ ]);
2910
+ function reachingWhenLeftIs(reaching) {
2911
+ return (command) => Boolean.match(Arr.some(command.leftOperand, (member) => Arr.contains(reaching, member)), {
2912
+ onTrue: climb,
2913
+ onFalse: unenforced$1
2914
+ });
2915
+ }
2916
+ const rightOperandOf = (command) => Option.match(Option.fromUndefinedOr(RIGHT_OPERAND_RULES.get(command.operator)), {
2917
+ onNone: unenforced$1,
2918
+ onSome: (rule) => rule(command)
2919
+ });
2920
+ const returnedOf = (unannotatedExpression) => (command) => Match.value(command.returnTarget).pipe(Match.when("annotated", declared$1), Match.when("unannotated-expression", unannotatedExpression), Match.when("unannotated-declaration", unenforced$1), Match.when("none", unenforced$1), Match.exhaustive);
2921
+ const initializerOf = (command) => Boolean.match(command.annotated, {
2922
+ onTrue: declared$1,
2923
+ onFalse: unenforced$1
2924
+ });
2925
+ const assertedOf = (command) => Boolean.match(command.constAssertion, {
2926
+ onTrue: climb,
2927
+ onFalse: unenforced$1
2928
+ });
2929
+ const ALLOW_LIST = {
2930
+ [SyntaxKind.ParenthesizedExpression]: { operand: climb },
2931
+ [SyntaxKind.ArrayLiteralExpression]: { element: climb },
2932
+ [SyntaxKind.ObjectLiteralExpression]: { member: climb },
2933
+ [SyntaxKind.PropertyAssignment]: { value: climb },
2934
+ [SyntaxKind.ConditionalExpression]: { branch: climb },
2935
+ [SyntaxKind.BinaryExpression]: { right: rightOperandOf },
2936
+ [SyntaxKind.AsExpression]: { operand: assertedOf },
2937
+ [SyntaxKind.SatisfiesExpression]: { operand: declared$1 },
2938
+ [SyntaxKind.CallExpression]: { argument: callArgument },
2939
+ [SyntaxKind.NewExpression]: { argument: callArgument },
2940
+ [SyntaxKind.ArrowFunction]: { body: returnedOf(climb) },
2941
+ [SyntaxKind.ReturnStatement]: { operand: returnedOf(climbFunction) },
2942
+ [SyntaxKind.VariableDeclaration]: { initializer: initializerOf },
2943
+ [SyntaxKind.PropertyDeclaration]: { initializer: initializerOf },
2944
+ [SyntaxKind.Parameter]: { initializer: initializerOf }
2945
+ };
2946
+ const isContextParentKind$1 = (kind) => Object.hasOwn(ALLOW_LIST, kind);
2947
+ const rulesOf = (kind) => ALLOW_LIST[kind];
2948
+ const ruleOf = (command) => Option.flatMap(Option.map(Option.filter(Option.some(command.parentKind), isContextParentKind$1), rulesOf), (rules) => Option.fromUndefinedOr(rules[command.slot]));
2949
+ const decide = (command) => Result.succeed(Option.match(ruleOf(command), {
2950
+ onNone: unenforced$1,
2951
+ onSome: (rule) => rule(command)
2952
+ }));
2953
+ const classifyContextLink = Workflow.make({
2954
+ command: ClassifyContextLinkCommand,
2955
+ decision: ContextLink,
2956
+ error: S.Never,
2957
+ decide
2958
+ });
2959
+ //#endregion
2960
+ //#region src/context-link-facts.ts
2961
+ const isCallLike = (parent) => isCallExpression(parent) || isNewExpression(parent);
2962
+ const isArgumentOf = (parent, node) => Arr.some(parent.arguments ?? [], (argument) => argument === node);
2963
+ const SHORT_CIRCUIT_OPERATORS = [
2964
+ SyntaxKind.QuestionQuestionToken,
2965
+ SyntaxKind.BarBarToken,
2966
+ SyntaxKind.AmpersandAmpersandToken
2967
+ ];
2968
+ const isConstName = (name) => isIdentifier(name) && name.text === "const";
2969
+ const isConstAssertion = (type) => isTypeReferenceNode(type) && isConstName(type.typeName);
2970
+ const enclosingFunctionOf = (node) => Option.flatMap(Option.fromUndefinedOr(node.parent), (parent) => isFunctionLikeDeclaration(parent) ? Option.some(parent) : enclosingFunctionOf(parent));
2971
+ const isExpressionFunction = (fn) => isArrowFunction(fn) || isFunctionExpression(fn);
2972
+ const INITIALIZED_DECLARATIONS = [
2973
+ isVariableDeclaration,
2974
+ isPropertyDeclaration,
2975
+ isParameterDeclaration
2976
+ ];
2977
+ const OPERAND_PARENTS = [
2978
+ isParenthesizedExpression,
2979
+ isAsExpression,
2980
+ isSatisfiesExpression,
2981
+ isReturnStatement
2982
+ ];
2983
+ const isInitializedDeclaration = (parent) => Arr.some(INITIALIZED_DECLARATIONS, (guard) => guard(parent));
2984
+ const isOperandParent = (parent) => Arr.some(OPERAND_PARENTS, (guard) => guard(parent));
2985
+ const slotWhen = (guard, read) => (parent, node) => guard(parent) ? Option.some(read(parent, node)) : Option.none();
2986
+ const slotIf = (filled, slot, otherwise) => filled ? slot : otherwise;
2987
+ const operandReader = slotWhen(isOperandParent, (parent, node) => slotIf(parent.expression === node, "operand", "other"));
2988
+ const callReader = slotWhen(isCallLike, (call, node) => slotIf(isArgumentOf(call, node), "argument", "callee"));
2989
+ const initializerReader = slotWhen(isInitializedDeclaration, (declaration, node) => slotIf(declaration.initializer === node, "initializer", "other"));
2990
+ const SLOT_READERS = {
2991
+ [SyntaxKind.ParenthesizedExpression]: operandReader,
2992
+ [SyntaxKind.ArrayLiteralExpression]: slotWhen(isArrayLiteralExpression, () => "element"),
2993
+ [SyntaxKind.ObjectLiteralExpression]: slotWhen(isObjectLiteralExpression, () => "member"),
2994
+ [SyntaxKind.PropertyAssignment]: slotWhen(isPropertyAssignment, (property, node) => slotIf(property.initializer === node, "value", "name")),
2995
+ [SyntaxKind.ConditionalExpression]: slotWhen(isConditionalExpression, (conditional, node) => slotIf(conditional.condition === node, "condition", "branch")),
2996
+ [SyntaxKind.BinaryExpression]: slotWhen(isBinaryExpression, (binary, node) => slotIf(binary.right === node, "right", "left")),
2997
+ [SyntaxKind.AsExpression]: operandReader,
2998
+ [SyntaxKind.SatisfiesExpression]: operandReader,
2999
+ [SyntaxKind.CallExpression]: callReader,
3000
+ [SyntaxKind.NewExpression]: callReader,
3001
+ [SyntaxKind.ArrowFunction]: slotWhen(isArrowFunction, (fn, node) => slotIf(fn.body === node, "body", "other")),
3002
+ [SyntaxKind.ReturnStatement]: operandReader,
3003
+ [SyntaxKind.VariableDeclaration]: initializerReader,
3004
+ [SyntaxKind.PropertyDeclaration]: initializerReader,
3005
+ [SyntaxKind.Parameter]: initializerReader
3006
+ };
3007
+ const isContextParentKind = (kind) => Object.hasOwn(SLOT_READERS, kind);
3008
+ const slotIn = (parent, node) => isContextParentKind(parent.kind) ? Option.getOrElse(SLOT_READERS[parent.kind](parent, node), () => "other") : "other";
3009
+ const slotOf = (node) => Option.match(Option.fromUndefinedOr(node.parent), {
3010
+ onNone: () => "other",
3011
+ onSome: (parent) => slotIn(parent, node)
3012
+ });
3013
+ const unannotatedTargetOf = (fn) => isExpressionFunction(fn) ? "unannotated-expression" : "unannotated-declaration";
3014
+ const functionTargetOf = (fn) => fn.type === void 0 ? unannotatedTargetOf(fn) : "annotated";
3015
+ const returnStatementFunctionOf = (parent) => isReturnStatement(parent) ? enclosingFunctionOf(parent) : Option.none();
3016
+ const returnFunctionOf = (parent) => isArrowFunction(parent) ? Option.some(parent) : returnStatementFunctionOf(parent);
3017
+ const returnTargetOf = (parent) => Option.match(returnFunctionOf(parent), {
3018
+ onNone: () => "none",
3019
+ onSome: functionTargetOf
3020
+ });
3021
+ const MEMBER_FLAGS = [
3022
+ [TypeFlags.Any, "any"],
3023
+ [TypeFlags.Unknown, "unknown"],
3024
+ [TypeFlags.Undefined | TypeFlags.Null | TypeFlags.Void, "nullish"],
3025
+ [TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt, "primitive"],
3026
+ [TypeFlags.Object | TypeFlags.NonPrimitive | TypeFlags.ESSymbol | TypeFlags.UniqueESSymbol, "always-truthy"]
3027
+ ];
3028
+ const FALSY_LITERAL_VALUES = [
3029
+ "",
3030
+ 0,
3031
+ 0n,
3032
+ false
3033
+ ];
3034
+ const BOOLEAN_LITERAL_NAMES = {
3035
+ true: true,
3036
+ false: false
3037
+ };
3038
+ const hasFlag = (type, flags) => (type.flags & flags) !== 0;
3039
+ const intrinsicNameOf = (type) => "intrinsicName" in type ? Option.filter(Option.some(type.intrinsicName), Predicate.isString) : Option.none();
3040
+ const intrinsicBooleanOf = (type) => Option.flatMap(intrinsicNameOf(type), (name) => Option.fromUndefinedOr(BOOLEAN_LITERAL_NAMES[name]));
3041
+ const literalValueOf = (type) => type.isLiteralType() ? Option.orElse(Option.fromUndefinedOr(type.value), () => intrinsicBooleanOf(type)) : Option.none();
3042
+ const literalMemberOf = (type) => Option.match(literalValueOf(type), {
3043
+ onNone: () => "unrecognized",
3044
+ onSome: (value) => Boolean.match(FALSY_LITERAL_VALUES.includes(value), {
3045
+ onTrue: () => "falsy-literal",
3046
+ onFalse: () => "truthy-literal"
3047
+ })
3048
+ });
3049
+ const leftOperandMemberOf = (type) => Option.getOrElse(Option.map(Arr.findFirst(MEMBER_FLAGS, ([flags]) => hasFlag(type, flags)), ([, member]) => member), () => literalMemberOf(type));
3050
+ const isShortCircuit = (parent) => isBinaryExpression(parent) && Arr.contains(SHORT_CIRCUIT_OPERATORS, parent.operatorToken.kind);
3051
+ const shortCircuitParentOf = (parent) => isShortCircuit(parent) ? Option.some(parent) : Option.none();
3052
+ const operatorOf = (parent) => isBinaryExpression(parent) ? parent.operatorToken.kind : SyntaxKind.Unknown;
3053
+ const constAssertionOf = (parent) => isAsExpression(parent) && isConstAssertion(parent.type);
3054
+ const annotatedOf = (parent) => isInitializedDeclaration(parent) && parent.type !== void 0;
3055
+ //#endregion
3056
+ //#region src/type-query.handle.ts
3057
+ const TypeId = Symbol.for("@systemfsoftware/stryker-js-typescript-checker/TypeQuery");
3058
+ const servedVersionOf = (version) => Arr.findFirst(TypeQuery.TypeQueryVersion.literals, (served) => served === version);
3059
+ const normalizeFileName = (fileName) => fileName.replace(/\\/g, "/");
3060
+ const isContextFree = (text) => {
3061
+ const command = ClassifyCandidateCommand.make({ text });
3062
+ const classified = classifyCandidate(command);
3063
+ const decision = decided(classified);
3064
+ return Match.value(decision).pipe(Match.tag("ContextFree", () => true), Match.tag("NotContextFree", () => false), Match.exhaustive);
3065
+ };
3066
+ const unsupportedVersion = (version) => TypeQuery.TypeQueryRefused.make({
3067
+ version,
3068
+ reason: "unsupported-version",
3069
+ nextAction: `Send a TypeQuery.TypeQueryRequest with version ${TypeQuery.TypeQueryVersion.literals.join(" or ")}; this server received version ${version}.`
3070
+ });
3071
+ const functionBodyNeedsVersionTwo = (version) => TypeQuery.TypeQueryRefused.make({
3072
+ version,
3073
+ reason: "unsupported-version",
3074
+ nextAction: "Send a version 2 TypeQuery.TypeQueryRequest for function-body sites; version 1 answers expression sites only."
3075
+ });
3076
+ const hasFunctionBodySite = (request) => Arr.some(request.files, (file) => Arr.some(file.sites, (site) => site.kind === "function-body"));
3077
+ const projectOpenFailed = (tsconfigFile, detail, version) => TypeQuery.TypeQueryRefused.make({
3078
+ version,
3079
+ reason: "project-open-failed",
3080
+ nextAction: `Open '${tsconfigFile}' with a valid TypeScript project and retry; opening it failed with: ${detail}`
3081
+ });
3082
+ const NOT_IN_PROJECT_NEXT_ACTION = "List the file in the tsconfig project (files/include) or drop it from the request.";
3083
+ const SERVER_CRASHED_NEXT_ACTION = "Retry the file; the next file is answered on a fresh tsgo server.";
3084
+ const crash = (failure) => ({
3085
+ _tag: "ServerCrash",
3086
+ detail: failure instanceof Error ? failure.message : String(failure)
3087
+ });
3088
+ const tryPromise = (evaluate) => Effect.tryPromise({
3089
+ try: evaluate,
3090
+ catch: crash
3091
+ });
3092
+ const makeOverlay = () => {
3093
+ const files = /* @__PURE__ */ new Map();
3094
+ return {
3095
+ fs: {
3096
+ readFile: (fileName) => files.get(normalizeFileName(fileName)),
3097
+ fileExists: (fileName) => files.has(normalizeFileName(fileName)) ? true : void 0,
3098
+ directoryExists: () => void 0,
3099
+ getAccessibleEntries: () => void 0,
3100
+ realpath: () => void 0
3101
+ },
3102
+ serve: (fileName, content) => {
3103
+ files.set(normalizeFileName(fileName), content);
3104
+ }
3105
+ };
3106
+ };
3107
+ const CLOSE_GRACE = "1 second";
3108
+ const QUERY_GRACE = "30 seconds";
3109
+ const QUERY_TIMED_OUT_NEXT_ACTION = `The query timed out after ${QUERY_GRACE} and its tsgo server was discarded. Retry the file; the next file is answered on a fresh tsgo server.`;
3110
+ const closeApi = (api) => Effect.tryPromise(() => api.close()).pipe(Effect.timeoutOption(CLOSE_GRACE), Effect.ignore);
3111
+ const closeServer = (server) => closeApi(server.api);
3112
+ const openServer = (tsconfigFile, version) => Effect.gen(function* () {
3113
+ const overlay = makeOverlay();
3114
+ const api = yield* Effect.try({
3115
+ try: () => new API({ fs: overlay.fs }),
3116
+ catch: (cause) => projectOpenFailed(tsconfigFile, crash(cause).detail, version)
3117
+ });
3118
+ const snapshot = yield* Effect.tryPromise({
3119
+ try: () => api.updateSnapshot({ openProjects: [tsconfigFile] }),
3120
+ catch: (cause) => projectOpenFailed(tsconfigFile, crash(cause).detail, version)
3121
+ }).pipe(Effect.timeoutOrElse({
3122
+ duration: QUERY_GRACE,
3123
+ orElse: () => Effect.fail(projectOpenFailed(tsconfigFile, `tsgo gave no answer within ${QUERY_GRACE}`, version))
3124
+ }), Effect.filterOrFail((opened) => opened.getProject(tsconfigFile) !== void 0, () => projectOpenFailed(tsconfigFile, "tsgo opened no project for this tsconfig", version)), Effect.tapError(() => closeApi(api)));
3125
+ return {
3126
+ tsconfigFile,
3127
+ api,
3128
+ overlay,
3129
+ snapshot: yield* Ref.make(snapshot),
3130
+ lock: yield* Semaphore.make(1)
3131
+ };
3132
+ });
3133
+ const TypeQueryServers = Handle.make()(TypeId);
3134
+ TypeQueryServers.is;
3135
+ const getOrOpen = (servers, tsconfigFile, version) => SynchronizedRef.modifyEffect(servers, (map) => Option.match(HashMap.get(map, tsconfigFile), {
3136
+ onSome: (server) => Effect.succeed([server, map]),
3137
+ onNone: () => Effect.map(openServer(tsconfigFile, version), (server) => [server, HashMap.set(map, tsconfigFile, server)])
3138
+ }));
3139
+ const discardServer = (servers, server) => Effect.flatMap(SynchronizedRef.modify(servers, (map) => Option.match(Option.filter(HashMap.get(map, server.tsconfigFile), (current) => current === server), {
3140
+ onNone: () => [false, map],
3141
+ onSome: () => [true, HashMap.remove(map, server.tsconfigFile)]
3142
+ })), (removed) => Boolean.match(removed, {
3143
+ onFalse: () => Effect.void,
3144
+ onTrue: () => closeServer(server)
3145
+ }));
3146
+ const discardAndAnswer = (servers, server, outcome) => Effect.as(discardServer(servers, server), outcome);
3147
+ const isCurrent = (servers, server) => Effect.map(SynchronizedRef.get(servers), (map) => Option.exists(HashMap.get(map, server.tsconfigFile), (current) => current === server));
3148
+ const closeAllServers = (servers) => Effect.flatMap(SynchronizedRef.getAndSet(servers, HashMap.empty()), (map) => Effect.forEach(HashMap.values(map), closeServer, { discard: true }));
3149
+ const nodeSpanOf = (node) => ({
3150
+ start: node.getStart(node.getSourceFile()),
3151
+ end: node.end
3152
+ });
3153
+ const childrenOf = (node) => {
3154
+ const children = [];
3155
+ node.forEachChild((child) => {
3156
+ children.push(child);
3157
+ });
3158
+ return children;
3159
+ };
3160
+ const spanMatches = (node, start, end) => {
3161
+ const span = nodeSpanOf(node);
3162
+ return span.start === start && span.end === end;
3163
+ };
3164
+ const spanContains = (node, start, end) => {
3165
+ const span = nodeSpanOf(node);
3166
+ return span.start <= start && end <= span.end;
3167
+ };
3168
+ const firstContainingChildOf = (node, start, end) => Option.flatMap(Arr.findFirst(childrenOf(node), (child) => spanContains(child, start, end)), (child) => nodeWithSpanOf(child, start, end));
3169
+ const nodeWithSpanOf = (node, start, end) => Option.orElse(Option.filter(Option.some(node), () => spanMatches(node, start, end)), () => firstContainingChildOf(node, start, end));
3170
+ const PROBE_OPEN = "\n;(";
3171
+ const PROBE_CLOSE = ");";
3172
+ const appendProbe = (probe, text) => {
3173
+ const start = probe.length + 3;
3174
+ return [`${probe}${PROBE_OPEN}${text}${PROBE_CLOSE}`, [text, {
3175
+ start,
3176
+ end: start + text.length
3177
+ }]];
3178
+ };
3179
+ const buildProbe = (file) => {
3180
+ const texts = Arr.dedupe(Arr.flatMap(file.sites, (site) => Boolean.match(site.kind === "function-body", {
3181
+ onTrue: () => Arr.empty(),
3182
+ onFalse: () => Arr.map(Arr.filter(site.candidates, (candidate) => isContextFree(candidate.text)), (candidate) => candidate.text)
3183
+ })));
3184
+ const [text, placed] = Arr.mapAccum(texts, file.content, appendProbe);
3185
+ return {
3186
+ text,
3187
+ slots: new Map(placed)
3188
+ };
3189
+ };
3190
+ const updateProbe = (server, fileName, probeText) => Effect.gen(function* () {
3191
+ server.overlay.serve(fileName, probeText);
3192
+ const previous = yield* Ref.get(server.snapshot);
3193
+ const next = yield* tryPromise(() => server.api.updateSnapshot({
3194
+ openProjects: [server.tsconfigFile],
3195
+ fileChanges: { changed: [normalizeFileName(fileName)] }
3196
+ }));
3197
+ yield* Ref.set(server.snapshot, next);
3198
+ yield* Effect.tryPromise(() => previous.dispose()).pipe(Effect.ignore);
3199
+ });
3200
+ const projectOf = (server) => Effect.map(Ref.get(server.snapshot), (snapshot) => Option.fromUndefinedOr(snapshot.getProject(server.tsconfigFile)));
3201
+ const sourceFileIn = (project, fileName) => Effect.map(tryPromise(() => project.program.getSourceFile(fileName)), Option.fromUndefinedOr);
3202
+ const missingReading = (site) => ({
3203
+ site,
3204
+ facts: { _tag: "SiteMissing" },
3205
+ contextType: Option.none(),
3206
+ siteType: Option.none(),
3207
+ contextualText: Option.none()
3208
+ });
3209
+ const notExpressionReading = (site, siteType) => ({
3210
+ site,
3211
+ facts: { _tag: "SiteNotExpression" },
3212
+ contextType: Option.none(),
3213
+ siteType,
3214
+ contextualText: Option.none()
3215
+ });
3216
+ const typeAt = (checker, node) => Effect.map(tryPromise(() => checker.getTypeAtLocation(node)), Option.fromUndefinedOr);
3217
+ const typeTextOf = (checker, type) => tryPromise(() => checker.typeToString(type));
3218
+ const isInstantiableFlag = (type) => (type.flags & TypeFlags.Instantiable) !== 0;
3219
+ const unionTypesOf = (type) => {
3220
+ if (!type.isUnionType()) return Option.none();
3221
+ const union = type;
3222
+ return Option.some(() => union.getTypes());
3223
+ };
3224
+ const intersectionTypesOf = (type) => {
3225
+ if (!type.isIntersectionType()) return Option.none();
3226
+ const intersection = type;
3227
+ return Option.some(() => intersection.getTypes());
3228
+ };
3229
+ const constituentsOf = (type) => Option.match(Option.orElse(unionTypesOf(type), () => intersectionTypesOf(type)), {
3230
+ onSome: (evaluate) => tryPromise(evaluate),
3231
+ onNone: () => Effect.succeed([])
3232
+ });
3233
+ const instantiableOf = (type) => Effect.gen(function* () {
3234
+ const constituents = yield* constituentsOf(type);
3235
+ return Boolean.or(isInstantiableFlag(type), Arr.some(constituents, isInstantiableFlag));
3236
+ });
3237
+ const contextualFactsOf = (checker, type) => Effect.gen(function* () {
3238
+ const text = yield* typeTextOf(checker, type);
3239
+ const instantiable = yield* instantiableOf(type);
3240
+ return {
3241
+ text,
3242
+ isError: type.isErrorType(),
3243
+ instantiable
3244
+ };
3245
+ });
3246
+ const DECLARED_CONTEXT = { _tag: "DeclaredContext" };
3247
+ const UNENFORCED_CONTEXT = { _tag: "UnenforcedContext" };
3248
+ const declared = () => Effect.succeed(DECLARED_CONTEXT);
3249
+ const unenforced = () => Effect.succeed(UNENFORCED_CONTEXT);
3250
+ const unionMembersOf = (type) => Option.match(unionTypesOf(type), {
3251
+ onSome: (evaluate) => tryPromise(evaluate),
3252
+ onNone: () => Effect.succeed([type])
3253
+ });
3254
+ const leftMembersOf = (checker, binary) => Effect.flatMap(typeAt(checker, binary.left), (type) => Option.match(type, {
3255
+ onNone: () => Effect.succeed(Arr.empty()),
3256
+ onSome: (left) => Effect.map(unionMembersOf(left), Arr.map(leftOperandMemberOf))
3257
+ }));
3258
+ const leftOperandOf = (checker, parent, slot) => Option.match(Option.filter(shortCircuitParentOf(parent), () => slot === "right"), {
3259
+ onNone: () => Effect.succeed(Arr.empty()),
3260
+ onSome: (binary) => leftMembersOf(checker, binary)
3261
+ });
3262
+ const linkCommandOf = (checker, parent, node) => {
3263
+ const slot = slotOf(node);
3264
+ return Effect.map(leftOperandOf(checker, parent, slot), (leftOperand) => ClassifyContextLinkCommand.make({
3265
+ parentKind: parent.kind,
3266
+ slot,
3267
+ operator: operatorOf(parent),
3268
+ constAssertion: constAssertionOf(parent),
3269
+ annotated: annotatedOf(parent),
3270
+ returnTarget: returnTargetOf(parent),
3271
+ leftOperand
3272
+ }));
3273
+ };
3274
+ const followLink = (checker, parent, link) => Match.value(link).pipe(Match.tag("LinkClimb", () => originOf(checker, parent)), Match.tag("LinkClimbFunction", () => Option.match(enclosingFunctionOf(parent), {
3275
+ onNone: unenforced,
3276
+ onSome: (fn) => originOf(checker, fn)
3277
+ })), Match.tag("LinkDeclared", declared), Match.tag("LinkCallArgument", () => isCallLike(parent) ? callArgumentFactsOf(checker, parent) : unenforced()), Match.tag("LinkUnenforced", unenforced), Match.exhaustive);
3278
+ function originOf(checker, node) {
3279
+ return Option.match(Option.fromUndefinedOr(node.parent), {
3280
+ onNone: unenforced,
3281
+ onSome: (parent) => Effect.flatMap(linkCommandOf(checker, parent, node), (command) => followLink(checker, parent, decided(classifyContextLink(command))))
3282
+ });
3283
+ }
3284
+ const signatureKindOf = (parent) => isNewExpression(parent) ? SignatureKind.Construct : SignatureKind.Call;
3285
+ const callArgumentFactsOf = (checker, parent) => Effect.gen(function* () {
3286
+ const calleeType = yield* typeAt(checker, parent.expression);
3287
+ const signatures = yield* Option.match(calleeType, {
3288
+ onNone: () => Effect.succeed(Arr.empty()),
3289
+ onSome: (type) => tryPromise(() => checker.getSignaturesOfType(type, signatureKindOf(parent)))
3290
+ });
3291
+ const typeParameterCounts = yield* Effect.forEach(signatures, (signature) => Effect.map(tryPromise(() => signature.getTypeParameters()), (parameters) => parameters.length));
3292
+ return {
3293
+ _tag: "CallArgument",
3294
+ signatureCount: signatures.length,
3295
+ declaredGeneric: Arr.some(typeParameterCounts, (count) => count > 0)
3296
+ };
3297
+ });
3298
+ const asExpression = (node) => Option.flatMap(Option.some(node), (candidate) => isExpression(candidate) ? Option.some(candidate) : Option.none());
3299
+ const expressionReadingOf = (project, site, node, siteType) => Effect.gen(function* () {
3300
+ const contextType = yield* Effect.map(tryPromise(() => project.checker.getContextualType(node)), Option.fromUndefinedOr);
3301
+ const contextual = yield* Option.match(contextType, {
3302
+ onNone: () => Effect.succeed(Option.none()),
3303
+ onSome: (type) => Effect.asSome(contextualFactsOf(project.checker, type))
3304
+ });
3305
+ return {
3306
+ site,
3307
+ facts: {
3308
+ _tag: "SiteExpression",
3309
+ contextualType: contextual,
3310
+ origin: yield* originOf(project.checker, node)
3311
+ },
3312
+ contextType,
3313
+ siteType,
3314
+ contextualText: Option.map(contextual, (facts) => facts.text)
3315
+ };
3316
+ });
3317
+ const readingOf = (project, site, node) => Effect.gen(function* () {
3318
+ const siteType = yield* Option.match(yield* typeAt(project.checker, node), {
3319
+ onNone: () => Effect.succeed(Option.none()),
3320
+ onSome: (type) => Effect.asSome(typeTextOf(project.checker, type))
3321
+ });
3322
+ return yield* Option.match(asExpression(node), {
3323
+ onNone: () => Effect.succeed(notExpressionReading(site, siteType)),
3324
+ onSome: (expression) => expressionReadingOf(project, site, expression, siteType)
3325
+ });
3326
+ });
3327
+ const notFunctionBodyReading = (site) => ({
3328
+ site,
3329
+ facts: { _tag: "SiteNotFunctionBody" },
3330
+ contextType: Option.none(),
3331
+ siteType: Option.none(),
3332
+ contextualText: Option.none()
3333
+ });
3334
+ const asyncOf = (fn) => (fn.modifierFlags & ModifierFlags.Async) !== 0;
3335
+ const functionLikeBodyOf = (node) => Boolean.match(isBlock(node), {
3336
+ onFalse: () => Option.none(),
3337
+ onTrue: () => Option.filter(Option.flatMap(Option.fromUndefinedOr(node.parent), (parent) => Option.filter(Option.some(parent), isFunctionLikeDeclaration)), (fn) => fn.body === node)
3338
+ });
3339
+ const FUNCTION_BODY_KIND_GUARDS = [
3340
+ [isGetAccessorDeclaration, "getter"],
3341
+ [isSetAccessorDeclaration, "setter"],
3342
+ [isConstructorDeclaration, "constructor"]
3343
+ ];
3344
+ const functionKindOf = (fn) => Option.getOrElse(Option.map(Arr.findFirst(FUNCTION_BODY_KIND_GUARDS, ([guard]) => guard(fn)), ([, kind]) => kind), () => "other");
3345
+ const promiseArgumentOf = (fn) => Option.flatMap(Option.fromUndefinedOr(fn.type), (annotation) => Option.flatMap(Option.filter(Option.some(annotation), isTypeReferenceNode), (reference) => Option.flatMap(Option.filter(Option.some(reference.typeName), isIdentifier), (name) => Boolean.match(name.text === "Promise", {
3346
+ onTrue: () => Arr.head(reference.typeArguments ?? []),
3347
+ onFalse: () => Option.none()
3348
+ }))));
3349
+ const promiseArgumentForTargetOf = (fn) => Boolean.match(asyncOf(fn), {
3350
+ onTrue: () => promiseArgumentOf(fn),
3351
+ onFalse: () => Option.none()
3352
+ });
3353
+ const isVoidLikeFlag = (type) => (type.flags & (TypeFlags.Void | TypeFlags.Undefined | TypeFlags.Any)) !== 0;
3354
+ const allowsImplicitReturnOf = (type) => Boolean.match(isVoidLikeFlag(type), {
3355
+ onTrue: () => Effect.succeed(true),
3356
+ onFalse: () => Effect.map(Option.match(unionTypesOf(type), {
3357
+ onNone: () => Effect.succeed(Arr.empty()),
3358
+ onSome: (evaluate) => tryPromise(evaluate)
3359
+ }), (members) => Arr.some(members, (member) => (member.flags & TypeFlags.Void) !== 0))
3360
+ });
3361
+ const signatureReturnTypeOf = (checker, fn) => Effect.gen(function* () {
3362
+ const signature = yield* tryPromise(() => checker.getSignatureFromDeclaration(fn));
3363
+ return yield* Option.match(Option.fromUndefinedOr(signature), {
3364
+ onNone: () => Effect.succeed(Option.none()),
3365
+ onSome: (found) => Effect.map(tryPromise(() => checker.getReturnTypeOfSignature(found)), Option.fromUndefinedOr)
3366
+ });
3367
+ });
3368
+ const targetTypeOf = (checker, fn) => Option.match(promiseArgumentForTargetOf(fn), {
3369
+ onNone: () => signatureReturnTypeOf(checker, fn),
3370
+ onSome: (argument) => Effect.map(tryPromise(() => checker.getTypeFromTypeNode(argument)), Option.fromUndefinedOr)
3371
+ });
3372
+ const functionBodyFactsOf = (checker, fn) => Effect.gen(function* () {
3373
+ const targetType = yield* targetTypeOf(checker, fn);
3374
+ const target = yield* Option.match(targetType, {
3375
+ onNone: () => Effect.succeed(Option.none()),
3376
+ onSome: (type) => Effect.asSome(contextualFactsOf(checker, type))
3377
+ });
3378
+ const undefinedType = yield* tryPromise(() => checker.getUndefinedType());
3379
+ const undefinedAssignable = yield* Option.match(targetType, {
3380
+ onNone: () => Effect.succeed(false),
3381
+ onSome: (type) => tryPromise(() => checker.isTypeAssignableTo(undefinedType, type))
3382
+ });
3383
+ const targetAllowsImplicitReturn = yield* Option.match(targetType, {
3384
+ onNone: () => Effect.succeed(false),
3385
+ onSome: allowsImplicitReturnOf
3386
+ });
3387
+ return {
3388
+ _tag: "SiteFunctionBody",
3389
+ functionKind: functionKindOf(fn),
3390
+ generator: fn.asteriskToken !== void 0,
3391
+ async: asyncOf(fn),
3392
+ returnTypeDeclared: fn.type !== void 0,
3393
+ asyncReturnIsPromise: Boolean.and(asyncOf(fn), Option.isSome(promiseArgumentOf(fn))),
3394
+ target,
3395
+ undefinedAssignable,
3396
+ targetAllowsImplicitReturn
3397
+ };
3398
+ });
3399
+ const functionBodyReading = (project, site, node) => Option.match(functionLikeBodyOf(node), {
3400
+ onNone: () => Effect.succeed(notFunctionBodyReading(site)),
3401
+ onSome: (fn) => Effect.map(functionBodyFactsOf(project.checker, fn), (facts) => ({
3402
+ site,
3403
+ facts,
3404
+ contextType: Option.none(),
3405
+ siteType: Option.none(),
3406
+ contextualText: Option.map(facts.target, (target) => target.text)
3407
+ }))
3408
+ });
3409
+ const readSite = (sourceFile, project, content, site) => {
3410
+ const lineStarts = lineStartsOf(content);
3411
+ const range = Option.all([offsetAt(lineStarts, site.location.start), offsetAt(lineStarts, site.location.end)]);
3412
+ const node = Option.flatMap(range, ([start, end]) => nodeWithSpanOf(sourceFile, start, end));
3413
+ return Option.match(node, {
3414
+ onNone: () => Effect.succeed(missingReading(site)),
3415
+ onSome: (found) => Boolean.match(site.kind === "function-body", {
3416
+ onTrue: () => functionBodyReading(project, site, found),
3417
+ onFalse: () => readingOf(project, site, found)
3418
+ })
3419
+ });
3420
+ };
3421
+ const candidateNodeOf = (probe, sourceFile, candidate) => Option.flatMap(Option.fromUndefinedOr(probe.slots.get(candidate.text)), (found) => nodeWithSpanOf(sourceFile, found.start, found.end));
3422
+ const typedCandidateFactsOf = (project, contextType, candidateType) => Effect.gen(function* () {
3423
+ return {
3424
+ _tag: "CandidateTyped",
3425
+ candidateType: yield* typeTextOf(project.checker, candidateType),
3426
+ assignable: yield* Option.match(contextType, {
3427
+ onNone: () => Effect.succeed(false),
3428
+ onSome: (contextual) => tryPromise(() => project.checker.isTypeAssignableTo(candidateType, contextual))
3429
+ })
3430
+ };
3431
+ });
3432
+ const contextFreeCandidateFactsOf = (probe, sourceFile, project, contextType, candidate) => Effect.gen(function* () {
3433
+ const candidateType = yield* Option.match(candidateNodeOf(probe, sourceFile, candidate), {
3434
+ onNone: () => Effect.succeed(Option.none()),
3435
+ onSome: (node) => typeAt(project.checker, node)
3436
+ });
3437
+ return yield* Option.match(candidateType, {
3438
+ onNone: () => Effect.succeed({ _tag: "CandidateMissing" }),
3439
+ onSome: (type) => typedCandidateFactsOf(project, contextType, type)
3440
+ });
3441
+ });
3442
+ const candidateFactsOf = (probe, sourceFile, project, contextType, candidate) => Boolean.match(isContextFree(candidate.text), {
3443
+ onTrue: () => contextFreeCandidateFactsOf(probe, sourceFile, project, contextType, candidate),
3444
+ onFalse: () => Effect.succeed({ _tag: "CandidateNotContextFree" })
3445
+ });
3446
+ const portAnswerOf = (decision) => Match.valueTags(decision, {
3447
+ AnswerAssignable: ({ candidateType }) => TypeQuery.Assignable.make({ candidateType }),
3448
+ AnswerNotAssignable: ({ candidateType, contextualType }) => TypeQuery.NotAssignable.make({
3449
+ candidateType,
3450
+ contextualType
3451
+ }),
3452
+ AnswerUnknown: ({ reason }) => TypeQuery.Unknown.make({ reason })
3453
+ });
3454
+ const answerCandidate = (probe, sourceFile, project, reading, candidate) => Effect.gen(function* () {
3455
+ const facts = yield* Boolean.match(reading.site.kind === "function-body", {
3456
+ onTrue: () => Effect.succeed({
3457
+ _tag: "CandidateBodyText",
3458
+ text: candidate.text
3459
+ }),
3460
+ onFalse: () => candidateFactsOf(probe, sourceFile, project, reading.contextType, candidate)
3461
+ });
3462
+ const decision = decided(answerTypeQuery(AnswerTypeQueryCommand.make({
3463
+ site: reading.facts,
3464
+ candidate: facts
3465
+ })));
3466
+ return {
3467
+ candidateId: candidate.candidateId,
3468
+ answer: portAnswerOf(decision)
3469
+ };
3470
+ });
3471
+ const answerSite = (probe, sourceFile, project, reading) => Effect.map(Effect.forEach(reading.site.candidates, (candidate) => answerCandidate(probe, sourceFile, project, reading, candidate), { concurrency: 1 }), (candidates) => ({
3472
+ siteId: reading.site.siteId,
3473
+ siteType: reading.siteType,
3474
+ contextualType: reading.contextualText,
3475
+ candidates
3476
+ }));
3477
+ const notInProject = (fileName) => ({
3478
+ _tag: "FileRefused",
3479
+ fileName,
3480
+ reason: "not-in-project",
3481
+ nextAction: NOT_IN_PROJECT_NEXT_ACTION
3482
+ });
3483
+ const serverCrashed = (fileName) => ({
3484
+ _tag: "FileRefused",
3485
+ fileName,
3486
+ reason: "server-crashed",
3487
+ nextAction: SERVER_CRASHED_NEXT_ACTION
3488
+ });
3489
+ const queryTimedOut = (fileName) => ({
3490
+ _tag: "FileRefused",
3491
+ fileName,
3492
+ reason: "query-timed-out",
3493
+ nextAction: QUERY_TIMED_OUT_NEXT_ACTION
3494
+ });
3495
+ const projectAndFile = (server, file) => Effect.gen(function* () {
3496
+ const project = yield* projectOf(server);
3497
+ const sourceFile = yield* Option.match(project, {
3498
+ onNone: () => Effect.succeed(Option.none()),
3499
+ onSome: (known) => sourceFileIn(known, file.fileName)
3500
+ });
3501
+ return Option.all([project, sourceFile]);
3502
+ });
3503
+ const answeredFile = (probe, project, sourceFile, file) => Effect.gen(function* () {
3504
+ const readings = yield* Effect.forEach(file.sites, (site) => readSite(sourceFile, project, file.content, site), { concurrency: 1 });
3505
+ const sites = yield* Effect.forEach(readings, (reading) => answerSite(probe, sourceFile, project, reading), { concurrency: 1 });
3506
+ return {
3507
+ _tag: "FileAnswered",
3508
+ fileName: file.fileName,
3509
+ sites
3510
+ };
3511
+ });
3512
+ const answerProjectFile = (server, file) => Effect.gen(function* () {
3513
+ const probe = buildProbe(file);
3514
+ yield* updateProbe(server, file.fileName, probe.text);
3515
+ const after = yield* projectAndFile(server, file);
3516
+ return yield* Option.match(after, {
3517
+ onNone: () => Effect.succeed(notInProject(file.fileName)),
3518
+ onSome: ([project, sourceFile]) => answeredFile(probe, project, sourceFile, file)
3519
+ });
3520
+ });
3521
+ const processFile = (server, file) => Effect.gen(function* () {
3522
+ const before = yield* projectAndFile(server, file);
3523
+ return yield* Option.match(before, {
3524
+ onNone: () => Effect.succeed(notInProject(file.fileName)),
3525
+ onSome: () => answerProjectFile(server, file)
3526
+ });
3527
+ });
3528
+ const serveFile = (servers, tsconfigFile, file, version) => Effect.flatMap(getOrOpen(servers, tsconfigFile, version), (server) => Semaphore.withPermit(server.lock, Effect.flatMap(isCurrent(servers, server), (current) => Boolean.match(current, {
3529
+ onFalse: () => Effect.suspend(() => serveFile(servers, tsconfigFile, file, version)),
3530
+ onTrue: () => Effect.timeoutOption(processFile(server, file), QUERY_GRACE).pipe(Effect.matchEffect({
3531
+ onFailure: () => discardAndAnswer(servers, server, serverCrashed(file.fileName)),
3532
+ onSuccess: (settled) => Option.match(settled, {
3533
+ onNone: () => discardAndAnswer(servers, server, queryTimedOut(file.fileName)),
3534
+ onSome: (outcome) => Effect.succeed(outcome)
3535
+ })
3536
+ }))
3537
+ }))));
3538
+ const makeShape = (servers) => ({ query: (request) => Effect.gen(function* () {
3539
+ const version = yield* Effect.fromOption(servedVersionOf(request.version), () => unsupportedVersion(request.version));
3540
+ const tsconfigFile = normalizeFileName(request.tsconfigFile);
3541
+ return {
3542
+ version,
3543
+ files: yield* Boolean.match(Boolean.and(version === 1, hasFunctionBodySite(request)), {
3544
+ onTrue: () => Effect.fail(functionBodyNeedsVersionTwo(request.version)),
3545
+ onFalse: () => Effect.forEach(request.files, (file) => serveFile(servers, tsconfigFile, file, request.version), { concurrency: 1 })
3546
+ })
3547
+ };
3548
+ }) });
3549
+ const layer = Layer.effect(TypeQuery.TypeQuery, Effect.map(Effect.acquireRelease(Effect.map(SynchronizedRef.make(HashMap.empty()), (servers) => TypeQueryServers.make({}, servers)), (self) => closeAllServers(TypeQueryServers.slot(self))), (self) => makeShape(TypeQueryServers.slot(self))));
3550
+ //#endregion
3551
+ export { groups as a, nodes as c, CheckMutantsInput as d, MutantVerdict as f, describeDiagnostics as i, programDigest as l, CheckMutantsCommand as m, check as n, init as o, tceFieldOf as p, close as r, make as s, layer as t, DryRunCompileErrors as u };