funkscript 0.2.6 → 0.2.7

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.
Files changed (171) hide show
  1. package/README.md +1 -1
  2. package/dist/cli/build-watch.d.ts.map +1 -1
  3. package/dist/cli/build-watch.js +4 -24
  4. package/dist/cli/build-watch.js.map +1 -1
  5. package/dist/cli/build.d.ts.map +1 -1
  6. package/dist/cli/build.js +3 -58
  7. package/dist/cli/build.js.map +1 -1
  8. package/dist/cli/check-policy.d.ts +9 -0
  9. package/dist/cli/check-policy.d.ts.map +1 -0
  10. package/dist/cli/check-policy.js +39 -0
  11. package/dist/cli/check-policy.js.map +1 -0
  12. package/dist/cli/check.d.ts.map +1 -1
  13. package/dist/cli/check.js +16 -30
  14. package/dist/cli/check.js.map +1 -1
  15. package/dist/cli/commands.d.ts.map +1 -1
  16. package/dist/cli/commands.js +11 -0
  17. package/dist/cli/commands.js.map +1 -1
  18. package/dist/cli/doctor.d.ts.map +1 -1
  19. package/dist/cli/doctor.js +2 -6
  20. package/dist/cli/doctor.js.map +1 -1
  21. package/dist/cli/index.js +3 -0
  22. package/dist/cli/index.js.map +1 -1
  23. package/dist/cli/query.d.ts +3 -0
  24. package/dist/cli/query.d.ts.map +1 -0
  25. package/dist/cli/query.js +152 -0
  26. package/dist/cli/query.js.map +1 -0
  27. package/dist/cli/run.d.ts.map +1 -1
  28. package/dist/cli/run.js +2 -29
  29. package/dist/cli/run.js.map +1 -1
  30. package/dist/cli/tsc.d.ts.map +1 -1
  31. package/dist/cli/tsc.js +2 -6
  32. package/dist/cli/tsc.js.map +1 -1
  33. package/dist/compiler/check.d.ts.map +1 -1
  34. package/dist/compiler/check.js +18 -28
  35. package/dist/compiler/check.js.map +1 -1
  36. package/dist/compiler/diagnostics-json.d.ts +73 -0
  37. package/dist/compiler/diagnostics-json.d.ts.map +1 -0
  38. package/dist/compiler/diagnostics-json.js +957 -0
  39. package/dist/compiler/diagnostics-json.js.map +1 -0
  40. package/dist/compiler/escape-audit.d.ts +46 -0
  41. package/dist/compiler/escape-audit.d.ts.map +1 -0
  42. package/dist/compiler/escape-audit.js +682 -0
  43. package/dist/compiler/escape-audit.js.map +1 -0
  44. package/dist/compiler/modules/output-plan.d.ts.map +1 -1
  45. package/dist/compiler/modules/output-plan.js +10 -5
  46. package/dist/compiler/modules/output-plan.js.map +1 -1
  47. package/dist/compiler/modules/source-files.d.ts +2 -0
  48. package/dist/compiler/modules/source-files.d.ts.map +1 -1
  49. package/dist/compiler/modules/source-files.js +8 -0
  50. package/dist/compiler/modules/source-files.js.map +1 -1
  51. package/dist/compiler/numeric-comparisons.d.ts.map +1 -1
  52. package/dist/compiler/numeric-comparisons.js +13 -7
  53. package/dist/compiler/numeric-comparisons.js.map +1 -1
  54. package/dist/compiler/pipelines/resolution.d.ts.map +1 -1
  55. package/dist/compiler/pipelines/resolution.js +24 -23
  56. package/dist/compiler/pipelines/resolution.js.map +1 -1
  57. package/dist/compiler/query.d.ts +53 -0
  58. package/dist/compiler/query.d.ts.map +1 -0
  59. package/dist/compiler/query.js +781 -0
  60. package/dist/compiler/query.js.map +1 -0
  61. package/dist/compiler/source-map.d.ts.map +1 -1
  62. package/dist/compiler/source-map.js +2 -7
  63. package/dist/compiler/source-map.js.map +1 -1
  64. package/dist/compiler/type-view-paths.d.ts +2 -0
  65. package/dist/compiler/type-view-paths.d.ts.map +1 -1
  66. package/dist/compiler/type-view-paths.js +8 -0
  67. package/dist/compiler/type-view-paths.js.map +1 -1
  68. package/dist/compiler/typescript-context.d.ts.map +1 -1
  69. package/dist/compiler/typescript-context.js +5 -7
  70. package/dist/compiler/typescript-context.js.map +1 -1
  71. package/dist/emitter/assemblyscript.d.ts.map +1 -1
  72. package/dist/emitter/assemblyscript.js +120 -136
  73. package/dist/emitter/assemblyscript.js.map +1 -1
  74. package/dist/formatter/index.d.ts +9 -0
  75. package/dist/formatter/index.d.ts.map +1 -1
  76. package/dist/formatter/index.js +158 -2
  77. package/dist/formatter/index.js.map +1 -1
  78. package/dist/index.d.ts +3 -0
  79. package/dist/index.d.ts.map +1 -1
  80. package/dist/index.js +3 -0
  81. package/dist/index.js.map +1 -1
  82. package/dist/lsp/completion.d.ts +25 -0
  83. package/dist/lsp/completion.d.ts.map +1 -1
  84. package/dist/lsp/completion.js +1114 -51
  85. package/dist/lsp/completion.js.map +1 -1
  86. package/dist/lsp/definition.d.ts +2 -0
  87. package/dist/lsp/definition.d.ts.map +1 -1
  88. package/dist/lsp/definition.js +52 -58
  89. package/dist/lsp/definition.js.map +1 -1
  90. package/dist/lsp/hover.d.ts +5 -1
  91. package/dist/lsp/hover.d.ts.map +1 -1
  92. package/dist/lsp/hover.js +1000 -41
  93. package/dist/lsp/hover.js.map +1 -1
  94. package/dist/lsp/imports.d.ts +2 -0
  95. package/dist/lsp/imports.d.ts.map +1 -1
  96. package/dist/lsp/imports.js +35 -20
  97. package/dist/lsp/imports.js.map +1 -1
  98. package/dist/lsp/navigation.d.ts +1 -1
  99. package/dist/lsp/navigation.d.ts.map +1 -1
  100. package/dist/lsp/navigation.js +30 -12
  101. package/dist/lsp/navigation.js.map +1 -1
  102. package/dist/lsp/range-format.d.ts +4 -0
  103. package/dist/lsp/range-format.d.ts.map +1 -0
  104. package/dist/lsp/range-format.js +88 -0
  105. package/dist/lsp/range-format.js.map +1 -0
  106. package/dist/lsp/schema-import-hover.d.ts +8 -0
  107. package/dist/lsp/schema-import-hover.d.ts.map +1 -0
  108. package/dist/lsp/schema-import-hover.js +52 -0
  109. package/dist/lsp/schema-import-hover.js.map +1 -0
  110. package/dist/lsp/server.d.ts +1 -0
  111. package/dist/lsp/server.d.ts.map +1 -1
  112. package/dist/lsp/server.js +53 -48
  113. package/dist/lsp/server.js.map +1 -1
  114. package/dist/lsp/workspace.d.ts +3 -1
  115. package/dist/lsp/workspace.d.ts.map +1 -1
  116. package/dist/lsp/workspace.js +66 -10
  117. package/dist/lsp/workspace.js.map +1 -1
  118. package/dist/plugins/bun.d.ts +2 -18
  119. package/dist/plugins/bun.d.ts.map +1 -1
  120. package/dist/plugins/bun.js +5 -30
  121. package/dist/plugins/bun.js.map +1 -1
  122. package/dist/plugins/esbuild.d.ts +1 -1
  123. package/dist/plugins/esbuild.d.ts.map +1 -1
  124. package/dist/plugins/esbuild.js +10 -36
  125. package/dist/plugins/esbuild.js.map +1 -1
  126. package/dist/plugins/server-boundary.d.ts +14 -0
  127. package/dist/plugins/server-boundary.d.ts.map +1 -0
  128. package/dist/plugins/server-boundary.js +25 -0
  129. package/dist/plugins/server-boundary.js.map +1 -0
  130. package/dist/plugins/vite.d.ts +2 -18
  131. package/dist/plugins/vite.d.ts.map +1 -1
  132. package/dist/plugins/vite.js +4 -29
  133. package/dist/plugins/vite.js.map +1 -1
  134. package/package.json +1 -1
  135. package/src/cli/build-watch.ts +4 -26
  136. package/src/cli/build.ts +9 -60
  137. package/src/cli/check-policy.ts +54 -0
  138. package/src/cli/check.ts +19 -31
  139. package/src/cli/commands.ts +13 -0
  140. package/src/cli/doctor.ts +2 -5
  141. package/src/cli/index.ts +3 -0
  142. package/src/cli/query.ts +191 -0
  143. package/src/cli/run.ts +5 -30
  144. package/src/cli/tsc.ts +2 -5
  145. package/src/compiler/check.ts +28 -48
  146. package/src/compiler/diagnostics-json.ts +1205 -0
  147. package/src/compiler/escape-audit.ts +913 -0
  148. package/src/compiler/modules/output-plan.ts +11 -9
  149. package/src/compiler/modules/source-files.ts +9 -0
  150. package/src/compiler/numeric-comparisons.ts +14 -8
  151. package/src/compiler/pipelines/resolution.ts +30 -26
  152. package/src/compiler/query.ts +1177 -0
  153. package/src/compiler/source-map.ts +3 -7
  154. package/src/compiler/type-view-paths.ts +7 -0
  155. package/src/compiler/typescript-context.ts +6 -7
  156. package/src/emitter/assemblyscript.ts +101 -147
  157. package/src/formatter/index.ts +229 -2
  158. package/src/index.ts +3 -0
  159. package/src/lsp/completion.ts +1452 -66
  160. package/src/lsp/definition.ts +50 -58
  161. package/src/lsp/hover.ts +1442 -40
  162. package/src/lsp/imports.ts +55 -21
  163. package/src/lsp/navigation.ts +41 -22
  164. package/src/lsp/range-format.ts +102 -0
  165. package/src/lsp/schema-import-hover.ts +76 -0
  166. package/src/lsp/server.ts +69 -69
  167. package/src/lsp/workspace.ts +63 -9
  168. package/src/plugins/bun.ts +14 -66
  169. package/src/plugins/esbuild.ts +16 -55
  170. package/src/plugins/server-boundary.ts +41 -0
  171. package/src/plugins/vite.ts +12 -62
@@ -0,0 +1,1177 @@
1
+ import * as Effect from "effect/Effect";
2
+ import * as fs from "node:fs/promises";
3
+ import * as path from "node:path";
4
+ import ts from "typescript";
5
+ import type {
6
+ BindingDeclaration,
7
+ BindingTarget,
8
+ ErrorDeclaration,
9
+ Pattern,
10
+ Program,
11
+ SchemaDeclaration,
12
+ ServiceDeclaration,
13
+ Span,
14
+ StringLiteral,
15
+ TypedHole,
16
+ } from "../ast/types.js";
17
+ import { compileString, CompilerError } from "../compiler.js";
18
+ import { toErrorMessage } from "../errors.js";
19
+ import { DEFAULT_COMPILER_OPTIONS } from "./check.js";
20
+ import { resolveFunModule } from "./modules/resolution.js";
21
+ import {
22
+ JSX_INTRINSICS_DECLARATION,
23
+ TS_RESET_DECLARATION,
24
+ TYPE_FEST_DECLARATION,
25
+ } from "./typescript-context.js";
26
+
27
+ export interface EffectChannelInfo {
28
+ success: string;
29
+ error: string;
30
+ requirements: string[];
31
+ }
32
+
33
+ export type QueriedSymbolKind =
34
+ "binding" | "function" | "schema" | "error" | "service" | "type";
35
+
36
+ export interface QueriedSymbol {
37
+ name: string;
38
+ kind: QueriedSymbolKind;
39
+ exported: boolean;
40
+ file: string;
41
+ line: number;
42
+ column: number;
43
+ type: string;
44
+ effect?: EffectChannelInfo;
45
+ }
46
+
47
+ export interface QueriedHole {
48
+ file: string;
49
+ line: number;
50
+ column: number;
51
+ message?: string;
52
+ expectedType?: string;
53
+ }
54
+
55
+ export interface FileQueryReport {
56
+ file: string;
57
+ imports: string[];
58
+ symbols: QueriedSymbol[];
59
+ holes: QueriedHole[];
60
+ }
61
+
62
+ export interface QueryReport {
63
+ schemaVersion: 1;
64
+ files: FileQueryReport[];
65
+ }
66
+
67
+ export interface QueryOptions {
68
+ cwd?: string;
69
+ symbol?: string;
70
+ }
71
+
72
+ interface CompiledVirtualFile {
73
+ funPath: string;
74
+ virtualTsPath: string;
75
+ ast: Program;
76
+ typescript: string;
77
+ }
78
+
79
+ interface TsHoleMatch {
80
+ call: ts.CallExpression;
81
+ rawMessage: string;
82
+ }
83
+
84
+ interface TopLevelDeclEntry {
85
+ exported: boolean;
86
+ decl:
87
+ | SchemaDeclaration
88
+ | ErrorDeclaration
89
+ | ServiceDeclaration
90
+ | BindingDeclaration;
91
+ }
92
+
93
+ function getCompilerOptions(cwd: string): ts.CompilerOptions {
94
+ let baseOptions: ts.CompilerOptions = { ...DEFAULT_COMPILER_OPTIONS };
95
+ const configPath = ts.findConfigFile(cwd, ts.sys.fileExists, "tsconfig.json");
96
+ if (configPath) {
97
+ const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
98
+ if (!configFile.error && configFile.config) {
99
+ const parsed = ts.parseJsonConfigFileContent(
100
+ configFile.config,
101
+ ts.sys,
102
+ path.dirname(configPath),
103
+ );
104
+ baseOptions = { ...baseOptions, ...parsed.options };
105
+ }
106
+ }
107
+ return {
108
+ ...baseOptions,
109
+ noEmit: true,
110
+ allowImportingTsExtensions: true,
111
+ };
112
+ }
113
+
114
+ function toVirtualTsPath(fullFunPath: string): string {
115
+ const ext = fullFunPath.endsWith(".funx") ? ".tsx" : ".ts";
116
+ return `${fullFunPath}${ext}`;
117
+ }
118
+
119
+ function cleanTypeString(typeText: string): string {
120
+ return typeText.replace(/\b([A-Z][A-Za-z0-9_]*)\$Class\b/g, "$1");
121
+ }
122
+
123
+ function formatType(
124
+ checker: ts.TypeChecker,
125
+ type: ts.Type,
126
+ enclosingNode?: ts.Node,
127
+ ): string {
128
+ return cleanTypeString(
129
+ checker.typeToString(type, enclosingNode, ts.TypeFormatFlags.NoTruncation),
130
+ );
131
+ }
132
+
133
+ function extractStringLiteralValue(lit: StringLiteral): string {
134
+ const fromParts = lit.parts
135
+ .map((p) => (p.kind === "StringRawPart" ? p.value : ""))
136
+ .join("");
137
+ if (fromParts.length > 0) return fromParts;
138
+ if (
139
+ (lit.raw.startsWith('"') && lit.raw.endsWith('"')) ||
140
+ (lit.raw.startsWith("'") && lit.raw.endsWith("'"))
141
+ ) {
142
+ return lit.raw.slice(1, -1);
143
+ }
144
+ return lit.raw;
145
+ }
146
+
147
+ function collectImports(ast: Program): string[] {
148
+ const imports: string[] = [];
149
+ for (const item of ast.body) {
150
+ if (item.kind === "ImportDeclaration") {
151
+ imports.push(extractStringLiteralValue(item.source));
152
+ }
153
+ }
154
+ return imports;
155
+ }
156
+
157
+ function collectTopLevelDeclarations(ast: Program): TopLevelDeclEntry[] {
158
+ const entries: TopLevelDeclEntry[] = [];
159
+ for (const item of ast.body) {
160
+ if (item.kind === "ExportDeclaration") {
161
+ entries.push({ exported: true, decl: item.declaration });
162
+ } else if (
163
+ item.kind === "SchemaDeclaration" ||
164
+ item.kind === "ErrorDeclaration" ||
165
+ item.kind === "ServiceDeclaration" ||
166
+ item.kind === "BindingDeclaration"
167
+ ) {
168
+ entries.push({ exported: false, decl: item });
169
+ }
170
+ }
171
+ return entries;
172
+ }
173
+
174
+ function collectBindingTargetLocations(
175
+ target: BindingTarget | Pattern,
176
+ ): Array<{ name: string; span: Span }> {
177
+ switch (target.kind) {
178
+ case "Identifier":
179
+ case "UpperIdentifier":
180
+ return [{ name: target.name, span: target.span }];
181
+ case "VariablePattern":
182
+ return [{ name: target.name.name, span: target.name.span }];
183
+ case "RestPattern":
184
+ return collectBindingTargetLocations(target.argument);
185
+ case "RecordPattern":
186
+ return target.fields.flatMap((field) =>
187
+ field.pattern
188
+ ? collectBindingTargetLocations(field.pattern)
189
+ : [{ name: field.key.name, span: field.key.span }],
190
+ );
191
+ case "ArrayPattern":
192
+ return target.elements.flatMap((elem) =>
193
+ collectBindingTargetLocations(elem),
194
+ );
195
+ case "OrPattern":
196
+ return target.patterns.flatMap((part) =>
197
+ collectBindingTargetLocations(part),
198
+ );
199
+ case "WildcardPattern":
200
+ case "LiteralPattern":
201
+ case "ConstructorPattern":
202
+ return [];
203
+ }
204
+ }
205
+
206
+ function isEffectType(type: ts.Type, checker: ts.TypeChecker): boolean {
207
+ const symbol = type.symbol ?? type.aliasSymbol;
208
+ if (!symbol || symbol.getName() !== "Effect") {
209
+ return false;
210
+ }
211
+ const typeArgs = checker.getTypeArguments(type as ts.TypeReference);
212
+ if (typeArgs.length !== 3) {
213
+ return false;
214
+ }
215
+ const decls = symbol.declarations;
216
+ if (!decls || decls.length === 0) {
217
+ return true;
218
+ }
219
+ return decls.some((d) => {
220
+ const fileName = d.getSourceFile().fileName;
221
+ return fileName.includes("effect") || Boolean(type.getProperty("pipe"));
222
+ });
223
+ }
224
+
225
+ function collectUnionMembers(
226
+ type: ts.Type,
227
+ checker: ts.TypeChecker,
228
+ enclosingNode?: ts.Node,
229
+ ): string[] {
230
+ const out: string[] = [];
231
+ const seen = new Set<string>();
232
+
233
+ const visit = (t: ts.Type): void => {
234
+ if ((t.flags & ts.TypeFlags.Never) !== 0) {
235
+ return;
236
+ }
237
+ if (t.isUnion()) {
238
+ for (const member of t.types) {
239
+ visit(member);
240
+ }
241
+ return;
242
+ }
243
+ const formatted = formatType(checker, t, enclosingNode);
244
+ if (formatted === "never" || seen.has(formatted)) {
245
+ return;
246
+ }
247
+ seen.add(formatted);
248
+ out.push(formatted);
249
+ };
250
+
251
+ visit(type);
252
+ return out;
253
+ }
254
+
255
+ function decomposeEffectType(
256
+ type: ts.Type,
257
+ checker: ts.TypeChecker,
258
+ enclosingNode?: ts.Node,
259
+ ): EffectChannelInfo | undefined {
260
+ if (isEffectType(type, checker)) {
261
+ const [successType, errorType, reqType] = checker.getTypeArguments(
262
+ type as ts.TypeReference,
263
+ );
264
+ return {
265
+ success: successType
266
+ ? formatType(checker, successType, enclosingNode)
267
+ : "unknown",
268
+ error: errorType
269
+ ? formatType(checker, errorType, enclosingNode)
270
+ : "never",
271
+ requirements: reqType
272
+ ? collectUnionMembers(reqType, checker, enclosingNode)
273
+ : [],
274
+ };
275
+ }
276
+
277
+ const callSignatures = type.getCallSignatures();
278
+ if (callSignatures.length > 0 && type.getConstructSignatures().length === 0) {
279
+ const returnType = callSignatures[0].getReturnType();
280
+ if (isEffectType(returnType, checker)) {
281
+ return decomposeEffectType(returnType, checker, enclosingNode);
282
+ }
283
+ }
284
+
285
+ return undefined;
286
+ }
287
+
288
+ function collectBindingNamesFromTsNode(
289
+ nameNode: ts.BindingName,
290
+ decl: ts.VariableDeclaration,
291
+ variables: Map<string, ts.VariableDeclaration>,
292
+ ): void {
293
+ if (ts.isIdentifier(nameNode)) {
294
+ variables.set(nameNode.text, decl);
295
+ return;
296
+ }
297
+ for (const element of nameNode.elements) {
298
+ if (ts.isBindingElement(element)) {
299
+ collectBindingNamesFromTsNode(element.name, decl, variables);
300
+ }
301
+ }
302
+ }
303
+
304
+ function findTopLevelDeclarationsInTs(sourceFile: ts.SourceFile): {
305
+ variables: Map<string, ts.VariableDeclaration>;
306
+ typeAliases: Map<string, ts.TypeAliasDeclaration>;
307
+ classes: Map<string, ts.ClassDeclaration>;
308
+ } {
309
+ const variables = new Map<string, ts.VariableDeclaration>();
310
+ const typeAliases = new Map<string, ts.TypeAliasDeclaration>();
311
+ const classes = new Map<string, ts.ClassDeclaration>();
312
+
313
+ for (const stmt of sourceFile.statements) {
314
+ if (ts.isVariableStatement(stmt)) {
315
+ for (const decl of stmt.declarationList.declarations) {
316
+ collectBindingNamesFromTsNode(decl.name, decl, variables);
317
+ }
318
+ } else if (ts.isTypeAliasDeclaration(stmt)) {
319
+ typeAliases.set(stmt.name.text, stmt);
320
+ } else if (ts.isClassDeclaration(stmt) && stmt.name) {
321
+ classes.set(stmt.name.text, stmt);
322
+ }
323
+ }
324
+
325
+ return { variables, typeAliases, classes };
326
+ }
327
+
328
+ function resolveSchemaSymbol(
329
+ entry: TopLevelDeclEntry & { decl: SchemaDeclaration },
330
+ funPath: string,
331
+ checker: ts.TypeChecker,
332
+ tsDecls: ReturnType<typeof findTopLevelDeclarationsInTs>,
333
+ ): QueriedSymbol {
334
+ const name = entry.decl.id.name;
335
+ const kind: QueriedSymbolKind =
336
+ entry.decl.body.kind === "TypeSignatureSchema" ? "type" : "schema";
337
+
338
+ const typeAlias = tsDecls.typeAliases.get(name);
339
+ const varDecl = tsDecls.variables.get(name);
340
+ const node: ts.Node | undefined = typeAlias ?? varDecl;
341
+
342
+ let resolvedType: ts.Type | undefined;
343
+ if (typeAlias) {
344
+ resolvedType =
345
+ kind === "type"
346
+ ? checker.getTypeFromTypeNode(typeAlias.type)
347
+ : checker.getTypeAtLocation(typeAlias);
348
+ } else if (varDecl) {
349
+ resolvedType = checker.getTypeAtLocation(varDecl);
350
+ }
351
+
352
+ let typeStr = resolvedType
353
+ ? formatType(checker, resolvedType, node)
354
+ : "unknown";
355
+ const effect =
356
+ resolvedType && kind === "type"
357
+ ? decomposeEffectType(resolvedType, checker, node)
358
+ : undefined;
359
+
360
+ if (kind === "type" && resolvedType && typeStr === name) {
361
+ if (effect) {
362
+ const reqs =
363
+ effect.requirements.length > 0
364
+ ? effect.requirements.join(" | ")
365
+ : "never";
366
+ typeStr = `Effect<${effect.success}, ${effect.error}, ${reqs}>`;
367
+ } else if (
368
+ resolvedType.getCallSignatures().length > 0 &&
369
+ resolvedType.getConstructSignatures().length === 0
370
+ ) {
371
+ typeStr = cleanTypeString(
372
+ checker.signatureToString(
373
+ resolvedType.getCallSignatures()[0],
374
+ node,
375
+ ts.TypeFormatFlags.NoTruncation |
376
+ ts.TypeFormatFlags.WriteArrowStyleSignature,
377
+ ),
378
+ );
379
+ } else if (typeAlias) {
380
+ typeStr = cleanTypeString(typeAlias.type.getText());
381
+ }
382
+ }
383
+
384
+ return {
385
+ name,
386
+ kind,
387
+ exported: entry.exported,
388
+ file: funPath,
389
+ line: entry.decl.id.span.start.line,
390
+ column: entry.decl.id.span.start.column,
391
+ type: typeStr,
392
+ ...(effect ? { effect } : {}),
393
+ };
394
+ }
395
+
396
+ function resolveErrorSymbol(
397
+ entry: TopLevelDeclEntry & { decl: ErrorDeclaration },
398
+ funPath: string,
399
+ checker: ts.TypeChecker,
400
+ tsDecls: ReturnType<typeof findTopLevelDeclarationsInTs>,
401
+ ): QueriedSymbol {
402
+ const name = entry.decl.id.name;
403
+ const classDecl = tsDecls.classes.get(`${name}$Class`);
404
+ const typeAlias = tsDecls.typeAliases.get(name);
405
+
406
+ let typeStr = name;
407
+ if (classDecl) {
408
+ const classType = checker.getTypeAtLocation(classDecl);
409
+ const baseTypes = classType.getBaseTypes();
410
+ if (baseTypes && baseTypes.length > 0) {
411
+ typeStr = formatType(checker, baseTypes[0], classDecl);
412
+ } else {
413
+ typeStr = formatType(checker, classType, classDecl);
414
+ }
415
+ } else if (typeAlias) {
416
+ const aliasType = checker.getTypeAtLocation(typeAlias);
417
+ typeStr = formatType(checker, aliasType, typeAlias);
418
+ }
419
+
420
+ return {
421
+ name,
422
+ kind: "error",
423
+ exported: entry.exported,
424
+ file: funPath,
425
+ line: entry.decl.id.span.start.line,
426
+ column: entry.decl.id.span.start.column,
427
+ type: typeStr,
428
+ };
429
+ }
430
+
431
+ function resolveServiceSymbol(
432
+ entry: TopLevelDeclEntry & { decl: ServiceDeclaration },
433
+ funPath: string,
434
+ checker: ts.TypeChecker,
435
+ tsDecls: ReturnType<typeof findTopLevelDeclarationsInTs>,
436
+ ): QueriedSymbol {
437
+ const name = entry.decl.id.name;
438
+ const classDecl = tsDecls.classes.get(name);
439
+
440
+ let typeStr = name;
441
+ if (classDecl) {
442
+ const classType = checker.getTypeAtLocation(classDecl);
443
+ const baseTypes = classType.getBaseTypes();
444
+ if (baseTypes && baseTypes.length > 0) {
445
+ const shapeArgs = checker.getTypeArguments(
446
+ baseTypes[0] as ts.TypeReference,
447
+ );
448
+ if (shapeArgs.length >= 2) {
449
+ typeStr = formatType(checker, shapeArgs[1], classDecl);
450
+ } else {
451
+ typeStr = formatType(checker, baseTypes[0], classDecl);
452
+ }
453
+ } else {
454
+ typeStr = formatType(checker, classType, classDecl);
455
+ }
456
+ }
457
+
458
+ return {
459
+ name,
460
+ kind: "service",
461
+ exported: entry.exported,
462
+ file: funPath,
463
+ line: entry.decl.id.span.start.line,
464
+ column: entry.decl.id.span.start.column,
465
+ type: typeStr,
466
+ };
467
+ }
468
+
469
+ function resolveBindingSymbols(
470
+ entry: TopLevelDeclEntry & { decl: BindingDeclaration },
471
+ funPath: string,
472
+ checker: ts.TypeChecker,
473
+ tsDecls: ReturnType<typeof findTopLevelDeclarationsInTs>,
474
+ ): QueriedSymbol[] {
475
+ const targets = collectBindingTargetLocations(entry.decl.id);
476
+ const isSimpleTarget =
477
+ entry.decl.id.kind === "Identifier" ||
478
+ entry.decl.id.kind === "UpperIdentifier";
479
+
480
+ return targets.map(({ name, span }) => {
481
+ const varDecl = tsDecls.variables.get(name);
482
+ let resolvedType: ts.Type | undefined;
483
+ if (varDecl) {
484
+ if (ts.isIdentifier(varDecl.name)) {
485
+ resolvedType = checker.getTypeAtLocation(varDecl);
486
+ } else {
487
+ const symbol = checker.getSymbolsInScope(
488
+ varDecl,
489
+ ts.SymbolFlags.BlockScopedVariable,
490
+ );
491
+ const match = symbol.find((sym) => sym.getName() === name);
492
+ if (match) {
493
+ resolvedType = checker.getTypeOfSymbolAtLocation(match, varDecl);
494
+ }
495
+ }
496
+ }
497
+
498
+ const isFuncFromAst =
499
+ isSimpleTarget &&
500
+ (entry.decl.init.kind === "FunctionExpression" ||
501
+ entry.decl.typeAnnotation?.kind === "FunctionTypeNode");
502
+ const isFuncFromTs =
503
+ resolvedType !== undefined &&
504
+ !isEffectType(resolvedType, checker) &&
505
+ resolvedType.getCallSignatures().length > 0 &&
506
+ resolvedType.getConstructSignatures().length === 0;
507
+
508
+ const kind: QueriedSymbolKind =
509
+ isFuncFromAst || isFuncFromTs ? "function" : "binding";
510
+
511
+ const typeStr = resolvedType
512
+ ? formatType(checker, resolvedType, varDecl)
513
+ : "unknown";
514
+ const effect = resolvedType
515
+ ? decomposeEffectType(resolvedType, checker, varDecl)
516
+ : undefined;
517
+
518
+ return {
519
+ name,
520
+ kind,
521
+ exported: entry.exported,
522
+ file: funPath,
523
+ line: span.start.line,
524
+ column: span.start.column,
525
+ type: typeStr,
526
+ ...(effect ? { effect } : {}),
527
+ };
528
+ });
529
+ }
530
+
531
+ function collectAstTypedHoles(ast: Program): TypedHole[] {
532
+ const holes: TypedHole[] = [];
533
+ const visited = new Set<unknown>();
534
+
535
+ const walk = (node: unknown): void => {
536
+ if (!node || typeof node !== "object") return;
537
+ if (visited.has(node)) return;
538
+ visited.add(node);
539
+
540
+ if (Array.isArray(node)) {
541
+ for (const item of node) walk(item);
542
+ return;
543
+ }
544
+
545
+ const record = node as Record<string, unknown>;
546
+ if (record.kind === "TypedHole") {
547
+ holes.push(record as unknown as TypedHole);
548
+ return;
549
+ }
550
+
551
+ for (const [key, value] of Object.entries(record)) {
552
+ if (key === "span") continue;
553
+ walk(value);
554
+ }
555
+ };
556
+
557
+ walk(ast);
558
+ return holes;
559
+ }
560
+
561
+ function extractTypedHoleCallMessage(node: ts.Node): string | undefined {
562
+ if (!ts.isCallExpression(node) || node.arguments.length !== 0) {
563
+ return undefined;
564
+ }
565
+ if (!ts.isParenthesizedExpression(node.expression)) {
566
+ return undefined;
567
+ }
568
+ const arrow = node.expression.expression;
569
+ if (!ts.isArrowFunction(arrow) || arrow.parameters.length !== 0) {
570
+ return undefined;
571
+ }
572
+ if (!ts.isBlock(arrow.body) || arrow.body.statements.length !== 1) {
573
+ return undefined;
574
+ }
575
+ const stmt = arrow.body.statements[0];
576
+ if (!ts.isThrowStatement(stmt) || !stmt.expression) {
577
+ return undefined;
578
+ }
579
+ if (!ts.isNewExpression(stmt.expression)) {
580
+ return undefined;
581
+ }
582
+ const ctor = stmt.expression.expression;
583
+ if (!ts.isIdentifier(ctor) || ctor.text !== "Error") {
584
+ return undefined;
585
+ }
586
+ const args = stmt.expression.arguments;
587
+ if (!args || args.length !== 1 || !ts.isStringLiteral(args[0])) {
588
+ return undefined;
589
+ }
590
+ const prefix = "Typed hole reached: ";
591
+ if (!args[0].text.startsWith(prefix)) {
592
+ return undefined;
593
+ }
594
+ return args[0].text.slice(prefix.length);
595
+ }
596
+
597
+ function collectTsHoleCalls(sourceFile: ts.SourceFile): TsHoleMatch[] {
598
+ const matches: TsHoleMatch[] = [];
599
+
600
+ const visit = (node: ts.Node): void => {
601
+ const rawMessage = extractTypedHoleCallMessage(node);
602
+ if (rawMessage !== undefined) {
603
+ matches.push({ call: node as ts.CallExpression, rawMessage });
604
+ return;
605
+ }
606
+ ts.forEachChild(node, visit);
607
+ };
608
+
609
+ visit(sourceFile);
610
+ return matches;
611
+ }
612
+
613
+ function findEnclosingOuterFunctionReturnType(
614
+ node: ts.Node,
615
+ checker: ts.TypeChecker,
616
+ ): ts.Type | undefined {
617
+ let cur: ts.Node | undefined = node.parent;
618
+ while (cur) {
619
+ if (ts.isFunctionLike(cur) && cur.type) {
620
+ return checker.getTypeFromTypeNode(cur.type);
621
+ }
622
+ if (ts.isVariableDeclaration(cur) && cur.type) {
623
+ return checker.getTypeFromTypeNode(cur.type);
624
+ }
625
+ cur = cur.parent;
626
+ }
627
+ return undefined;
628
+ }
629
+
630
+ function unwrapEffectSuccessFromOuterCall(
631
+ effectCall: ts.CallExpression,
632
+ checker: ts.TypeChecker,
633
+ ): ts.Type | undefined {
634
+ let outerCall: ts.CallExpression = effectCall;
635
+ if (
636
+ ts.isCallExpression(outerCall.parent) &&
637
+ outerCall.parent.expression.getText().endsWith("Effect.scoped")
638
+ ) {
639
+ outerCall = outerCall.parent;
640
+ }
641
+
642
+ const contextual = checker.getContextualType(outerCall);
643
+ const candidate =
644
+ contextual ?? findEnclosingOuterFunctionReturnType(outerCall, checker);
645
+ if (candidate && isEffectType(candidate, checker)) {
646
+ const args = checker.getTypeArguments(candidate as ts.TypeReference);
647
+ return args[0];
648
+ }
649
+ return undefined;
650
+ }
651
+
652
+ function unwrapEffectSuccessIfReturnInEffectGen(
653
+ holeCall: ts.CallExpression,
654
+ checker: ts.TypeChecker,
655
+ ): ts.Type | undefined {
656
+ if (ts.isArrowFunction(holeCall.parent)) {
657
+ const parentCall = holeCall.parent.parent;
658
+ if (
659
+ ts.isCallExpression(parentCall) &&
660
+ parentCall.expression.getText().endsWith("Effect.map")
661
+ ) {
662
+ return unwrapEffectSuccessFromOuterCall(parentCall, checker);
663
+ }
664
+ }
665
+
666
+ if (!ts.isReturnStatement(holeCall.parent)) {
667
+ return undefined;
668
+ }
669
+ let genFn: ts.Node | undefined = holeCall.parent.parent;
670
+ while (genFn && !ts.isFunctionLike(genFn)) {
671
+ genFn = genFn.parent;
672
+ }
673
+ if (!genFn || !ts.isCallExpression(genFn.parent)) {
674
+ return undefined;
675
+ }
676
+ const effectCall = genFn.parent;
677
+ const calleeText = effectCall.expression.getText();
678
+ if (
679
+ !calleeText.endsWith("Effect.gen") &&
680
+ calleeText !== "gen" &&
681
+ !calleeText.endsWith("Effect.map")
682
+ ) {
683
+ return undefined;
684
+ }
685
+
686
+ return unwrapEffectSuccessFromOuterCall(effectCall, checker);
687
+ }
688
+
689
+ function unwrapMatchChainExpectedType(
690
+ holeCall: ts.CallExpression,
691
+ checker: ts.TypeChecker,
692
+ ): ts.Type | undefined {
693
+ if (!ts.isArrowFunction(holeCall.parent)) {
694
+ return undefined;
695
+ }
696
+ const armArrow = holeCall.parent;
697
+ if (!ts.isCallExpression(armArrow.parent)) {
698
+ return undefined;
699
+ }
700
+ let chainCall: ts.CallExpression = armArrow.parent;
701
+ while (
702
+ ts.isPropertyAccessExpression(chainCall.parent) &&
703
+ ts.isCallExpression(chainCall.parent.parent)
704
+ ) {
705
+ chainCall = chainCall.parent.parent;
706
+ }
707
+
708
+ const chainCtx = checker.getContextualType(chainCall);
709
+ if (chainCtx && (chainCtx.flags & ts.TypeFlags.Never) === 0) {
710
+ return chainCtx;
711
+ }
712
+ if (ts.isReturnStatement(chainCall.parent)) {
713
+ return findEnclosingOuterFunctionReturnType(chainCall, checker);
714
+ }
715
+ return undefined;
716
+ }
717
+
718
+ function resolveHoleExpectedType(
719
+ holeCall: ts.CallExpression,
720
+ checker: ts.TypeChecker,
721
+ ): string | undefined {
722
+ const contextual = checker.getContextualType(holeCall);
723
+ if (contextual && (contextual.flags & ts.TypeFlags.Never) === 0) {
724
+ return formatType(checker, contextual, holeCall);
725
+ }
726
+
727
+ const effectSuccess = unwrapEffectSuccessIfReturnInEffectGen(
728
+ holeCall,
729
+ checker,
730
+ );
731
+ if (effectSuccess && (effectSuccess.flags & ts.TypeFlags.Never) === 0) {
732
+ return formatType(checker, effectSuccess, holeCall);
733
+ }
734
+
735
+ const matchType = unwrapMatchChainExpectedType(holeCall, checker);
736
+ if (matchType && (matchType.flags & ts.TypeFlags.Never) === 0) {
737
+ return formatType(checker, matchType, holeCall);
738
+ }
739
+
740
+ return undefined;
741
+ }
742
+
743
+ function resolveFileHoles(
744
+ ast: Program,
745
+ funPath: string,
746
+ sourceFile: ts.SourceFile,
747
+ checker: ts.TypeChecker,
748
+ ): QueriedHole[] {
749
+ const astHoles = collectAstTypedHoles(ast);
750
+ if (astHoles.length === 0) {
751
+ return [];
752
+ }
753
+
754
+ const tsHoles = collectTsHoleCalls(sourceFile);
755
+ const usedTsIndices = new Set<number>();
756
+ const queriedHoles: QueriedHole[] = [];
757
+
758
+ for (const astHole of astHoles) {
759
+ const targetMsg = astHole.label || "???";
760
+ let matchedIdx = tsHoles.findIndex(
761
+ (h, idx) => !usedTsIndices.has(idx) && h.rawMessage === targetMsg,
762
+ );
763
+ if (matchedIdx === -1) {
764
+ matchedIdx = tsHoles.findIndex((_, idx) => !usedTsIndices.has(idx));
765
+ }
766
+
767
+ let expectedType: string | undefined;
768
+ if (matchedIdx !== -1) {
769
+ usedTsIndices.add(matchedIdx);
770
+ expectedType = resolveHoleExpectedType(tsHoles[matchedIdx].call, checker);
771
+ }
772
+
773
+ queriedHoles.push({
774
+ file: funPath,
775
+ line: astHole.span.start.line,
776
+ column: astHole.span.start.column,
777
+ ...(astHole.label !== undefined ? { message: astHole.label } : {}),
778
+ ...(expectedType !== undefined ? { expectedType } : {}),
779
+ });
780
+ }
781
+
782
+ return queriedHoles;
783
+ }
784
+
785
+ function inspectCompiledFile(
786
+ compiled: CompiledVirtualFile,
787
+ program: ts.Program,
788
+ checker: ts.TypeChecker,
789
+ symbolFilter?: string,
790
+ ): FileQueryReport {
791
+ const sourceFile = program.getSourceFile(compiled.virtualTsPath);
792
+ const imports = collectImports(compiled.ast);
793
+ const declEntries = collectTopLevelDeclarations(compiled.ast);
794
+
795
+ let symbols: QueriedSymbol[] = [];
796
+ let holes: QueriedHole[] = [];
797
+
798
+ if (sourceFile) {
799
+ const tsDecls = findTopLevelDeclarationsInTs(sourceFile);
800
+ for (const entry of declEntries) {
801
+ switch (entry.decl.kind) {
802
+ case "SchemaDeclaration":
803
+ symbols.push(
804
+ resolveSchemaSymbol(
805
+ entry as TopLevelDeclEntry & { decl: SchemaDeclaration },
806
+ compiled.funPath,
807
+ checker,
808
+ tsDecls,
809
+ ),
810
+ );
811
+ break;
812
+ case "ErrorDeclaration":
813
+ symbols.push(
814
+ resolveErrorSymbol(
815
+ entry as TopLevelDeclEntry & { decl: ErrorDeclaration },
816
+ compiled.funPath,
817
+ checker,
818
+ tsDecls,
819
+ ),
820
+ );
821
+ break;
822
+ case "ServiceDeclaration":
823
+ symbols.push(
824
+ resolveServiceSymbol(
825
+ entry as TopLevelDeclEntry & { decl: ServiceDeclaration },
826
+ compiled.funPath,
827
+ checker,
828
+ tsDecls,
829
+ ),
830
+ );
831
+ break;
832
+ case "BindingDeclaration":
833
+ symbols.push(
834
+ ...resolveBindingSymbols(
835
+ entry as TopLevelDeclEntry & { decl: BindingDeclaration },
836
+ compiled.funPath,
837
+ checker,
838
+ tsDecls,
839
+ ),
840
+ );
841
+ break;
842
+ }
843
+ }
844
+
845
+ holes = resolveFileHoles(
846
+ compiled.ast,
847
+ compiled.funPath,
848
+ sourceFile,
849
+ checker,
850
+ );
851
+ }
852
+
853
+ if (symbolFilter) {
854
+ symbols = symbols.filter((s) => s.name === symbolFilter);
855
+ }
856
+
857
+ return {
858
+ file: compiled.funPath,
859
+ imports,
860
+ symbols,
861
+ holes,
862
+ };
863
+ }
864
+
865
+ /**
866
+ * Queries semantic type, Effect channel, and typed-hole information for virtual FunkScript files.
867
+ */
868
+ export const queryVirtualFiles = (
869
+ virtualInputFiles: Record<string, string>,
870
+ options?: QueryOptions,
871
+ ): Effect.Effect<QueryReport, Error> =>
872
+ Effect.tryPromise({
873
+ try: async () => {
874
+ const cwd = options?.cwd ? path.resolve(options.cwd) : process.cwd();
875
+ const compilerOptions = getCompilerOptions(cwd);
876
+
877
+ const virtualTsFiles = new Map<string, string>();
878
+ const compiledFiles: CompiledVirtualFile[] = [];
879
+ const virtualSources = new Map(
880
+ Object.entries(virtualInputFiles).map(([file, content]) => [
881
+ path.resolve(cwd, file),
882
+ content,
883
+ ]),
884
+ );
885
+
886
+ for (const [filePath, source] of Object.entries(virtualInputFiles)) {
887
+ const fullFunPath = path.isAbsolute(filePath)
888
+ ? path.normalize(filePath)
889
+ : path.normalize(path.join(cwd, filePath));
890
+ const virtualTsPath = toVirtualTsPath(fullFunPath);
891
+
892
+ let compiled;
893
+ try {
894
+ compiled = await Effect.runPromise(
895
+ compileString(source, filePath, {
896
+ sourcemap: false,
897
+ allowHoles: true,
898
+ preserveFunImports: true,
899
+ sourcePath: fullFunPath,
900
+ virtualSources,
901
+ }),
902
+ );
903
+ } catch (err: unknown) {
904
+ const compErr =
905
+ err instanceof CompilerError
906
+ ? err
907
+ : new CompilerError(
908
+ toErrorMessage(err),
909
+ err instanceof Error ? err : new Error(toErrorMessage(err)),
910
+ );
911
+ throw new Error(
912
+ `Failed to compile '${filePath}': ${compErr.message}`,
913
+ );
914
+ }
915
+
916
+ virtualTsFiles.set(virtualTsPath, compiled.typescript);
917
+ compiledFiles.push({
918
+ funPath: filePath,
919
+ virtualTsPath,
920
+ ast: compiled.ast,
921
+ typescript: compiled.typescript,
922
+ });
923
+ }
924
+
925
+ const hasTsx = Array.from(virtualTsFiles.keys()).some((fileName) =>
926
+ fileName.endsWith(".tsx"),
927
+ );
928
+ const hasJsxIntrinsicTypes = Array.from(virtualTsFiles.values()).some(
929
+ (src) => /namespace\s+JSX[\s\S]*?IntrinsicElements/.test(src),
930
+ );
931
+ if (hasTsx && !hasJsxIntrinsicTypes) {
932
+ const jsxTypesPath = path.join(
933
+ cwd,
934
+ "__funscript_jsx_intrinsics__.d.ts",
935
+ );
936
+ virtualTsFiles.set(jsxTypesPath, JSX_INTRINSICS_DECLARATION);
937
+ }
938
+
939
+ virtualTsFiles.set(
940
+ path.join(cwd, "__funscript_ts_reset__.d.ts"),
941
+ TS_RESET_DECLARATION,
942
+ );
943
+ virtualTsFiles.set(
944
+ path.join(cwd, "__funscript_type_fest__.d.ts"),
945
+ TYPE_FEST_DECLARATION,
946
+ );
947
+
948
+ const files: FileQueryReport[] = [];
949
+
950
+ if (compiledFiles.length > 0) {
951
+ const defaultHost = ts.createCompilerHost(compilerOptions);
952
+
953
+ const resolveVirtualContent = (
954
+ fileName: string,
955
+ ): string | undefined => {
956
+ const norm = path.normalize(fileName);
957
+ const direct = virtualTsFiles.get(norm);
958
+ if (direct !== undefined) return direct;
959
+ if (virtualTsFiles.has(norm + ".ts"))
960
+ return virtualTsFiles.get(norm + ".ts");
961
+ if (virtualTsFiles.has(norm + ".tsx"))
962
+ return virtualTsFiles.get(norm + ".tsx");
963
+ if (
964
+ norm.endsWith(".js") &&
965
+ virtualTsFiles.has(norm.slice(0, -3) + ".ts")
966
+ ) {
967
+ return virtualTsFiles.get(norm.slice(0, -3) + ".ts");
968
+ }
969
+ if (
970
+ norm.endsWith(".jsx") &&
971
+ virtualTsFiles.has(norm.slice(0, -4) + ".tsx")
972
+ ) {
973
+ return virtualTsFiles.get(norm.slice(0, -4) + ".tsx");
974
+ }
975
+ if (path.basename(fileName) === "__funscript_type_fest__.d.ts") {
976
+ return TYPE_FEST_DECLARATION;
977
+ }
978
+ if (path.basename(fileName) === "__funscript_ts_reset__.d.ts") {
979
+ return TS_RESET_DECLARATION;
980
+ }
981
+ if (path.basename(fileName) === "__funscript_jsx_intrinsics__.d.ts") {
982
+ return JSX_INTRINSICS_DECLARATION;
983
+ }
984
+ return undefined;
985
+ };
986
+
987
+ const host: ts.CompilerHost = {
988
+ ...defaultHost,
989
+ getSourceFile: (
990
+ fileName,
991
+ languageVersion,
992
+ onError,
993
+ shouldCreateNewSourceFile,
994
+ ) => {
995
+ const content = resolveVirtualContent(fileName);
996
+ if (content !== undefined) {
997
+ return ts.createSourceFile(
998
+ fileName,
999
+ content,
1000
+ languageVersion,
1001
+ true,
1002
+ );
1003
+ }
1004
+ return defaultHost.getSourceFile(
1005
+ fileName,
1006
+ languageVersion,
1007
+ onError,
1008
+ shouldCreateNewSourceFile,
1009
+ );
1010
+ },
1011
+ fileExists: (fileName) => {
1012
+ if (resolveVirtualContent(fileName) !== undefined) return true;
1013
+ return defaultHost.fileExists(fileName);
1014
+ },
1015
+ readFile: (fileName) => {
1016
+ const content = resolveVirtualContent(fileName);
1017
+ if (content !== undefined) return content;
1018
+ return defaultHost.readFile(fileName);
1019
+ },
1020
+ writeFile: () => {},
1021
+ };
1022
+
1023
+ host.resolveModuleNames = (names, containingFile) =>
1024
+ names.map((name) => {
1025
+ if (/^\.{1,2}\//.test(name)) {
1026
+ if (name.endsWith(".js")) {
1027
+ const regular = ts.resolveModuleName(
1028
+ name,
1029
+ containingFile,
1030
+ compilerOptions,
1031
+ defaultHost,
1032
+ ).resolvedModule;
1033
+ if (regular) return regular;
1034
+ }
1035
+ const source = resolveFunModule(
1036
+ containingFile,
1037
+ name,
1038
+ (file) =>
1039
+ /\.funx?$/.test(file) &&
1040
+ virtualTsFiles.has(
1041
+ file + (file.endsWith(".funx") ? ".tsx" : ".ts"),
1042
+ ),
1043
+ { directories: true },
1044
+ );
1045
+ if (source) {
1046
+ return {
1047
+ resolvedFileName:
1048
+ source + (source.endsWith(".funx") ? ".tsx" : ".ts"),
1049
+ extension: source.endsWith(".funx")
1050
+ ? ts.Extension.Tsx
1051
+ : ts.Extension.Ts,
1052
+ };
1053
+ }
1054
+ if (/\.funx?$/.test(name)) return undefined;
1055
+ }
1056
+ return ts.resolveModuleName(
1057
+ name,
1058
+ containingFile,
1059
+ compilerOptions,
1060
+ host,
1061
+ ).resolvedModule;
1062
+ });
1063
+
1064
+ const program = ts.createProgram({
1065
+ rootNames: Array.from(virtualTsFiles.keys()),
1066
+ options: compilerOptions,
1067
+ host,
1068
+ });
1069
+ const checker = program.getTypeChecker();
1070
+
1071
+ for (const compiled of compiledFiles) {
1072
+ files.push(
1073
+ inspectCompiledFile(compiled, program, checker, options?.symbol),
1074
+ );
1075
+ }
1076
+ }
1077
+
1078
+ return {
1079
+ schemaVersion: 1 as const,
1080
+ files,
1081
+ };
1082
+ },
1083
+ catch: (error: unknown) =>
1084
+ error instanceof Error
1085
+ ? error
1086
+ : new Error(`Query failed: ${toErrorMessage(error)}`),
1087
+ });
1088
+
1089
+ /**
1090
+ * Reads FunkScript files from disk and queries their semantic information.
1091
+ */
1092
+ export const queryFiles = (
1093
+ files: string[],
1094
+ options?: QueryOptions,
1095
+ ): Effect.Effect<QueryReport, Error> =>
1096
+ Effect.gen(function* () {
1097
+ const cwd = options?.cwd ? path.resolve(options.cwd) : process.cwd();
1098
+ const virtualFiles: Record<string, string> = {};
1099
+
1100
+ for (const filePath of files) {
1101
+ const fullPath = path.isAbsolute(filePath)
1102
+ ? filePath
1103
+ : path.resolve(cwd, filePath);
1104
+ const content = yield* Effect.tryPromise({
1105
+ try: () => fs.readFile(fullPath, "utf-8"),
1106
+ catch: (err: unknown) =>
1107
+ new Error(
1108
+ `Failed to read file '${filePath}': ${toErrorMessage(err)}`,
1109
+ ),
1110
+ });
1111
+ virtualFiles[filePath] = content;
1112
+ }
1113
+
1114
+ return yield* queryVirtualFiles(virtualFiles, options);
1115
+ });
1116
+
1117
+ /**
1118
+ * Formats a QueryReport as JSON or human-readable semantic inspection output.
1119
+ */
1120
+ export function formatQueryReport(
1121
+ report: QueryReport,
1122
+ options?: { json?: boolean },
1123
+ ): string {
1124
+ if (options?.json) {
1125
+ return JSON.stringify(report, null, 2);
1126
+ }
1127
+
1128
+ if (report.files.length === 0) {
1129
+ return "No files queried.";
1130
+ }
1131
+
1132
+ const sections: string[] = [];
1133
+
1134
+ for (const fileReport of report.files) {
1135
+ const lines: string[] = [`File: ${fileReport.file}`];
1136
+
1137
+ if (fileReport.imports.length > 0) {
1138
+ lines.push(` Imports: ${fileReport.imports.join(", ")}`);
1139
+ }
1140
+
1141
+ if (fileReport.symbols.length === 0) {
1142
+ lines.push(" Symbols: (none)");
1143
+ } else {
1144
+ lines.push(` Symbols (${fileReport.symbols.length}):`);
1145
+ for (const sym of fileReport.symbols) {
1146
+ const exp = sym.exported ? "export " : "";
1147
+ lines.push(
1148
+ ` ${exp}${sym.kind} ${sym.name}: ${sym.type} (${sym.file}:${sym.line}:${sym.column})`,
1149
+ );
1150
+ if (sym.effect) {
1151
+ const reqs =
1152
+ sym.effect.requirements.length > 0
1153
+ ? sym.effect.requirements.join(" | ")
1154
+ : "never";
1155
+ lines.push(
1156
+ ` effect: success=${sym.effect.success}, error=${sym.effect.error}, requirements=${reqs}`,
1157
+ );
1158
+ }
1159
+ }
1160
+ }
1161
+
1162
+ if (fileReport.holes.length > 0) {
1163
+ lines.push(` Holes (${fileReport.holes.length}):`);
1164
+ for (const hole of fileReport.holes) {
1165
+ const label = hole.message ? ` "${hole.message}"` : "";
1166
+ const expected = hole.expectedType ?? "unknown";
1167
+ lines.push(
1168
+ ` ???${label} -> expected ${expected} (${hole.file}:${hole.line}:${hole.column})`,
1169
+ );
1170
+ }
1171
+ }
1172
+
1173
+ sections.push(lines.join("\n"));
1174
+ }
1175
+
1176
+ return sections.join("\n\n");
1177
+ }