vitest-pool-assemblyscript 0.5.1 → 0.6.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.
Files changed (66) hide show
  1. package/README.md +162 -37
  2. package/binding.gyp +6 -6
  3. package/dist/{compiler-CBBHCPAU.mjs → addon-interface-_pNXcbib.mjs} +8 -138
  4. package/dist/addon-interface-_pNXcbib.mjs.map +1 -0
  5. package/dist/{compile-runner-DrDjhdPG.mjs → compile-runner-DOMhsLQE.mjs} +3 -3
  6. package/dist/{compile-runner-DrDjhdPG.mjs.map → compile-runner-DOMhsLQE.mjs.map} +1 -1
  7. package/dist/compiler/transforms/strip-inline.mjs +1 -2
  8. package/dist/compiler/transforms/strip-inline.mjs.map +1 -1
  9. package/dist/compiler-CIXpfKq0.mjs +147 -0
  10. package/dist/compiler-CIXpfKq0.mjs.map +1 -0
  11. package/dist/config/index-v3.d.mts +2 -2
  12. package/dist/config/index.d.mts +3 -3
  13. package/dist/config/index.mjs +2 -2
  14. package/dist/coverage-provider/index.mjs +5 -5
  15. package/dist/coverage-provider/index.mjs.map +1 -1
  16. package/dist/{custom-provider-options-39YrzdqD.d.mts → custom-provider-options-BZg2Trd5.d.mts} +2 -2
  17. package/dist/{custom-provider-options-39YrzdqD.d.mts.map → custom-provider-options-BZg2Trd5.d.mts.map} +1 -1
  18. package/dist/feature-check-ELxw_Mji.mjs +82 -0
  19. package/dist/feature-check-ELxw_Mji.mjs.map +1 -0
  20. package/dist/index-internal.d.mts +1 -1
  21. package/dist/index-internal.d.mts.map +1 -1
  22. package/dist/index-internal.mjs +2 -1
  23. package/dist/index-v3.mjs +12 -9
  24. package/dist/index-v3.mjs.map +1 -1
  25. package/dist/index.d.mts +2 -2
  26. package/dist/index.mjs +2 -2
  27. package/dist/{load-user-imports-BIQvqM7K.mjs → load-user-imports-B3Iy_K8k.mjs} +2 -3
  28. package/dist/{load-user-imports-BIQvqM7K.mjs.map → load-user-imports-B3Iy_K8k.mjs.map} +1 -1
  29. package/dist/{pool-runner-init-D8Ei957C.mjs → pool-runner-init-BDQtAGwQ.mjs} +3 -3
  30. package/dist/pool-runner-init-BDQtAGwQ.mjs.map +1 -0
  31. package/dist/{pool-runner-init-DVk4hB5d.d.mts → pool-runner-init-BLvrW28n.d.mts} +2 -2
  32. package/dist/pool-runner-init-BLvrW28n.d.mts.map +1 -0
  33. package/dist/pool-thread/compile-worker-thread.d.mts +3 -3
  34. package/dist/pool-thread/compile-worker-thread.d.mts.map +1 -1
  35. package/dist/pool-thread/compile-worker-thread.mjs +7 -7
  36. package/dist/pool-thread/compile-worker-thread.mjs.map +1 -1
  37. package/dist/pool-thread/test-worker-thread.d.mts +1 -1
  38. package/dist/pool-thread/test-worker-thread.mjs +4 -4
  39. package/dist/pool-thread/test-worker-thread.mjs.map +1 -1
  40. package/dist/pool-thread/v3-tinypool-thread.d.mts +1 -1
  41. package/dist/pool-thread/v3-tinypool-thread.mjs +6 -6
  42. package/dist/pool-thread/v3-tinypool-thread.mjs.map +1 -1
  43. package/dist/{resolve-config-BFNr7LW7.mjs → resolve-config-DhZ4lOSK.mjs} +17 -12
  44. package/dist/resolve-config-DhZ4lOSK.mjs.map +1 -0
  45. package/dist/{test-runner-DNGLk7lx.mjs → test-runner-WF857_Bk.mjs} +2 -2
  46. package/dist/{test-runner-DNGLk7lx.mjs.map → test-runner-WF857_Bk.mjs.map} +1 -1
  47. package/dist/{types-6ta3lLJM.d.mts → types-CnJC7Ydg.d.mts} +2 -1
  48. package/dist/types-CnJC7Ydg.d.mts.map +1 -0
  49. package/package.json +52 -24
  50. package/prebuilds/darwin-arm64/vitest-pool-assemblyscript.glibc.node +0 -0
  51. package/prebuilds/darwin-x64/vitest-pool-assemblyscript.glibc.node +0 -0
  52. package/prebuilds/linux-arm64/vitest-pool-assemblyscript.glibc.node +0 -0
  53. package/prebuilds/linux-x64/vitest-pool-assemblyscript.glibc.node +0 -0
  54. package/prebuilds/linux-x64/vitest-pool-assemblyscript.musl.node +0 -0
  55. package/prebuilds/win32-arm64/vitest-pool-assemblyscript.glibc.node +0 -0
  56. package/prebuilds/win32-x64/vitest-pool-assemblyscript.glibc.node +0 -0
  57. package/scripts/install-native-addon.js +138 -0
  58. package/src/{native-instrumentation → instrumentation/native}/addon.cpp +8 -8
  59. package/dist/compiler-CBBHCPAU.mjs.map +0 -1
  60. package/dist/node-check-CcKfvjM4.mjs +0 -16
  61. package/dist/node-check-CcKfvjM4.mjs.map +0 -1
  62. package/dist/pool-runner-init-D8Ei957C.mjs.map +0 -1
  63. package/dist/pool-runner-init-DVk4hB5d.d.mts.map +0 -1
  64. package/dist/resolve-config-BFNr7LW7.mjs.map +0 -1
  65. package/dist/types-6ta3lLJM.d.mts.map +0 -1
  66. package/scripts/install.js +0 -91
@@ -1 +1 @@
1
- {"version":3,"file":"strip-inline.mjs","names":[],"sources":["../../../src/compiler/transforms/strip-inline.mts"],"sourcesContent":["/**\n * AssemblyScript Transform to strip @inline decorators\n *\n * Production code uses @inline decorators for performance. When functions are inlined,\n * coverage instrumentation can't track their execution. This transform removes @inline\n * decorators from the AST during test compilation, allowing coverage instrumentation\n * to properly track function calls.\n * \n * - Hooks into the AssemblyScript compiler's `afterParse` lifecycle\n * - Walks through all parsed source files before compilation begins\n * - Uses shared ASTVisitor to recurse into ALL node types\n * - Strips @inline decorators from any node that has them in user code\n *\n * @see https://www.assemblyscript.org/compiler.html#transforms\n * @see https://github.com/AssemblyScript/assemblyscript/blob/main/src/ast.ts\n */\n\nimport { Node, Parser, Source, DecoratorNode } from 'assemblyscript';\nimport { Transform } from 'assemblyscript/transform';\n\nimport { ASTVisitor } from '../../util/ast-visitor.js';\nimport {\n ASSEMBLYSCRIPT_LIB_PREFIX,\n ASDecoratorKind,\n ASSourceKind,\n} from '../../types/constants.js';\n\n/**\n * Visitor that strips @inline decorators from nodes\n */\nclass StripInlineVisitor extends ASTVisitor {\n /**\n * Strip @inline decorator from a node if present\n */\n protected beforeVisit(node: Node): void {\n if ('decorators' in node && node.decorators) {\n const filtered = (node.decorators as DecoratorNode[]).filter(\n (decorator: DecoratorNode) => decorator.decoratorKind !== ASDecoratorKind.Inline\n );\n node.decorators = filtered.length > 0 ? filtered : null;\n }\n }\n}\n\n/**\n * AssemblyScript compiler transform that strips @inline decorators\n */\nclass StripInlineTransform extends Transform {\n private visitor = new StripInlineVisitor();\n\n /**\n * Called after parsing is complete, before the program is initialized.\n * This is the ideal time to modify the AST.\n */\n afterParse(_parser: Parser): void {\n const sources = (this as Transform).program.sources;\n\n // Filter to user source files only\n const userSources = sources.filter((source: Source) =>\n (source.sourceKind === ASSourceKind.User || source.sourceKind === ASSourceKind.UserEntry)\n && !source.normalizedPath.startsWith(ASSEMBLYSCRIPT_LIB_PREFIX)\n );\n\n for (const source of userSources) {\n this.visitor.visitSource(source);\n }\n }\n}\n\nexport default StripInlineTransform;\n"],"mappings":";;;;;;;;AA8BA,IAAM,qBAAN,cAAiC,WAAW;;;;CAI1C,AAAU,YAAY,MAAkB;AACtC,MAAI,gBAAgB,QAAQ,KAAK,YAAY;GAC3C,MAAM,WAAY,KAAK,WAA+B,QACnD,cAA6B,UAAU,kBAAkB,gBAAgB,OAC3E;AACD,QAAK,aAAa,SAAS,SAAS,IAAI,WAAW;;;;;;;AAQzD,IAAM,uBAAN,cAAmC,UAAU;CAC3C,AAAQ,UAAU,IAAI,oBAAoB;;;;;CAM1C,WAAW,SAAuB;EAIhC,MAAM,cAHW,KAAmB,QAAQ,QAGhB,QAAQ,YACjC,OAAO,eAAe,aAAa,QAAQ,OAAO,eAAe,aAAa,cAC5E,CAAC,OAAO,eAAe,mBAAqC,CAChE;AAED,OAAK,MAAM,UAAU,YACnB,MAAK,QAAQ,YAAY,OAAO;;;AAKtC,2BAAe"}
1
+ {"version":3,"file":"strip-inline.mjs","names":[],"sources":["../../../src/compiler/transforms/strip-inline.mts"],"sourcesContent":["/**\n * AssemblyScript Transform to strip @inline decorators\n *\n * Production code uses @inline decorators for performance. When functions are inlined,\n * coverage instrumentation can't track their execution. This transform removes @inline\n * decorators from the AST during test compilation, allowing coverage instrumentation\n * to properly track function calls.\n * \n * - Hooks into the AssemblyScript compiler's `afterParse` lifecycle\n * - Walks through all parsed source files before compilation begins\n * - Uses shared ASTVisitor to recurse into ALL node types\n * - Strips @inline decorators from any node that has them in user code\n *\n * @see https://www.assemblyscript.org/compiler.html#transforms\n * @see https://github.com/AssemblyScript/assemblyscript/blob/main/src/ast.ts\n */\n\nimport { Node, Parser, Source, DecoratorNode } from 'assemblyscript';\nimport { Transform } from 'assemblyscript/transform';\n\nimport { ASTVisitor } from '../../util/ast-visitor.js';\nimport {\n ASSEMBLYSCRIPT_LIB_PREFIX,\n ASDecoratorKind,\n ASSourceKind,\n} from '../../types/constants.js';\n\n/**\n * Visitor that strips @inline decorators from nodes\n */\nclass StripInlineVisitor extends ASTVisitor {\n /**\n * Strip @inline decorator from a node if present\n */\n protected beforeVisit(node: Node): void {\n if ('decorators' in node && node.decorators) {\n const filtered = (node.decorators as DecoratorNode[]).filter(\n (decorator: DecoratorNode) => decorator.decoratorKind !== ASDecoratorKind.Inline\n );\n node.decorators = filtered.length > 0 ? filtered : null;\n }\n }\n}\n\n/**\n * AssemblyScript compiler transform that strips @inline decorators\n */\nclass StripInlineTransform extends Transform {\n private visitor = new StripInlineVisitor();\n\n /**\n * Called after parsing is complete, before the program is initialized.\n * This is the ideal time to modify the AST.\n */\n afterParse(_parser: Parser): void {\n const sources = (this as Transform).program.sources;\n\n // Filter to user source files only\n const userSources = sources.filter((source: Source) =>\n (source.sourceKind === ASSourceKind.User || source.sourceKind === ASSourceKind.UserEntry)\n && !source.normalizedPath.startsWith(ASSEMBLYSCRIPT_LIB_PREFIX)\n );\n\n for (const source of userSources) {\n this.visitor.visitSource(source);\n }\n }\n}\n\nexport default StripInlineTransform;\n"],"mappings":";;;;;;;;AA8BA,IAAM,qBAAN,cAAiC,WAAW;;;;CAI1C,AAAU,YAAY,MAAkB;AACtC,MAAI,gBAAgB,QAAQ,KAAK,YAAY;GAC3C,MAAM,WAAY,KAAK,WAA+B,QACnD,cAA6B,UAAU,kBAAkB,gBAAgB,OAC3E;AACD,QAAK,aAAa,SAAS,SAAS,IAAI,WAAW;;;;;;;AAQzD,IAAM,uBAAN,cAAmC,UAAU;CAC3C,AAAQ,UAAU,IAAI,oBAAoB;;;;;CAM1C,WAAW,SAAuB;EAIhC,MAAM,cAHW,KAAmB,QAAQ,QAGhB,QAAQ,YACjC,OAAO,eAAe,aAAa,QAAQ,OAAO,eAAe,aAAa,cAC5E,CAAC,OAAO,eAAe,mBAAqC,CAChE;AAED,OAAK,MAAM,UAAU,YACnB,MAAK,QAAQ,YAAY,OAAO"}
@@ -0,0 +1,147 @@
1
+ import { POOL_ERROR_NAMES } from "./constants-DuBLuMjt.mjs";
2
+ import { createPoolError, debug, throwPoolErrorIfAborted } from "./debug-Cm1VFmaz.mjs";
3
+ import { clearNativeBuildError, hasNativeBuildError, warnASInstrumentationNotLoaded } from "./feature-check-ELxw_Mji.mjs";
4
+ import { basename, resolve } from "node:path";
5
+ import { access, readFile } from "node:fs/promises";
6
+ import { main } from "assemblyscript/asc";
7
+
8
+ //#region src/compiler/index.ts
9
+ /**
10
+ * AssemblyScript Compiler
11
+ *
12
+ * Handles compilation of AssemblyScript source code to WASM binaries.
13
+ * Manages compiler options, transforms, and in-memory compilation.
14
+ */
15
+ let nativeAddon;
16
+ try {
17
+ nativeAddon = await import("./addon-interface-_pNXcbib.mjs");
18
+ clearNativeBuildError();
19
+ } catch (err) {
20
+ if (await hasNativeBuildError()) debug(`[Compiler] Native instrumentation addon not loaded (known build failure): ${err?.message ?? String(err)}`);
21
+ else warnASInstrumentationNotLoaded(err?.message ?? String(err));
22
+ }
23
+ const POOL_ASSEMBLY_NODE_MODULES_PREFIX = "node_modules/vitest-pool-assemblyscript/assembly/";
24
+ const STRIP_INLINE_TRANSFORM = resolve(import.meta.dirname, "./compiler/transforms/strip-inline.mjs");
25
+ setImmediate(async () => {
26
+ try {
27
+ await access(STRIP_INLINE_TRANSFORM);
28
+ } catch {
29
+ throw createPoolError(`AS Compiler strip inline transform file not found at "${STRIP_INLINE_TRANSFORM}"`, POOL_ERROR_NAMES.CompilationError);
30
+ }
31
+ });
32
+ /**
33
+ * Compile AssemblyScript source code to WASM binary
34
+ */
35
+ async function compileAssemblyScript(filename, options, logModule, logLabel, signal) {
36
+ throwPoolErrorIfAborted(signal);
37
+ const compileStart = performance.now();
38
+ const logPrefix = `[${logModule} ASC] ${logLabel}`;
39
+ const { shouldInstrument, instrumentationOptions, extraFlags } = options;
40
+ if (shouldInstrument && !instrumentationOptions) throw createPoolError("Instrumentation options are required for coverage instrumentation", POOL_ERROR_NAMES.CompilationError);
41
+ const stdoutLines = [];
42
+ const stderrLines = [];
43
+ let binary;
44
+ let sourceMap;
45
+ const entryFile = filename;
46
+ const outputFile = "output.wasm";
47
+ debug(`${logPrefix} - Compiling: "${filename}"`);
48
+ const stdout = { write: (text) => {
49
+ stdoutLines.push(text);
50
+ return true;
51
+ } };
52
+ const stderr = { write: (text) => {
53
+ stderrLines.push(text);
54
+ return true;
55
+ } };
56
+ const compilerFlags = [
57
+ entryFile,
58
+ "--optimizeLevel",
59
+ "0",
60
+ "--shrinkLevel",
61
+ "0",
62
+ "--runtime",
63
+ "stub",
64
+ ...extraFlags || [],
65
+ "--outFile",
66
+ outputFile,
67
+ "--importMemory",
68
+ "--debug",
69
+ "--sourceMap",
70
+ "--exportStart",
71
+ "_start",
72
+ "--exportTable"
73
+ ];
74
+ if (options.stripInline === true) {
75
+ compilerFlags.push("--transform", STRIP_INLINE_TRANSFORM);
76
+ debug(`${logPrefix} - Added Transform - Stripping @inline decorators`);
77
+ }
78
+ const ascStart = performance.now();
79
+ const result = await main(compilerFlags, {
80
+ stdout,
81
+ stderr,
82
+ writeFile: (name, contents, _baseDir) => {
83
+ throwPoolErrorIfAborted(signal);
84
+ if (name.endsWith(".wasm") && contents instanceof Uint8Array) {
85
+ binary = contents;
86
+ debug(`${logPrefix} - Captured binary in memory: "${name}"`);
87
+ } else if (name.endsWith(".wasm.map") && typeof contents === "string") {
88
+ debug(`${logPrefix} - Captured source map in memory: "${name}"`);
89
+ sourceMap = contents;
90
+ } else debug(`${logPrefix} - WARNING - Captured Unexpected File: "${name}" at baseDir: "${_baseDir}"`);
91
+ },
92
+ readFile: async (filename, baseDir) => {
93
+ const filePath = resolve(baseDir, filename);
94
+ try {
95
+ return await readFile(filePath, { encoding: "utf-8" });
96
+ } catch {
97
+ if (filename.startsWith(POOL_ASSEMBLY_NODE_MODULES_PREFIX)) {
98
+ const localPath = resolve(baseDir, "assembly", filename.substring(49));
99
+ try {
100
+ return await readFile(localPath, { encoding: "utf-8" });
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
105
+ return null;
106
+ }
107
+ }
108
+ });
109
+ debug(`${logPrefix} - TIMING asc.main: ${(performance.now() - ascStart).toFixed(2)} ms`);
110
+ if (result.error) {
111
+ const errorMessage = stderrLines.length > 0 ? `${result.error.message}\n\n${stderrLines.join("")}` : result.error.message;
112
+ throw createPoolError(errorMessage, POOL_ERROR_NAMES.CompilationError, errorMessage);
113
+ }
114
+ if (!binary) throw createPoolError(stderrLines.length > 0 ? `No WASM binary was generated\n\nAS Compiler output:\n${stderrLines.join("")}` : "No WASM binary was generated", POOL_ERROR_NAMES.CompilationError);
115
+ if (!sourceMap) throw createPoolError("Source map not captured from AssemblyScript Compiler", POOL_ERROR_NAMES.CompilationError);
116
+ const cleanBinary = binary;
117
+ const wasmSourceMap = sourceMap;
118
+ debug(`${logPrefix} - Compilation successful, clean binary size: ${cleanBinary.length} bytes`);
119
+ debug(`${logPrefix} - Source map generated, size: ${wasmSourceMap.length * 2} bytes`);
120
+ if (options.shouldInstrument && nativeAddon) {
121
+ throwPoolErrorIfAborted(signal);
122
+ const instrumentStart = performance.now();
123
+ const wasmBuffer = Buffer.from(cleanBinary);
124
+ const sourceMapBuffer = Buffer.from(wasmSourceMap);
125
+ const instrumentResult = nativeAddon.instrumentForCoverage(wasmBuffer, sourceMapBuffer, options.instrumentationOptions, logModule, logLabel);
126
+ const instCount = instrumentResult.debugInfo.instrumentedFunctionCount;
127
+ const instrumentEnd = performance.now();
128
+ debug(`${logPrefix} - TIMING Instrumented ${instCount} functions: ${(performance.now() - instrumentStart).toFixed(2)} ms`);
129
+ return {
130
+ binary: instrumentResult.instrumentedWasm,
131
+ sourceMap: instrumentResult.sourceMap,
132
+ debugInfo: instrumentResult.debugInfo,
133
+ isInstrumented: true,
134
+ compileTiming: instrumentEnd - compileStart
135
+ };
136
+ }
137
+ return {
138
+ binary: cleanBinary,
139
+ sourceMap: wasmSourceMap,
140
+ isInstrumented: false,
141
+ compileTiming: performance.now() - compileStart
142
+ };
143
+ }
144
+
145
+ //#endregion
146
+ export { compileAssemblyScript };
147
+ //# sourceMappingURL=compiler-CIXpfKq0.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compiler-CIXpfKq0.mjs","names":["ascMain"],"sources":["../src/compiler/index.ts"],"sourcesContent":["/**\n * AssemblyScript Compiler\n *\n * Handles compilation of AssemblyScript source code to WASM binaries.\n * Manages compiler options, transforms, and in-memory compilation.\n */\n\nimport { main as ascMain } from 'assemblyscript/asc';\nimport { basename, resolve } from 'node:path';\nimport { access, readFile, writeFile, mkdir } from 'node:fs/promises';\n\nimport type {\n AssemblyScriptCompilerResult,\n AssemblyScriptCompilerOptions,\n NativeAddonInterface\n} from '../types/types.js';\nimport { POOL_ERROR_NAMES } from '../types/constants.js';\nimport { debug } from '../util/debug.js';\nimport { createPoolError, throwPoolErrorIfAborted } from '../util/pool-errors.js';\nimport { clearNativeBuildError, hasNativeBuildError, warnASInstrumentationNotLoaded } from '../util/feature-check.js';\n\nlet nativeAddon: NativeAddonInterface | undefined;\ntry {\n nativeAddon = await import('../instrumentation/addon-interface.js');\n // Addon loaded successfully — clear any stale build error marker (fire and forget)\n clearNativeBuildError();\n} catch (err: any) {\n const knownBuildFailure = await hasNativeBuildError();\n if (knownBuildFailure) {\n // Marker file exists — coverage provider will warn the user, just debug log here\n debug(`[Compiler] Native instrumentation addon not loaded (known build failure): ${err?.message ?? String(err)}`);\n } else {\n // Unexpected failure — no marker file, warn the user\n warnASInstrumentationNotLoaded(err?.message ?? String(err));\n }\n}\n\nconst DEBUG_WRITE_FILES = false;\n\n// Path prefix the AS compiler uses when resolving bare `vitest-pool-assemblyscript/assembly` imports\n// via node_modules. Used to detect self-imports and redirect to local assembly/ dir when running in-tree.\nconst POOL_ASSEMBLY_NODE_MODULES_PREFIX = 'node_modules/vitest-pool-assemblyscript/assembly/';\n\n// path assumes that we're running from dist/\nconst STRIP_INLINE_TRANSFORM = resolve(import.meta.dirname, './compiler/transforms/strip-inline.mjs');\n\nsetImmediate(async () => {\n try {\n await access(STRIP_INLINE_TRANSFORM);\n } catch {\n throw createPoolError(\n `AS Compiler strip inline transform file not found at \"${STRIP_INLINE_TRANSFORM}\"`,\n POOL_ERROR_NAMES.CompilationError\n );\n }\n});\n\n/**\n * Compile AssemblyScript source code to WASM binary\n */\nexport async function compileAssemblyScript(\n filename: string,\n options: AssemblyScriptCompilerOptions,\n logModule: string,\n logLabel: string,\n signal?: AbortSignal\n): Promise<AssemblyScriptCompilerResult> {\n throwPoolErrorIfAborted(signal);\n\n const compileStart = performance.now();\n const logPrefix = `[${logModule} ASC] ${logLabel}`;\n\n const { shouldInstrument, instrumentationOptions, extraFlags } = options;\n\n if (shouldInstrument && !instrumentationOptions) {\n throw createPoolError(\n 'Instrumentation options are required for coverage instrumentation',\n POOL_ERROR_NAMES.CompilationError\n );\n }\n\n const stdoutLines: string[] = [];\n const stderrLines: string[] = [];\n let binary: Uint8Array | undefined;\n let sourceMap: string | undefined;\n\n // Use full path as entry file so AS compiler can resolve relative imports\n const entryFile = filename;\n // Use simple output name to avoid AS compiler prepending it to source map paths\n const outputFile = 'output.wasm';\n\n debug(`${logPrefix} - Compiling: \"${filename}\"`);\n\n // Capture stdout/stderr (for potential error reporting)\n const stdout = {\n write: (text: string) => {\n stdoutLines.push(text);\n return true;\n }\n };\n\n const stderr = {\n write: (text: string) => {\n stderrLines.push(text);\n return true;\n }\n };\n\n // Build compiler flags\n const compilerFlags = [\n entryFile,\n\n // overrideable, though not recommended\n '--optimizeLevel', '0', // No optimization for easier debugging\n '--shrinkLevel', '0', // No shrink\n '--runtime', 'stub', // stub runtime (no GC)\n\n ...(extraFlags || []),\n\n // non-overrideable\n '--outFile', outputFile,\n '--importMemory', // Import memory from JS (enables imports during WASM start)\n '--debug', // Include debug info\n '--sourceMap', // Generate source maps for error reporting\n '--exportStart', '_start', // Export start function for explicit initialization control\n '--exportTable' // Export function table for direct test execution\n ];\n\n // Add transform to strip @inline decorators if requested\n // This improves coverage accuracy by preventing functions from being inlined,\n // and enables correct source-mapped error reporting for errors originating\n // inside inlined functions.\n if (options.stripInline === true) {\n compilerFlags.push(\n '--transform', STRIP_INLINE_TRANSFORM\n );\n debug(`${logPrefix} - Added Transform - Stripping @inline decorators`);\n }\n\n // Compile with AssemblyScript compiler\n const ascStart = performance.now();\n const result = await ascMain(compilerFlags, {\n stdout,\n stderr,\n // Let AS read from filesystem for import resolution\n // WASM binary and source map are captured in memory via writeFile callback\n writeFile: (name: string, contents: string | Uint8Array, _baseDir: string) => {\n throwPoolErrorIfAborted(signal);\n\n if (name.endsWith('.wasm') && contents instanceof Uint8Array) {\n binary = contents;\n debug(`${logPrefix} - Captured binary in memory: \"${name}\"`);\n } else if (name.endsWith('.wasm.map') && typeof contents === 'string') {\n debug(`${logPrefix} - Captured source map in memory: \"${name}\"`);\n sourceMap = contents;\n } else {\n debug(`${logPrefix} - WARNING - Captured Unexpected File: \"${name}\" at baseDir: \"${_baseDir}\"`);\n }\n },\n \n // Custom readFile enables in-tree resolution of bare pool assembly imports.\n // When a test file imports 'vitest-pool-assemblyscript/assembly', the AS compiler\n // resolves it to a node_modules path. This works when the package is installed,\n // but fails in-tree (the package isn't in its own node_modules). The fallback\n // redirects these to the local assembly/ directory when the normal path isn't found.\n readFile: async (filename, baseDir): Promise<string | null> => {\n const filePath = resolve(baseDir, filename);\n\n try {\n return await readFile(filePath, { encoding: 'utf-8' });\n } catch {\n // Fallback: when running in-tree, redirect pool assembly imports to local assembly/ dir\n if (filename.startsWith(POOL_ASSEMBLY_NODE_MODULES_PREFIX)) {\n const localSubpath = filename.substring(POOL_ASSEMBLY_NODE_MODULES_PREFIX.length);\n const localPath = resolve(baseDir, 'assembly', localSubpath);\n\n try {\n return await readFile(localPath, { encoding: 'utf-8' });\n } catch {\n return null;\n }\n }\n\n return null;\n }\n },\n });\n\n debug(`${logPrefix} - TIMING asc.main: ${(performance.now() - ascStart).toFixed(2)} ms`);\n\n if (result.error) {\n const errorMessage = stderrLines.length > 0\n ? `${result.error.message}\\n\\n${stderrLines.join('')}`\n : result.error.message;\n\n throw createPoolError(errorMessage, POOL_ERROR_NAMES.CompilationError, errorMessage);\n }\n\n if (!binary) {\n const errorMessage = stderrLines.length > 0\n ? `No WASM binary was generated\\n\\nAS Compiler output:\\n${stderrLines.join('')}`\n : 'No WASM binary was generated';\n\n throw createPoolError(errorMessage, POOL_ERROR_NAMES.CompilationError);\n }\n\n if (!sourceMap) {\n throw createPoolError('Source map not captured from AssemblyScript Compiler', POOL_ERROR_NAMES.CompilationError);\n }\n\n const cleanBinary: Uint8Array = binary;\n const wasmSourceMap: string = sourceMap;\n\n debug(`${logPrefix} - Compilation successful, clean binary size: ${cleanBinary.length} bytes`);\n debug(`${logPrefix} - Source map generated, size: ${wasmSourceMap.length * 2} bytes`);\n \n if (DEBUG_WRITE_FILES) {\n // Write source map for debugging\n const dir = './debug';\n // TODO - handle non-.ts extensions\n const sourceMapFileName = `${basename(filename, '.ts')}.ts.map`;\n const sourceMapPath = `${dir}/${sourceMapFileName}`;\n\n // Create directory if it doesn't exist\n try {\n await mkdir(dir, { recursive: true });\n } catch {\n // Directory already exists or creation failed, continue\n }\n\n // Format as well-formed JSON\n const formattedSourceMap = JSON.stringify(JSON.parse(wasmSourceMap), null, 2);\n\n writeFile(sourceMapPath, formattedSourceMap, { encoding: 'utf8' });\n debug(`${logPrefix} - Wrote source map to: \"${sourceMapPath}\"`);\n\n // Also write WASM binary for inspection\n const wasmPath = sourceMapPath.replace('.map', '.wasm');\n writeFile(wasmPath, cleanBinary);\n debug(`${logPrefix} - Wrote WASM binary to: \"${wasmPath}\"`);\n }\n\n // Instrument binary for coverage if requested and available\n if (options.shouldInstrument && nativeAddon) {\n throwPoolErrorIfAborted(signal);\n\n const instrumentStart = performance.now();\n const wasmBuffer = Buffer.from(cleanBinary);\n const sourceMapBuffer = Buffer.from(wasmSourceMap);\n\n const instrumentResult = nativeAddon.instrumentForCoverage(wasmBuffer, sourceMapBuffer, options.instrumentationOptions!, logModule, logLabel);\n const instCount = instrumentResult.debugInfo.instrumentedFunctionCount;\n\n const instrumentEnd = performance.now();\n debug(`${logPrefix} - TIMING Instrumented ${instCount} functions: ${(performance.now() - instrumentStart).toFixed(2)} ms`);\n\n return {\n binary: instrumentResult.instrumentedWasm,\n sourceMap: instrumentResult.sourceMap,\n debugInfo: instrumentResult.debugInfo,\n isInstrumented: true,\n compileTiming: instrumentEnd - compileStart,\n };\n }\n\n // No instrumentation requested\n return {\n binary: cleanBinary,\n sourceMap: wasmSourceMap,\n isInstrumented: false,\n compileTiming: performance.now() - compileStart,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAqBA,IAAI;AACJ,IAAI;AACF,eAAc,MAAM,OAAO;AAE3B,wBAAuB;SAChB,KAAU;AAEjB,KAD0B,MAAM,qBAAqB,CAGnD,OAAM,6EAA6E,KAAK,WAAW,OAAO,IAAI,GAAG;KAGjH,gCAA+B,KAAK,WAAW,OAAO,IAAI,CAAC;;AAQ/D,MAAM,oCAAoC;AAG1C,MAAM,yBAAyB,QAAQ,OAAO,KAAK,SAAS,yCAAyC;AAErG,aAAa,YAAY;AACvB,KAAI;AACF,QAAM,OAAO,uBAAuB;SAC9B;AACN,QAAM,gBACJ,yDAA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YAAY,iBAAiB,UAAU;EAE7C,MAAM,gBAAgB,YAAY,KAAK;AACvC,QAAM,GAAG,UAAU,yBAAyB,UAAU,eAAe,YAAY,KAAK,GAAG,iBAAiB,QAAQ,EAAE,CAAC,KAAK;AAE1H,SAAO;GACL,QAAQ,iBAAiB;GACzB,WAAW,iBAAiB;GAC5B,WAAW,iBAAiB;GAC5B,gBAAgB;GAChB,eAAe,gBAAgB;GAChC;;AAIH,QAAO;EACL,QAAQ;EACR,WAAW;EACX,gBAAgB;EAChB,eAAe,YAAY,KAAK,GAAG;EACpC"}
@@ -1,5 +1,5 @@
1
- import { AssemblyScriptPoolOptions, WasmImportsFactory, WasmImportsFactoryInfo } from "../types-6ta3lLJM.mjs";
2
- import "../custom-provider-options-39YrzdqD.mjs";
1
+ import { AssemblyScriptPoolOptions, WasmImportsFactory, WasmImportsFactoryInfo } from "../types-CnJC7Ydg.mjs";
2
+ import "../custom-provider-options-BZg2Trd5.mjs";
3
3
  import { ConfigEnv, UserWorkspaceConfig, ViteUserConfig } from "vitest/config";
4
4
 
5
5
  //#region src/config/config-helpers-v3.d.ts
@@ -1,4 +1,4 @@
1
- import { AssemblyScriptPoolOptions, WasmImportsFactory, WasmImportsFactoryInfo } from "../types-6ta3lLJM.mjs";
2
- import "../custom-provider-options-39YrzdqD.mjs";
3
- import { createAssemblyScriptPool } from "../pool-runner-init-DVk4hB5d.mjs";
1
+ import { AssemblyScriptPoolOptions, WasmImportsFactory, WasmImportsFactoryInfo } from "../types-CnJC7Ydg.mjs";
2
+ import "../custom-provider-options-BZg2Trd5.mjs";
3
+ import { createAssemblyScriptPool } from "../pool-runner-init-BLvrW28n.mjs";
4
4
  export { type AssemblyScriptPoolOptions, type WasmImportsFactory, type WasmImportsFactoryInfo, createAssemblyScriptPool };
@@ -1,9 +1,9 @@
1
1
  import "../constants-DuBLuMjt.mjs";
2
- import "../resolve-config-BFNr7LW7.mjs";
2
+ import "../resolve-config-DhZ4lOSK.mjs";
3
3
  import "../debug-Cm1VFmaz.mjs";
4
4
  import "../vitest-file-tasks-Bn9CrWt_.mjs";
5
5
  import "../vitest-tasks--ow4pacR.mjs";
6
6
  import "../worker-rpc-channel-CZZIxtv5.mjs";
7
- import { createAssemblyScriptPool } from "../pool-runner-init-D8Ei957C.mjs";
7
+ import { createAssemblyScriptPool } from "../pool-runner-init-BDQtAGwQ.mjs";
8
8
 
9
9
  export { createAssemblyScriptPool };
@@ -1,8 +1,8 @@
1
1
  import { ASCommonFlags, ASNodeKind, COVERAGE_PAYLOAD_FORMATS, POOL_ERROR_NAMES } from "../constants-DuBLuMjt.mjs";
2
- import { getProjectSerializedOrGlobalConfig } from "../resolve-config-BFNr7LW7.mjs";
2
+ import { getProjectSerializedOrGlobalConfig } from "../resolve-config-DhZ4lOSK.mjs";
3
3
  import { createPoolError, debug, debugOverride } from "../debug-Cm1VFmaz.mjs";
4
4
  import { toForwardSlash } from "../path-utils-t9OzjXYF.mjs";
5
- import { warnIfASCoverageNotSupported } from "../node-check-CcKfvjM4.mjs";
5
+ import { warnIfASCoverageNotSupportedByNode, warnIfNativeBuildFailed } from "../feature-check-ELxw_Mji.mjs";
6
6
  import { mergeCoverageData } from "../coverage-merge-CBXkpM1O.mjs";
7
7
  import { ASTVisitor } from "../ast-visitor-C5gQqWD2.mjs";
8
8
  import { basename, parse, relative } from "node:path";
@@ -376,7 +376,8 @@ var HybridCoverageProvider = class {
376
376
  await this.v8Provider.initialize(ctx);
377
377
  this.v8Provider.name = "hybrid-assemblyscript-v8 (delegated v8 reporter)";
378
378
  debug("[HybridCoverageProvider] Initialized with delegated v8 provider");
379
- warnIfASCoverageNotSupported();
379
+ warnIfASCoverageNotSupportedByNode();
380
+ await warnIfNativeBuildFailed();
380
381
  }
381
382
  /**
382
383
  * Handle suite completion - delegate based on coverage format marker
@@ -536,8 +537,7 @@ const hybridProviderModule = {
536
537
  else throw createPoolError("HybridCoverageProvider - v8 coverage module does not provide `stopCoverage`", POOL_ERROR_NAMES.HybridCoverageProviderError);
537
538
  }
538
539
  };
539
- var coverage_provider_default = hybridProviderModule;
540
540
 
541
541
  //#endregion
542
- export { coverage_provider_default as default };
542
+ export { hybridProviderModule as default };
543
543
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["parsePath","AssemblyScriptParser"],"sources":["../../src/coverage-provider/containment-matcher.ts","../../src/coverage-provider/istanbul-converter.ts","../../src/coverage-provider/ast-parser.ts","../../src/coverage-provider/glob-utils.ts","../../src/coverage-provider/hybrid-coverage-provider.ts","../../src/coverage-provider/index.ts"],"sourcesContent":["/**\n * Containment Matcher\n *\n * Provides containment-based matching for coverage mapping.\n * Binary debug info provides points (representativeLocation), source parsing provides ranges.\n * We find which source range contains each binary point.\n *\n * Usage by version:\n * - v1: Function containment matching (binary representativeLocation → source function range)\n * - v2: Function containment (same) + statement containment + branch path containment\n *\n * Why containment matching (not direct position lookup):\n * AS compiler generates source map entries differently by statement type:\n * - Variable declarations: source map points to statement start (keyword)\n * - Control flow (if/switch/for): source map points to condition EXPRESSION, not keyword\n *\n * Example: `if (n < 0)` → binary reports column 7 ('n'), not column 3 ('i' of 'if')\n *\n * Containment matching is more robust:\n * - Binary gives us a position (representativeLocation) somewhere in the function\n * - Source gives us function ranges (start/end line/column)\n * - We find which source function range contains the binary position\n * - Handles nested functions with \"tightest fit\" (innermost function wins)\n */\n\nimport type { ParsedSourceFunctionInfo, SourceRange } from '../types/types.js';\n\n/**\n * Functions indexed by file path, then by start line.\n * Multiple functions can start on the same line (e.g., nested arrow functions).\n */\nexport type FunctionsByFileAndStartLine = Record<string, Record<number, ParsedSourceFunctionInfo[]>>;\n\n/**\n * Find the source function whose range contains the given position.\n *\n * For nested functions, uses \"tightest fit\" - returns the innermost function\n * (the one with the largest start position among all containing functions).\n *\n * @param functionsByStartLine - Functions for a single file, indexed by start line\n * @param line - Target line number (1-based)\n * @param column - Target column number (1-based)\n * @returns The containing function, or undefined if no match\n */\nexport function findFunctionContainingPosition(\n functionsByStartLine: Record<number, ParsedSourceFunctionInfo[]>,\n line: number,\n column: number\n): ParsedSourceFunctionInfo | undefined {\n let bestMatch: ParsedSourceFunctionInfo | undefined;\n let bestStartLine = -1;\n let bestStartColumn = -1;\n\n // Check functions starting on lines <= target line\n for (const [startLineStr, functions] of Object.entries(functionsByStartLine)) {\n const startLine = Number(startLineStr);\n if (startLine > line) continue;\n\n for (const func of functions) {\n const { range } = func;\n\n // Check if position is within this function's range\n if (!isPositionInRange(line, column, range)) continue;\n\n // Tightest fit: prefer function with largest start position (innermost)\n if (startLine > bestStartLine ||\n (startLine === bestStartLine && range.startColumn > bestStartColumn)) {\n bestMatch = func;\n bestStartLine = startLine;\n bestStartColumn = range.startColumn;\n }\n }\n }\n\n return bestMatch;\n}\n\n/**\n * Check if a position (line, column) falls within a source range.\n *\n * @param line - Target line number (1-based)\n * @param column - Target column number (1-based)\n * @param range - Source range to check against\n * @returns true if position is within range (inclusive)\n */\nexport function isPositionInRange(\n line: number,\n column: number,\n range: SourceRange\n): boolean {\n // Outside line range entirely\n if (line < range.startLine || line > range.endLine) return false;\n\n // On start line but before start column\n if (line === range.startLine && column < range.startColumn) return false;\n\n // On end line but after end column\n if (line === range.endLine && column > range.endColumn) return false;\n\n return true;\n}\n","/**\n * Istanbul Format Converter\n *\n * Converts AssemblyScript coverage data to Istanbul's FileCoverageData format.\n * This enables integration with Vitest's coverage reporting system and standard\n * coverage tools like Codecov, Coveralls, etc.\n *\n * Current Implementation: Function-level coverage only\n * - Uses containment matching: binary positions → source function ranges\n * - Each function maps to both a function entry AND a statement entry\n * - Statement coverage matches function coverage (function-level granularity)\n * - Branch coverage is 0% (no branches tracked yet)\n * - Line coverage derived from statement coverage\n *\n * Future Enhancement (v2): Block-level statement and branch coverage\n */\n\nimport type { FileCoverageData, Range, FunctionMapping, BranchMapping } from 'istanbul-lib-coverage';\nimport type { ParsedSourceFunctionInfo } from '../types/types.js';\nimport { findFunctionContainingPosition } from './containment-matcher.js';\nimport { debugOverride } from '../util/debug.js';\n\n/**\n * Convert AssemblyScript coverage data to Istanbul format for a single file\n *\n * Algorithm (containment matching):\n * 1. For each hit position in fileHitCountsByPosition:\n * - Use containment matcher to find which source function contains this position\n * - Record the hit count for that function\n * 2. For each function in fileFunctionsByStartLine:\n * - Add function mapping to fnMap\n * - Add function hit count to f (from matched hits, or 0 if not hit)\n * - Add corresponding statement mapping to statementMap\n * - Add same hit count to s (statement coverage matches function coverage)\n *\n * @param fileFunctionsByStartLine - Functions for this file, keyed by start line (from AST parser)\n * @param fileHitCountsByPosition - Hit counts for this file, keyed by position \"line:column\" (from accumulated coverage)\n * @param absoluteFilePath - Absolute path to the source file (for Istanbul output)\n * @returns Istanbul FileCoverage object\n */\nexport async function convertToIstanbulFormat(\n fileFunctionsByStartLine: Record<number, ParsedSourceFunctionInfo[]>,\n fileHitCountsByPosition: Record<string, number>,\n absoluteFilePath: string,\n istanbulDebugEnabled: boolean\n): Promise<FileCoverageData> {\n const startMatch = performance.now();\n\n function istanbulDebug(...args: any[]): void {\n if (istanbulDebugEnabled) {\n debugOverride(...args);\n }\n };\n\n istanbulDebug(() => {\n const sourceFunctionCount = Object.values(fileFunctionsByStartLine).reduce((sum, funcs) => sum + funcs.length, 0);\n const uniqueHitPosCount = Object.keys(fileHitCountsByPosition).length;\n const coverageEstimate = sourceFunctionCount === 0 ? Infinity : ((uniqueHitPosCount * 100) / sourceFunctionCount).toFixed(2);\n\n return `[IstanbulConverter] Processing source file: \"${absoluteFilePath}\"\\n`\n + `[IstanbulConverter] Source: ${sourceFunctionCount} total functions, Coverage: ${uniqueHitPosCount} unique hit positions\\n`\n + `[IstanbulConverter] Sanity Check - AS File Coverage Estimate: ${coverageEstimate}%\\n`\n + `[IstanbulConverter] Containment matching functions: coverage hit positions to source functions by range`;\n });\n\n // Build a map of function → hit count using containment matching\n // Key: function source identity (qualifiedName), Value: hit count\n const hitCountsBySourceFunctionName = new Map<ParsedSourceFunctionInfo, number>();\n\n // For each hit position, find which function contains it\n for (const [positionKey, hitCount] of Object.entries(fileHitCountsByPosition)) {\n // Position key format is \"line:column\"\n const parts = positionKey.split(':');\n const lineStr = parts[0];\n const columnStr = parts[1];\n\n if (lineStr && columnStr) {\n const line = parseInt(lineStr, 10);\n const column = parseInt(columnStr, 10);\n\n const containingFunction = findFunctionContainingPosition(fileFunctionsByStartLine, line, column);\n if (containingFunction) {\n // Accumulate hits (in case multiple positions map to same function)\n const existingHits = hitCountsBySourceFunctionName.get(containingFunction);\n const existingHitsCount = existingHits ?? 0;\n const max = Math.max(existingHitsCount, hitCount);\n hitCountsBySourceFunctionName.set(containingFunction, max); // <-- TODO: Explain this max logic\n\n if (existingHits !== undefined) {\n istanbulDebug(`[IstanbulConverter] Position ${positionKey} → function \"${containingFunction.shortName}\" EXISTING HITS: ${existingHits} NEW COUNT: ${max}`);\n } else {\n istanbulDebug(`[IstanbulConverter] Position ${positionKey} → function \"${containingFunction.shortName}\" (hits: ${hitCount})`);\n }\n } else {\n istanbulDebug(`[IstanbulConverter] Position ${positionKey} has no containing function`);\n }\n }\n }\n\n const startConvert = performance.now();\n istanbulDebug(`[IstanbulConverter] Matching Complete - Converting to Istanbul format`);\n\n // Initialize Istanbul data structures\n const fnMap: { [key: string]: FunctionMapping } = {};\n const f: { [key: string]: number } = {};\n const statementMap: { [key: string]: Range } = {};\n const s: { [key: string]: number } = {};\n const branchMap: { [key: string]: BranchMapping } = {};\n const b: { [key: string]: number[] } = {};\n\n // Convert function coverage to Istanbul format\n // Iterate all functions from parsed source (ensures 0-hit functions are included)\n let funcIdx = 0;\n for (const functions of Object.values(fileFunctionsByStartLine)) {\n for (const funcInfo of functions) {\n const { range, shortName } = funcInfo;\n\n // Defensive: skip functions with invalid metadata (shouldn't happen - AST parser filters these)\n if (range.startLine === 0) {\n continue;\n }\n\n // Get hit count from containment matching (or 0 if not hit)\n const hitCount = hitCountsBySourceFunctionName.get(funcInfo) ?? 0;\n const displayShortName = shortName && shortName !== '' ? shortName : '<anonymous>';\n istanbulDebug(\n `[IstanbulConverter] Istanbul function index ${funcIdx}: \"${displayShortName}\"`\n + ` (source ${range.startLine}:${range.startColumn} - ${range.endLine}:${range.endColumn}), hits: ${hitCount}`\n );\n\n // Create function mapping\n // Both 'decl' (declaration) and 'loc' (location) use the same range\n // Internal ParsedSourceFunctionInfo uses 1-based columns, Istanbul expects 0-based\n const istanbulRange: Range = {\n start: { line: range.startLine, column: range.startColumn - 1 },\n end: { line: range.endLine, column: range.endColumn - 1 }\n };\n\n const idxStr = funcIdx.toString();\n fnMap[idxStr] = {\n name: shortName,\n decl: istanbulRange,\n loc: istanbulRange,\n line: range.startLine\n };\n f[idxStr] = hitCount;\n\n // Create corresponding statement mapping\n // For function-level coverage, each function is one \"statement\"\n // The statement range matches the function range\n // This gives us statement coverage at function granularity\n statementMap[idxStr] = istanbulRange;\n s[idxStr] = hitCount;\n\n funcIdx++;\n }\n }\n\n const done = performance.now();\n const matchingMs = (startConvert - startMatch).toFixed(2);\n const convertMs = (done - startConvert).toFixed(2);\n const totalMs = (done - startMatch).toFixed(2);\n\n istanbulDebug(\n `[IstanbulConverter] Coverage Coversion Complete: ${Object.keys(fnMap).length} functions,` \n + ` ${totalMs} ms total (matching: ${matchingMs} ms, convert: ${convertMs} ms)`\n );\n\n return {\n path: absoluteFilePath,\n fnMap,\n f,\n statementMap,\n s,\n branchMap,\n b\n };\n}\n","/**\n * AST Parser for AssemblyScript Source Files\n *\n * Parses AS source files to extract function metadata for coverage.\n * Used by generateCoverage to build empty coverage map from all source files.\n *\n * Source AST is the source of truth for what SHOULD be covered.\n * Binary instrumentation tells us what we CAN measure (hit counts).\n *\n * Functions are grouped by start line for efficient containment matching.\n *\n * Architecture:\n * - Uses shared ASTVisitor for complete NodeKind coverage\n * - Overrides hooks to extract function information during traversal\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { parse as parsePath } from 'node:path';\nimport {\n Parser as AssemblyScriptParser,\n Source,\n BlockStatement,\n Node,\n FunctionDeclaration,\n MethodDeclaration,\n ClassDeclaration,\n VariableDeclaration,\n FunctionExpression,\n} from 'assemblyscript';\n\nimport type { ParsedSourceFunctionInfo, SourceRange } from '../types/types.js';\nimport { ASCommonFlags, ASNodeKind } from '../types/constants.js';\nimport { ASTVisitor } from '../util/ast-visitor.js';\n\n/**\n * Visitor that extracts function information from AST nodes\n */\nclass FunctionExtractorVisitor extends ASTVisitor {\n /** Source file being parsed */\n private source: Source;\n /** Module path for building qualified names */\n private modulePath: string;\n /** Absolute file path */\n private filePath: string;\n /** Accumulated function records, keyed by start line */\n readonly functions: Record<number, ParsedSourceFunctionInfo[]> = {};\n /** Current class name (when inside a class) */\n private currentClassName: string | null = null;\n\n constructor(source: Source, modulePath: string, filePath: string) {\n super();\n this.source = source;\n this.modulePath = modulePath;\n this.filePath = filePath;\n }\n\n /**\n * Track class context when entering a class\n */\n protected onClassEnter(node: ClassDeclaration): void {\n this.currentClassName = node.name?.text ?? 'Anonymous';\n }\n\n /**\n * Restore class context when exiting a class\n */\n protected onClassExit(_node: ClassDeclaration): void {\n this.currentClassName = null;\n }\n\n /**\n * Extract function info from function declarations\n */\n protected onFunctionDeclaration(node: FunctionDeclaration): boolean {\n if (node.body && this.hasBodyStatements(node.body)) {\n const shortName = node.name?.text ?? '~anonymous';\n const qualifiedName = `${this.modulePath}/${shortName}`;\n const range = this.buildRange(node, node.name ?? null);\n this.addFunction(qualifiedName, shortName, range);\n }\n return true; // Continue recursion into body\n }\n\n /**\n * Extract function info from method declarations\n */\n protected onMethodDeclaration(node: MethodDeclaration): boolean {\n if (node.body && this.hasBodyStatements(node.body)) {\n const methodName = node.name?.text ?? 'constructor';\n const className = this.currentClassName ?? 'Unknown';\n const flags = node.flags;\n\n // Determine method type from flags\n const isStatic = (flags & ASCommonFlags.Static) !== 0;\n const isGetter = (flags & ASCommonFlags.Get) !== 0;\n const isSetter = (flags & ASCommonFlags.Set) !== 0;\n\n // Build short name to match binary naming convention:\n // - Static: ClassName.methodName\n // - Getter: ClassName#get:propertyName\n // - Setter: ClassName#set:propertyName\n // - Instance: ClassName#methodName\n let shortName: string;\n if (isStatic) {\n shortName = `${className}.${methodName}`;\n } else if (isGetter) {\n shortName = `${className}#get:${methodName}`;\n } else if (isSetter) {\n shortName = `${className}#set:${methodName}`;\n } else {\n shortName = `${className}#${methodName}`;\n }\n\n const qualifiedName = `${this.modulePath}/${shortName}`;\n const range = this.buildRange(node, node.name ?? null);\n this.addFunction(qualifiedName, shortName, range);\n }\n return true; // Continue recursion into body\n }\n\n /**\n * Extract function info from variable declarations (arrow functions)\n */\n protected onVariableDeclaration(node: VariableDeclaration): boolean {\n if (node.initializer && node.initializer.kind === ASNodeKind.Function) {\n const funcExpr = node.initializer as FunctionExpression;\n const funcDecl = funcExpr.declaration;\n\n if (funcDecl.body && this.hasBodyStatements(funcDecl.body)) {\n // Use variable name for the function\n const shortName = node.name.text;\n const qualifiedName = `${this.modulePath}/${shortName}`;\n\n // Use the variable declaration's range\n const range: SourceRange = {\n filePath: this.filePath,\n startLine: this.source.lineAt(node.range.start),\n startColumn: this.source.columnAt(),\n endLine: this.source.lineAt(node.range.end),\n endColumn: this.source.columnAt(),\n };\n\n this.addFunction(qualifiedName, shortName, range);\n }\n\n // Visit the function body manually since we're handling this specially\n if (funcDecl.body) {\n this.visitNode(funcDecl.body);\n }\n return false; // Don't recurse again - we handled it\n }\n return true; // Continue recursion for non-function initializers\n }\n\n /**\n * Check if a function body has statements (non-empty body)\n */\n private hasBodyStatements(body: Node): boolean {\n if (body.kind === ASNodeKind.Block) {\n const blockBody = body as BlockStatement;\n return blockBody.statements.length > 0;\n }\n // Expression body (braceless arrow) - always has the expression\n return true;\n }\n\n /**\n * Add a function to the functions record, keyed by start line\n */\n private addFunction(qualifiedName: string, shortName: string, range: SourceRange): void {\n const startLine = range.startLine;\n if (!this.functions[startLine]) {\n this.functions[startLine] = [];\n }\n this.functions[startLine].push({ qualifiedName, shortName, range });\n }\n\n /**\n * Build a SourceRange for a node, using name.range.start to skip decorators\n */\n private buildRange(node: Node, nameNode: Node | null): SourceRange {\n const startNode = nameNode ?? node;\n return {\n filePath: this.filePath,\n startLine: this.source.lineAt(startNode.range.start),\n startColumn: this.source.columnAt(),\n endLine: this.source.lineAt(node.range.end),\n endColumn: this.source.columnAt(),\n };\n }\n}\n\n/**\n * Parse functions from a single AS source file\n *\n * @param absoluteSourceFilePath - Absolute path to AS source file\n * @param relativeSourceFilePath - Relative path to AS source file (derived once in caller and used several places)\n * @returns Record of start line to array of ParsedSourceFunctionInfo (multiple functions can start on same line)\n */\nexport async function parseFunctionsFromFile(\n absoluteSourceFilePath: string,\n relativeSourceFilePath: string,\n): Promise<Record<number, ParsedSourceFunctionInfo[]>> {\n const sourceCode = await readFile(absoluteSourceFilePath, 'utf8');\n\n // Build the module path (strip any extension, use forward slashes)\n const parsed = parsePath(relativeSourceFilePath);\n const modulePath = parsed.dir ? `${parsed.dir}/${parsed.name}` : parsed.name;\n\n // Parse with AssemblyScript parser\n const asParser = new AssemblyScriptParser();\n asParser.parseFile(sourceCode, relativeSourceFilePath, true);\n\n const source = asParser.currentSource;\n if (!source) {\n return {};\n }\n\n // Create visitor and traverse\n const visitor = new FunctionExtractorVisitor(source, modulePath, absoluteSourceFilePath);\n visitor.visitSource(source);\n\n return visitor.functions || {};\n}\n","/**\n * Glob Utilities for Coverage\n *\n * Uses tinyglobby to glob AssemblyScript files matching coverage include/exclude patterns.\n * Supports ../ path traversals for projects that import source from outside the project root.\n *\n * Note: tinyglobby docs warn of a performance cost when globbing outside cwd (e.g. ../ patterns)\n * due to recalculating relative paths. Acceptable here since this runs once at startup.\n */\n\nimport { relative } from 'node:path';\nimport { globSync } from 'tinyglobby';\n\nimport { GlobResult } from '../types/types.js';\nimport { toForwardSlash } from '../util/path-utils.js';\n\nconst NODE_MODULES_GLOB = '**/node_modules/**';\n\n/**\n * Glob files matching coverage include/exclude patterns\n *\n * @param include - Include patterns (e.g., ['assembly/**\\/*.ts'])\n * @param exclude - Exclude patterns (e.g., ['**\\/*.test.ts'])\n * @param projectRoot - Project root directory\n * @returns Array of glob results with absolute and project-root-relative paths\n */\nexport function globFiles(\n include: string[],\n exclude: string[],\n projectRoot: string\n): GlobResult[] {\n if (include.length === 0) {\n return [];\n }\n\n const absolutePaths = globSync(include, {\n cwd: projectRoot,\n ignore: [NODE_MODULES_GLOB, ...exclude],\n absolute: true,\n });\n\n return absolutePaths.map((absolute) => ({\n absolute: toForwardSlash(absolute),\n projectRootRelative: toForwardSlash(relative(projectRoot, absolute)),\n }));\n}\n","/**\n * Hybrid Coverage Provider\n *\n * This provider handles both AssemblyScript and JavaScript and coverage\n * - Converts AS coverage to Istanbul format\n * - Delegates JS coverage to Vitest's v8 provider\n * - Merges both into a unified coverage report\n */\n\nimport { basename, relative } from 'node:path';\nimport type {\n CoverageProvider,\n Vitest,\n ReportContext,\n ResolvedCoverageOptions,\n CustomProviderOptions,\n ResolvedConfig,\n} from 'vitest/node';\nimport type { AfterSuiteRunMeta, SerializedConfig } from 'vitest';\nimport v8CoverageModule from '@vitest/coverage-v8';\nimport type { CoverageMap } from 'istanbul-lib-coverage';\nimport istanbulCoverage from 'istanbul-lib-coverage';\nconst { createCoverageMap } = istanbulCoverage;\n\n// pick up CustomProviderOptions module augmentation\nimport '../config/custom-provider-options.js';\n\nimport { convertToIstanbulFormat } from './istanbul-converter.js';\nimport { parseFunctionsFromFile } from './ast-parser.js';\nimport { globFiles } from './glob-utils.js';\nimport { getProjectSerializedOrGlobalConfig } from '../util/resolve-config.js';\nimport { mergeCoverageData } from './coverage-merge.js';\nimport { debug } from '../util/debug.js';\nimport { createPoolError } from '../util/pool-errors.js';\nimport type {\n AssemblyScriptCoveragePayload,\n CoverageData,\n GlobResult,\n ResolvedHybridProviderOptions,\n} from '../types/types.js';\nimport {\n POOL_ERROR_NAMES,\n COVERAGE_PAYLOAD_FORMATS\n} from '../types/constants.js';\nimport { warnIfASCoverageNotSupported } from '../util/node-check.js';\n\nexport class HybridCoverageProvider implements CoverageProvider {\n name = 'hybrid-assemblyscript-v8' as const;\n\n private v8Provider: CoverageProvider | undefined;\n private accumulatedCoverageData: CoverageData = { hitCountsByFileAndPosition: {} };\n private projectConfig: SerializedConfig | ResolvedConfig = {} as SerializedConfig;\n private coverageOptions: ResolvedHybridProviderOptions = {} as ResolvedHybridProviderOptions;\n\n /**\n * Initialize the provider and get reference to v8 provider\n */\n async initialize(ctx: Vitest): Promise<void> {\n this.projectConfig = getProjectSerializedOrGlobalConfig(ctx).config;\n\n debug('[HybridCoverageProvider] Initializing Provider');\n\n // Get v8 provider from the coverage module\n this.v8Provider = await v8CoverageModule.getProvider();\n\n if (!this.v8Provider) {\n throw createPoolError(\n 'HybridCoverageProvider - initialize failed to get delegated v8 provider',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n\n await this.v8Provider.initialize(ctx);\n this.v8Provider.name = 'hybrid-assemblyscript-v8 (delegated v8 reporter)' as const;\n debug('[HybridCoverageProvider] Initialized with delegated v8 provider');\n\n warnIfASCoverageNotSupported();\n }\n\n /**\n * Handle suite completion - delegate based on coverage format marker\n */\n async onAfterSuiteRun(meta: AfterSuiteRunMeta): Promise<void> {\n const start = performance.now();\n const format: string | undefined = (meta?.coverage as any)?.__format;\n let suiteLogLabel = meta.testFiles.length > 0 ? basename(meta.testFiles[0]!) : '';\n\n // Check for AssemblyScript format marker\n if (format === COVERAGE_PAYLOAD_FORMATS.AssemblyScript) {\n const payload = meta.coverage as AssemblyScriptCoveragePayload;\n const { coverageData, suiteLogLabel: label } = payload;\n suiteLogLabel = label;\n\n debug(() => {\n const fileCount = Object.keys(coverageData.hitCountsByFileAndPosition).length;\n const positionCount = Object.values(coverageData.hitCountsByFileAndPosition)\n .reduce((sum, positions) => sum + Object.keys(positions).length, 0);\n return `[HybridCoverageProvider] ${suiteLogLabel} - onAfterSuiteRun - Suite payload: ${positionCount} unique positions over ${fileCount} source files`;\n });\n\n // Merge incoming coverage data into accumulated (by position, summing hit counts)\n mergeCoverageData(this.accumulatedCoverageData, coverageData);\n\n debug(() => {\n const fileCount = Object.keys(this.accumulatedCoverageData.hitCountsByFileAndPosition).length;\n const positionCount = Object.values(this.accumulatedCoverageData.hitCountsByFileAndPosition)\n .reduce((sum, positions) => sum + Object.keys(positions).length, 0);\n return `[HybridCoverageProvider] ${suiteLogLabel} - onAfterSuiteRun - Accumulated coverage: ${positionCount} unique positions over ${fileCount} source files`;\n });\n } else {\n // Delegate to v8 provider for all other formats (JS, etc.)\n if (!this.v8Provider) {\n throw createPoolError(\n 'HybridCoverageProvider - onAfterSuiteRun failed to delegate to v8 provider',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n\n debug(`[HybridCoverageProvider] ${suiteLogLabel} - Delegating to v8 provider`);\n await this.v8Provider.onAfterSuiteRun(meta);\n }\n\n debug(() => {\n const files = meta.testFiles.map(tf => relative(this.projectConfig.root, tf)).join(',');\n return `[HybridCoverageProvider] ${suiteLogLabel} - onAfterSuiteRun complete - TIMING ${(performance.now() - start).toFixed(2)} ms | testFiles: \"${files}\"`;\n });\n }\n\n /**\n * Generate unified coverage map (merging JS and AS coverage)\n *\n * Flow:\n * 1. Parse included AS source files to get sourceDebugInfo (source of truth for line numbers)\n * 1. Build merged CoverageData (all source functions + accumulated hit counts)\n * 4. Convert merged CoverageData to Istanbul format\n * 5. Get JS coverage from v8 provider\n * 6. Merge AS coverage into JS coverage\n */\n async generateCoverage(context: ReportContext): Promise<unknown> {\n const start = performance.now();\n\n debug('[HybridCoverageProvider] Generating coverage for test run');\n\n if (!this.v8Provider) {\n throw createPoolError(\n 'HybridCoverageProvider - generateCoverage failed to delegate to v8 provider',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n\n // Build AS coverage map\n let asCoverageMap = createCoverageMap();\n\n if (this.coverageOptions.globbedAssemblyScriptInclude?.length > 0) {\n debug(`[HybridCoverageProvider] Building AS coverage map with ${this.coverageOptions.globbedAssemblyScriptInclude.length} source files `);\n debug(() => {\n const accumulatedPositionCount = Object.values(this.accumulatedCoverageData.hitCountsByFileAndPosition)\n .reduce((sum, positions) => sum + Object.keys(positions)?.length, 0);\n const files = Object.keys(this.accumulatedCoverageData.hitCountsByFileAndPosition).length;\n return `[HybridCoverageProvider] Accumulated coverage data has ${accumulatedPositionCount} unique positions hit across ${files} debug source files`;\n });\n\n // parse source files with AST parser, then match to hits and convert to istanbul format\n const fileProcessingPromises = this.coverageOptions.globbedAssemblyScriptInclude.map(async (include: GlobResult) => {\n debug(`[HybridCoverageProvider] Parsing AS source for expected coverage: \"${include.absolute}\"`);\n \n const functionsByStartLine = await parseFunctionsFromFile(include.absolute, include.projectRootRelative) || {};\n debug(`[HybridCoverageProvider] Parsed ${Object.keys(functionsByStartLine).length} AS source functions in \"${include.absolute}\"`);\n\n const fileHitCountsByPosition = this.accumulatedCoverageData.hitCountsByFileAndPosition[include.absolute] ?? {};\n debug(`[HybridCoverageProvider] Accumulated AS coverage has ${Object.keys(fileHitCountsByPosition).length} positions for \"${include.absolute}\"`);\n\n // Containment matching (binary hit position → source) is performed during istanbul conversion\n return convertToIstanbulFormat(functionsByStartLine, fileHitCountsByPosition, include.absolute, this.coverageOptions.debugIstanbul);\n });\n\n // Wait for all files to complete\n const istanbulResults = await Promise.all(fileProcessingPromises);\n\n // Add all results to coverage map\n for (const istanbulData of istanbulResults) {\n asCoverageMap.addFileCoverage(istanbulData);\n }\n\n debug(`[HybridCoverageProvider] Built AS coverage map with ${Object.keys(asCoverageMap.data).length} files`);\n } else {\n debug('[HybridCoverageProvider] WARNING: No assemblyScriptInclude patterns yieldled files - Coverage Map will be empty!');\n }\n\n const asGenerateEnd = performance.now();\n debug(`[HybridCoverageProvider] TIMING AS generateCoverage: ${(asGenerateEnd - start).toFixed(2)} ms`);\n\n // Get JS coverage from v8 provider\n debug('[HybridCoverageProvider] Getting JS coverage from v8 provider');\n const jsCoverage = await this.v8Provider.generateCoverage(context) as CoverageMap;\n debug(`[HybridCoverageProvider] JS coverage has ${Object.keys(jsCoverage.data).length} files`);\n debug(`[HybridCoverageProvider] TIMING JS generateCoverage: ${(performance.now() - asGenerateEnd).toFixed(2)} ms`);\n\n // Merge AS coverage into JS coverage.\n // Use toJSON() to pass plain data instead of the CoverageMap instance. This avoids\n // instanceof failures when istanbul-lib-coverage is loaded from different module paths\n // (e.g. the pool workers resolve one copy while the coverage provider resolves another).\n if (asCoverageMap.files().length) {\n debug('[HybridCoverageProvider] Merging AS coverage into JS coverage');\n jsCoverage.merge(asCoverageMap.toJSON());\n } else {\n debug('[HybridCoverageProvider] AS coverage map empty, not merging into JS coverage');\n }\n debug(`[HybridCoverageProvider] Final merged coverage has ${Object.keys(jsCoverage.data).length} files`);\n\n debug(`[HybridCoverageProvider] TIMING Total generateCoverage: ${(performance.now() - start).toFixed(2)} ms`);\n\n return jsCoverage;\n }\n\n /**\n * Report coverage - delegate to v8 provider\n */\n async reportCoverage(coverageMap: unknown, context: ReportContext): Promise<void> {\n if (!this.v8Provider) {\n throw createPoolError(\n 'HybridCoverageProvider - reportCoverage failed to delegate to v8 provider',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n\n debug(`[HybridCoverageProvider] Reporting coverage (allTestsRun=${context.allTestsRun})`);\n await this.v8Provider.reportCoverage(coverageMap, context);\n }\n\n /**\n * Resolve options\n */\n resolveOptions(): ResolvedHybridProviderOptions {\n if (!this.v8Provider) {\n throw createPoolError(\n 'HybridCoverageProvider - resolveOptions failed to delegate to v8 provider',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n \n debug(`[HybridCoverageProvider] Resolving Coverage Options`);\n \n const definedCoverageOptions = this.projectConfig.coverage as CustomProviderOptions;\n const resolvedV8Options = this.v8Provider.resolveOptions() as ResolvedCoverageOptions<'v8'>;\n\n // For some reason the v8 provider builds its `excludes` values to include a null byte.\n // Remove null bytes for logging purposes so tools like grep won't complain about binary content.\n const sanitizedV8Options: ResolvedCoverageOptions<'v8'> = {\n ...resolvedV8Options,\n include: resolvedV8Options.include?.map(i => i.replace(/\\0/g, '')) || undefined,\n exclude: resolvedV8Options.exclude?.map(i => i.replace(/\\0/g, '')) || undefined\n };\n\n debug(`[HybridCoverageProvider] AS include: ${(definedCoverageOptions.assemblyScriptInclude || []).join(', ') || '(none)'}`);\n debug(`[HybridCoverageProvider] AS exclude: ${(definedCoverageOptions.assemblyScriptExclude || []).join(', ') || '(none)'}`);\n debug(`[HybridCoverageProvider] JS include: ${(sanitizedV8Options.include || []).join(', ') || '(none)'}`);\n debug(`[HybridCoverageProvider] JS exclude: ${(sanitizedV8Options.exclude || []).join(', ') || '(none)'}`);\n\n debug(`[HybridCoverageProvider] Globbing AS source files to include for coverage map basis`);\n const globbedAssemblyScriptInclude = globFiles(\n definedCoverageOptions.assemblyScriptInclude || [],\n definedCoverageOptions.assemblyScriptExclude || [],\n this.projectConfig.root\n );\n debug(`[HybridCoverageProvider] Including ${globbedAssemblyScriptInclude.length} AS files in coverage map`);\n \n const globbedAssemblyScriptExcludeOnly = globFiles(\n definedCoverageOptions.assemblyScriptExclude || [],\n [],\n this.projectConfig.root\n );\n debug(`[HybridCoverageProvider] Excluding ${globbedAssemblyScriptExcludeOnly.length} AS files from coverage map & instrumentation`);\n \n const resolvedCoverageOptions: ResolvedHybridProviderOptions = {\n ...resolvedV8Options,\n provider: 'custom',\n customProviderModule: definedCoverageOptions.customProviderModule,\n debugIstanbul: definedCoverageOptions.debugIstanbul ?? false,\n assemblyScriptInclude: definedCoverageOptions.assemblyScriptInclude ?? [],\n assemblyScriptExclude: definedCoverageOptions.assemblyScriptExclude ?? [],\n globbedAssemblyScriptInclude,\n globbedAssemblyScriptProjectRelativeExcludeOnly : globbedAssemblyScriptExcludeOnly.map(gr => gr.projectRootRelative)\n }; \n\n this.coverageOptions = resolvedCoverageOptions;\n return resolvedCoverageOptions;\n }\n\n async clean(clean: boolean = true): Promise<void> {\n debug('[HybridCoverageProvider] Clean coverage data - clean:', clean);\n if (clean) {\n this.accumulatedCoverageData = { hitCountsByFileAndPosition: {} };\n debug('[HybridCoverageProvider] Cleaned all internal coverage data');\n }\n\n if (this.v8Provider) {\n await this.v8Provider.clean(clean);\n debug(`[HybridCoverageProvider] V8 provider finished clean(${clean})`);\n }\n }\n}\n","/**\n * Coverage Provider Module Export\n *\n * This module exports the hybrid coverage provider for Vitest to load.\n * Users configure this via:\n * coverage.provider = 'custom'\n * coverage.customProviderModule = 'vitest-pool-assemblyscript/coverage'\n */\n\nimport { CoverageProviderModule } from 'vitest/node';\nimport v8CoverageModule from '@vitest/coverage-v8';\n\nimport { POOL_ERROR_NAMES } from '../types/constants.js';\nimport { createPoolError } from '../util/pool-errors.js';\nimport { HybridCoverageProvider } from './hybrid-coverage-provider.js';\n\n/**\n * Hybrid Coverage Provider\n *\n * This provider handles both AssemblyScript and JavaScript and coverage\n * - Converts AS coverage to Istanbul format\n * - Delegates JS coverage to Vitest's v8 provider\n * - Merges both into a unified coverage report\n */\nconst hybridProviderModule: CoverageProviderModule = {\n getProvider: (): HybridCoverageProvider => new HybridCoverageProvider(),\n\n startCoverage: async (runtimeOptions: {\n isolate: boolean\n }): Promise<unknown> => {\n if (v8CoverageModule.startCoverage) {\n return await v8CoverageModule.startCoverage(runtimeOptions);\n } else {\n throw createPoolError(\n 'HybridCoverageProvider - v8 coverage module does not provide `startCoverage`',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n },\n \n takeCoverage: async (runtimeOptions?: any): Promise<unknown> => {\n if (v8CoverageModule.takeCoverage) {\n return await v8CoverageModule.takeCoverage(runtimeOptions);\n } else {\n throw createPoolError(\n 'HybridCoverageProvider - v8 coverage module does not provide `takeCoverage`',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n },\n \n stopCoverage: async (runtimeOptions: {\n isolate: boolean\n }): Promise<unknown> => {\n if (v8CoverageModule.stopCoverage) {\n return await v8CoverageModule.stopCoverage(runtimeOptions);\n } else {\n throw createPoolError(\n 'HybridCoverageProvider - v8 coverage module does not provide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AAqB;AAChD,QAAM,yDAAyD,MAAM;AACrE,MAAI,OAAO;AACT,QAAK,0BAA0B,EAAE,4BAA4B,EAAE,EAAE;AACjE,SAAM,8DAA8D;;AAGtE,MAAI,KAAK,YAAY;AACnB,SAAM,KAAK,WAAW,MAAM,MAAM;AAClC,SAAM,uDAAuD,MAAM,GAAG;;;;;;;;;;;;;;;AClR5E,MAAM,uBAA+C;CACnD,mBAA2C,IAAI,wBAAwB;CAEvE,eAAe,OAAO,mBAEE;AACtB,MAAI,iBAAiB,cACnB,QAAO,MAAM,iBAAiB,cAAc,eAAe;MAE3D,OAAM,gBACJ,gFACA,iBAAiB,4BAClB;;CAIL,cAAc,OAAO,mBAA2C;AAC9D,MAAI,iBAAiB,aACnB,QAAO,MAAM,iBAAiB,aAAa,eAAe;MAE1D,OAAM,gBACJ,+EACA,iBAAiB,4BAClB;;CAIL,cAAc,OAAO,mBAEG;AACtB,MAAI,iBAAiB,aACnB,QAAO,MAAM,iBAAiB,aAAa,eAAe;MAE1D,OAAM,gBACJ,+EACA,iBAAiB,4BAClB;;CAGN;AAED,gCAAe"}
1
+ {"version":3,"file":"index.mjs","names":["parsePath","AssemblyScriptParser"],"sources":["../../src/coverage-provider/containment-matcher.ts","../../src/coverage-provider/istanbul-converter.ts","../../src/coverage-provider/ast-parser.ts","../../src/coverage-provider/glob-utils.ts","../../src/coverage-provider/hybrid-coverage-provider.ts","../../src/coverage-provider/index.ts"],"sourcesContent":["/**\n * Containment Matcher\n *\n * Provides containment-based matching for coverage mapping.\n * Binary debug info provides points (representativeLocation), source parsing provides ranges.\n * We find which source range contains each binary point.\n *\n * Usage by version:\n * - v1: Function containment matching (binary representativeLocation → source function range)\n * - v2: Function containment (same) + statement containment + branch path containment\n *\n * Why containment matching (not direct position lookup):\n * AS compiler generates source map entries differently by statement type:\n * - Variable declarations: source map points to statement start (keyword)\n * - Control flow (if/switch/for): source map points to condition EXPRESSION, not keyword\n *\n * Example: `if (n < 0)` → binary reports column 7 ('n'), not column 3 ('i' of 'if')\n *\n * Containment matching is more robust:\n * - Binary gives us a position (representativeLocation) somewhere in the function\n * - Source gives us function ranges (start/end line/column)\n * - We find which source function range contains the binary position\n * - Handles nested functions with \"tightest fit\" (innermost function wins)\n */\n\nimport type { ParsedSourceFunctionInfo, SourceRange } from '../types/types.js';\n\n/**\n * Functions indexed by file path, then by start line.\n * Multiple functions can start on the same line (e.g., nested arrow functions).\n */\nexport type FunctionsByFileAndStartLine = Record<string, Record<number, ParsedSourceFunctionInfo[]>>;\n\n/**\n * Find the source function whose range contains the given position.\n *\n * For nested functions, uses \"tightest fit\" - returns the innermost function\n * (the one with the largest start position among all containing functions).\n *\n * @param functionsByStartLine - Functions for a single file, indexed by start line\n * @param line - Target line number (1-based)\n * @param column - Target column number (1-based)\n * @returns The containing function, or undefined if no match\n */\nexport function findFunctionContainingPosition(\n functionsByStartLine: Record<number, ParsedSourceFunctionInfo[]>,\n line: number,\n column: number\n): ParsedSourceFunctionInfo | undefined {\n let bestMatch: ParsedSourceFunctionInfo | undefined;\n let bestStartLine = -1;\n let bestStartColumn = -1;\n\n // Check functions starting on lines <= target line\n for (const [startLineStr, functions] of Object.entries(functionsByStartLine)) {\n const startLine = Number(startLineStr);\n if (startLine > line) continue;\n\n for (const func of functions) {\n const { range } = func;\n\n // Check if position is within this function's range\n if (!isPositionInRange(line, column, range)) continue;\n\n // Tightest fit: prefer function with largest start position (innermost)\n if (startLine > bestStartLine ||\n (startLine === bestStartLine && range.startColumn > bestStartColumn)) {\n bestMatch = func;\n bestStartLine = startLine;\n bestStartColumn = range.startColumn;\n }\n }\n }\n\n return bestMatch;\n}\n\n/**\n * Check if a position (line, column) falls within a source range.\n *\n * @param line - Target line number (1-based)\n * @param column - Target column number (1-based)\n * @param range - Source range to check against\n * @returns true if position is within range (inclusive)\n */\nexport function isPositionInRange(\n line: number,\n column: number,\n range: SourceRange\n): boolean {\n // Outside line range entirely\n if (line < range.startLine || line > range.endLine) return false;\n\n // On start line but before start column\n if (line === range.startLine && column < range.startColumn) return false;\n\n // On end line but after end column\n if (line === range.endLine && column > range.endColumn) return false;\n\n return true;\n}\n","/**\n * Istanbul Format Converter\n *\n * Converts AssemblyScript coverage data to Istanbul's FileCoverageData format.\n * This enables integration with Vitest's coverage reporting system and standard\n * coverage tools like Codecov, Coveralls, etc.\n *\n * Current Implementation: Function-level coverage only\n * - Uses containment matching: binary positions → source function ranges\n * - Each function maps to both a function entry AND a statement entry\n * - Statement coverage matches function coverage (function-level granularity)\n * - Branch coverage is 0% (no branches tracked yet)\n * - Line coverage derived from statement coverage\n *\n * Future Enhancement (v2): Block-level statement and branch coverage\n */\n\nimport type { FileCoverageData, Range, FunctionMapping, BranchMapping } from 'istanbul-lib-coverage';\nimport type { ParsedSourceFunctionInfo } from '../types/types.js';\nimport { findFunctionContainingPosition } from './containment-matcher.js';\nimport { debugOverride } from '../util/debug.js';\n\n/**\n * Convert AssemblyScript coverage data to Istanbul format for a single file\n *\n * Algorithm (containment matching):\n * 1. For each hit position in fileHitCountsByPosition:\n * - Use containment matcher to find which source function contains this position\n * - Record the hit count for that function\n * 2. For each function in fileFunctionsByStartLine:\n * - Add function mapping to fnMap\n * - Add function hit count to f (from matched hits, or 0 if not hit)\n * - Add corresponding statement mapping to statementMap\n * - Add same hit count to s (statement coverage matches function coverage)\n *\n * @param fileFunctionsByStartLine - Functions for this file, keyed by start line (from AST parser)\n * @param fileHitCountsByPosition - Hit counts for this file, keyed by position \"line:column\" (from accumulated coverage)\n * @param absoluteFilePath - Absolute path to the source file (for Istanbul output)\n * @returns Istanbul FileCoverage object\n */\nexport async function convertToIstanbulFormat(\n fileFunctionsByStartLine: Record<number, ParsedSourceFunctionInfo[]>,\n fileHitCountsByPosition: Record<string, number>,\n absoluteFilePath: string,\n istanbulDebugEnabled: boolean\n): Promise<FileCoverageData> {\n const startMatch = performance.now();\n\n function istanbulDebug(...args: any[]): void {\n if (istanbulDebugEnabled) {\n debugOverride(...args);\n }\n };\n\n istanbulDebug(() => {\n const sourceFunctionCount = Object.values(fileFunctionsByStartLine).reduce((sum, funcs) => sum + funcs.length, 0);\n const uniqueHitPosCount = Object.keys(fileHitCountsByPosition).length;\n const coverageEstimate = sourceFunctionCount === 0 ? Infinity : ((uniqueHitPosCount * 100) / sourceFunctionCount).toFixed(2);\n\n return `[IstanbulConverter] Processing source file: \"${absoluteFilePath}\"\\n`\n + `[IstanbulConverter] Source: ${sourceFunctionCount} total functions, Coverage: ${uniqueHitPosCount} unique hit positions\\n`\n + `[IstanbulConverter] Sanity Check - AS File Coverage Estimate: ${coverageEstimate}%\\n`\n + `[IstanbulConverter] Containment matching functions: coverage hit positions to source functions by range`;\n });\n\n // Build a map of function → hit count using containment matching\n // Key: function source identity (qualifiedName), Value: hit count\n const hitCountsBySourceFunctionName = new Map<ParsedSourceFunctionInfo, number>();\n\n // For each hit position, find which function contains it\n for (const [positionKey, hitCount] of Object.entries(fileHitCountsByPosition)) {\n // Position key format is \"line:column\"\n const parts = positionKey.split(':');\n const lineStr = parts[0];\n const columnStr = parts[1];\n\n if (lineStr && columnStr) {\n const line = parseInt(lineStr, 10);\n const column = parseInt(columnStr, 10);\n\n const containingFunction = findFunctionContainingPosition(fileFunctionsByStartLine, line, column);\n if (containingFunction) {\n // Accumulate hits (in case multiple positions map to same function)\n const existingHits = hitCountsBySourceFunctionName.get(containingFunction);\n const existingHitsCount = existingHits ?? 0;\n const max = Math.max(existingHitsCount, hitCount);\n hitCountsBySourceFunctionName.set(containingFunction, max); // <-- TODO: Explain this max logic\n\n if (existingHits !== undefined) {\n istanbulDebug(`[IstanbulConverter] Position ${positionKey} → function \"${containingFunction.shortName}\" EXISTING HITS: ${existingHits} NEW COUNT: ${max}`);\n } else {\n istanbulDebug(`[IstanbulConverter] Position ${positionKey} → function \"${containingFunction.shortName}\" (hits: ${hitCount})`);\n }\n } else {\n istanbulDebug(`[IstanbulConverter] Position ${positionKey} has no containing function`);\n }\n }\n }\n\n const startConvert = performance.now();\n istanbulDebug(`[IstanbulConverter] Matching Complete - Converting to Istanbul format`);\n\n // Initialize Istanbul data structures\n const fnMap: { [key: string]: FunctionMapping } = {};\n const f: { [key: string]: number } = {};\n const statementMap: { [key: string]: Range } = {};\n const s: { [key: string]: number } = {};\n const branchMap: { [key: string]: BranchMapping } = {};\n const b: { [key: string]: number[] } = {};\n\n // Convert function coverage to Istanbul format\n // Iterate all functions from parsed source (ensures 0-hit functions are included)\n let funcIdx = 0;\n for (const functions of Object.values(fileFunctionsByStartLine)) {\n for (const funcInfo of functions) {\n const { range, shortName } = funcInfo;\n\n // Defensive: skip functions with invalid metadata (shouldn't happen - AST parser filters these)\n if (range.startLine === 0) {\n continue;\n }\n\n // Get hit count from containment matching (or 0 if not hit)\n const hitCount = hitCountsBySourceFunctionName.get(funcInfo) ?? 0;\n const displayShortName = shortName && shortName !== '' ? shortName : '<anonymous>';\n istanbulDebug(\n `[IstanbulConverter] Istanbul function index ${funcIdx}: \"${displayShortName}\"`\n + ` (source ${range.startLine}:${range.startColumn} - ${range.endLine}:${range.endColumn}), hits: ${hitCount}`\n );\n\n // Create function mapping\n // Both 'decl' (declaration) and 'loc' (location) use the same range\n // Internal ParsedSourceFunctionInfo uses 1-based columns, Istanbul expects 0-based\n const istanbulRange: Range = {\n start: { line: range.startLine, column: range.startColumn - 1 },\n end: { line: range.endLine, column: range.endColumn - 1 }\n };\n\n const idxStr = funcIdx.toString();\n fnMap[idxStr] = {\n name: shortName,\n decl: istanbulRange,\n loc: istanbulRange,\n line: range.startLine\n };\n f[idxStr] = hitCount;\n\n // Create corresponding statement mapping\n // For function-level coverage, each function is one \"statement\"\n // The statement range matches the function range\n // This gives us statement coverage at function granularity\n statementMap[idxStr] = istanbulRange;\n s[idxStr] = hitCount;\n\n funcIdx++;\n }\n }\n\n const done = performance.now();\n const matchingMs = (startConvert - startMatch).toFixed(2);\n const convertMs = (done - startConvert).toFixed(2);\n const totalMs = (done - startMatch).toFixed(2);\n\n istanbulDebug(\n `[IstanbulConverter] Coverage Coversion Complete: ${Object.keys(fnMap).length} functions,` \n + ` ${totalMs} ms total (matching: ${matchingMs} ms, convert: ${convertMs} ms)`\n );\n\n return {\n path: absoluteFilePath,\n fnMap,\n f,\n statementMap,\n s,\n branchMap,\n b\n };\n}\n","/**\n * AST Parser for AssemblyScript Source Files\n *\n * Parses AS source files to extract function metadata for coverage.\n * Used by generateCoverage to build empty coverage map from all source files.\n *\n * Source AST is the source of truth for what SHOULD be covered.\n * Binary instrumentation tells us what we CAN measure (hit counts).\n *\n * Functions are grouped by start line for efficient containment matching.\n *\n * Architecture:\n * - Uses shared ASTVisitor for complete NodeKind coverage\n * - Overrides hooks to extract function information during traversal\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { parse as parsePath } from 'node:path';\nimport {\n Parser as AssemblyScriptParser,\n Source,\n BlockStatement,\n Node,\n FunctionDeclaration,\n MethodDeclaration,\n ClassDeclaration,\n VariableDeclaration,\n FunctionExpression,\n} from 'assemblyscript';\n\nimport type { ParsedSourceFunctionInfo, SourceRange } from '../types/types.js';\nimport { ASCommonFlags, ASNodeKind } from '../types/constants.js';\nimport { ASTVisitor } from '../util/ast-visitor.js';\n\n/**\n * Visitor that extracts function information from AST nodes\n */\nclass FunctionExtractorVisitor extends ASTVisitor {\n /** Source file being parsed */\n private source: Source;\n /** Module path for building qualified names */\n private modulePath: string;\n /** Absolute file path */\n private filePath: string;\n /** Accumulated function records, keyed by start line */\n readonly functions: Record<number, ParsedSourceFunctionInfo[]> = {};\n /** Current class name (when inside a class) */\n private currentClassName: string | null = null;\n\n constructor(source: Source, modulePath: string, filePath: string) {\n super();\n this.source = source;\n this.modulePath = modulePath;\n this.filePath = filePath;\n }\n\n /**\n * Track class context when entering a class\n */\n protected onClassEnter(node: ClassDeclaration): void {\n this.currentClassName = node.name?.text ?? 'Anonymous';\n }\n\n /**\n * Restore class context when exiting a class\n */\n protected onClassExit(_node: ClassDeclaration): void {\n this.currentClassName = null;\n }\n\n /**\n * Extract function info from function declarations\n */\n protected onFunctionDeclaration(node: FunctionDeclaration): boolean {\n if (node.body && this.hasBodyStatements(node.body)) {\n const shortName = node.name?.text ?? '~anonymous';\n const qualifiedName = `${this.modulePath}/${shortName}`;\n const range = this.buildRange(node, node.name ?? null);\n this.addFunction(qualifiedName, shortName, range);\n }\n return true; // Continue recursion into body\n }\n\n /**\n * Extract function info from method declarations\n */\n protected onMethodDeclaration(node: MethodDeclaration): boolean {\n if (node.body && this.hasBodyStatements(node.body)) {\n const methodName = node.name?.text ?? 'constructor';\n const className = this.currentClassName ?? 'Unknown';\n const flags = node.flags;\n\n // Determine method type from flags\n const isStatic = (flags & ASCommonFlags.Static) !== 0;\n const isGetter = (flags & ASCommonFlags.Get) !== 0;\n const isSetter = (flags & ASCommonFlags.Set) !== 0;\n\n // Build short name to match binary naming convention:\n // - Static: ClassName.methodName\n // - Getter: ClassName#get:propertyName\n // - Setter: ClassName#set:propertyName\n // - Instance: ClassName#methodName\n let shortName: string;\n if (isStatic) {\n shortName = `${className}.${methodName}`;\n } else if (isGetter) {\n shortName = `${className}#get:${methodName}`;\n } else if (isSetter) {\n shortName = `${className}#set:${methodName}`;\n } else {\n shortName = `${className}#${methodName}`;\n }\n\n const qualifiedName = `${this.modulePath}/${shortName}`;\n const range = this.buildRange(node, node.name ?? null);\n this.addFunction(qualifiedName, shortName, range);\n }\n return true; // Continue recursion into body\n }\n\n /**\n * Extract function info from variable declarations (arrow functions)\n */\n protected onVariableDeclaration(node: VariableDeclaration): boolean {\n if (node.initializer && node.initializer.kind === ASNodeKind.Function) {\n const funcExpr = node.initializer as FunctionExpression;\n const funcDecl = funcExpr.declaration;\n\n if (funcDecl.body && this.hasBodyStatements(funcDecl.body)) {\n // Use variable name for the function\n const shortName = node.name.text;\n const qualifiedName = `${this.modulePath}/${shortName}`;\n\n // Use the variable declaration's range\n const range: SourceRange = {\n filePath: this.filePath,\n startLine: this.source.lineAt(node.range.start),\n startColumn: this.source.columnAt(),\n endLine: this.source.lineAt(node.range.end),\n endColumn: this.source.columnAt(),\n };\n\n this.addFunction(qualifiedName, shortName, range);\n }\n\n // Visit the function body manually since we're handling this specially\n if (funcDecl.body) {\n this.visitNode(funcDecl.body);\n }\n return false; // Don't recurse again - we handled it\n }\n return true; // Continue recursion for non-function initializers\n }\n\n /**\n * Check if a function body has statements (non-empty body)\n */\n private hasBodyStatements(body: Node): boolean {\n if (body.kind === ASNodeKind.Block) {\n const blockBody = body as BlockStatement;\n return blockBody.statements.length > 0;\n }\n // Expression body (braceless arrow) - always has the expression\n return true;\n }\n\n /**\n * Add a function to the functions record, keyed by start line\n */\n private addFunction(qualifiedName: string, shortName: string, range: SourceRange): void {\n const startLine = range.startLine;\n if (!this.functions[startLine]) {\n this.functions[startLine] = [];\n }\n this.functions[startLine].push({ qualifiedName, shortName, range });\n }\n\n /**\n * Build a SourceRange for a node, using name.range.start to skip decorators\n */\n private buildRange(node: Node, nameNode: Node | null): SourceRange {\n const startNode = nameNode ?? node;\n return {\n filePath: this.filePath,\n startLine: this.source.lineAt(startNode.range.start),\n startColumn: this.source.columnAt(),\n endLine: this.source.lineAt(node.range.end),\n endColumn: this.source.columnAt(),\n };\n }\n}\n\n/**\n * Parse functions from a single AS source file\n *\n * @param absoluteSourceFilePath - Absolute path to AS source file\n * @param relativeSourceFilePath - Relative path to AS source file (derived once in caller and used several places)\n * @returns Record of start line to array of ParsedSourceFunctionInfo (multiple functions can start on same line)\n */\nexport async function parseFunctionsFromFile(\n absoluteSourceFilePath: string,\n relativeSourceFilePath: string,\n): Promise<Record<number, ParsedSourceFunctionInfo[]>> {\n const sourceCode = await readFile(absoluteSourceFilePath, 'utf8');\n\n // Build the module path (strip any extension, use forward slashes)\n const parsed = parsePath(relativeSourceFilePath);\n const modulePath = parsed.dir ? `${parsed.dir}/${parsed.name}` : parsed.name;\n\n // Parse with AssemblyScript parser\n const asParser = new AssemblyScriptParser();\n asParser.parseFile(sourceCode, relativeSourceFilePath, true);\n\n const source = asParser.currentSource;\n if (!source) {\n return {};\n }\n\n // Create visitor and traverse\n const visitor = new FunctionExtractorVisitor(source, modulePath, absoluteSourceFilePath);\n visitor.visitSource(source);\n\n return visitor.functions || {};\n}\n","/**\n * Glob Utilities for Coverage\n *\n * Uses tinyglobby to glob AssemblyScript files matching coverage include/exclude patterns.\n * Supports ../ path traversals for projects that import source from outside the project root.\n *\n * Note: tinyglobby docs warn of a performance cost when globbing outside cwd (e.g. ../ patterns)\n * due to recalculating relative paths. Acceptable here since this runs once at startup.\n */\n\nimport { relative } from 'node:path';\nimport { globSync } from 'tinyglobby';\n\nimport { GlobResult } from '../types/types.js';\nimport { toForwardSlash } from '../util/path-utils.js';\n\nconst NODE_MODULES_GLOB = '**/node_modules/**';\n\n/**\n * Glob files matching coverage include/exclude patterns\n *\n * @param include - Include patterns (e.g., ['assembly/**\\/*.ts'])\n * @param exclude - Exclude patterns (e.g., ['**\\/*.test.ts'])\n * @param projectRoot - Project root directory\n * @returns Array of glob results with absolute and project-root-relative paths\n */\nexport function globFiles(\n include: string[],\n exclude: string[],\n projectRoot: string\n): GlobResult[] {\n if (include.length === 0) {\n return [];\n }\n\n const absolutePaths = globSync(include, {\n cwd: projectRoot,\n ignore: [NODE_MODULES_GLOB, ...exclude],\n absolute: true,\n });\n\n return absolutePaths.map((absolute) => ({\n absolute: toForwardSlash(absolute),\n projectRootRelative: toForwardSlash(relative(projectRoot, absolute)),\n }));\n}\n","/**\n * Hybrid Coverage Provider\n *\n * This provider handles both AssemblyScript and JavaScript and coverage\n * - Converts AS coverage to Istanbul format\n * - Delegates JS coverage to Vitest's v8 provider\n * - Merges both into a unified coverage report\n */\n\nimport { basename, relative } from 'node:path';\nimport type {\n CoverageProvider,\n Vitest,\n ReportContext,\n ResolvedCoverageOptions,\n CustomProviderOptions,\n ResolvedConfig,\n} from 'vitest/node';\nimport type { AfterSuiteRunMeta, SerializedConfig } from 'vitest';\nimport v8CoverageModule from '@vitest/coverage-v8';\nimport type { CoverageMap } from 'istanbul-lib-coverage';\nimport istanbulCoverage from 'istanbul-lib-coverage';\nconst { createCoverageMap } = istanbulCoverage;\n\n// pick up CustomProviderOptions module augmentation\nimport '../config/custom-provider-options.js';\n\nimport { convertToIstanbulFormat } from './istanbul-converter.js';\nimport { parseFunctionsFromFile } from './ast-parser.js';\nimport { globFiles } from './glob-utils.js';\nimport { getProjectSerializedOrGlobalConfig } from '../util/resolve-config.js';\nimport { mergeCoverageData } from './coverage-merge.js';\nimport { debug } from '../util/debug.js';\nimport { createPoolError } from '../util/pool-errors.js';\nimport type {\n AssemblyScriptCoveragePayload,\n CoverageData,\n GlobResult,\n ResolvedHybridProviderOptions,\n} from '../types/types.js';\nimport {\n POOL_ERROR_NAMES,\n COVERAGE_PAYLOAD_FORMATS\n} from '../types/constants.js';\nimport { warnIfASCoverageNotSupportedByNode, warnIfNativeBuildFailed } from '../util/feature-check.js';\n\nexport class HybridCoverageProvider implements CoverageProvider {\n name = 'hybrid-assemblyscript-v8' as const;\n\n private v8Provider: CoverageProvider | undefined;\n private accumulatedCoverageData: CoverageData = { hitCountsByFileAndPosition: {} };\n private projectConfig: SerializedConfig | ResolvedConfig = {} as SerializedConfig;\n private coverageOptions: ResolvedHybridProviderOptions = {} as ResolvedHybridProviderOptions;\n\n /**\n * Initialize the provider and get reference to v8 provider\n */\n async initialize(ctx: Vitest): Promise<void> {\n this.projectConfig = getProjectSerializedOrGlobalConfig(ctx).config;\n\n debug('[HybridCoverageProvider] Initializing Provider');\n\n // Get v8 provider from the coverage module\n this.v8Provider = await v8CoverageModule.getProvider();\n\n if (!this.v8Provider) {\n throw createPoolError(\n 'HybridCoverageProvider - initialize failed to get delegated v8 provider',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n\n await this.v8Provider.initialize(ctx);\n this.v8Provider.name = 'hybrid-assemblyscript-v8 (delegated v8 reporter)' as const;\n debug('[HybridCoverageProvider] Initialized with delegated v8 provider');\n\n warnIfASCoverageNotSupportedByNode();\n await warnIfNativeBuildFailed();\n }\n\n /**\n * Handle suite completion - delegate based on coverage format marker\n */\n async onAfterSuiteRun(meta: AfterSuiteRunMeta): Promise<void> {\n const start = performance.now();\n const format: string | undefined = (meta?.coverage as any)?.__format;\n let suiteLogLabel = meta.testFiles.length > 0 ? basename(meta.testFiles[0]!) : '';\n\n // Check for AssemblyScript format marker\n if (format === COVERAGE_PAYLOAD_FORMATS.AssemblyScript) {\n const payload = meta.coverage as AssemblyScriptCoveragePayload;\n const { coverageData, suiteLogLabel: label } = payload;\n suiteLogLabel = label;\n\n debug(() => {\n const fileCount = Object.keys(coverageData.hitCountsByFileAndPosition).length;\n const positionCount = Object.values(coverageData.hitCountsByFileAndPosition)\n .reduce((sum, positions) => sum + Object.keys(positions).length, 0);\n return `[HybridCoverageProvider] ${suiteLogLabel} - onAfterSuiteRun - Suite payload: ${positionCount} unique positions over ${fileCount} source files`;\n });\n\n // Merge incoming coverage data into accumulated (by position, summing hit counts)\n mergeCoverageData(this.accumulatedCoverageData, coverageData);\n\n debug(() => {\n const fileCount = Object.keys(this.accumulatedCoverageData.hitCountsByFileAndPosition).length;\n const positionCount = Object.values(this.accumulatedCoverageData.hitCountsByFileAndPosition)\n .reduce((sum, positions) => sum + Object.keys(positions).length, 0);\n return `[HybridCoverageProvider] ${suiteLogLabel} - onAfterSuiteRun - Accumulated coverage: ${positionCount} unique positions over ${fileCount} source files`;\n });\n } else {\n // Delegate to v8 provider for all other formats (JS, etc.)\n if (!this.v8Provider) {\n throw createPoolError(\n 'HybridCoverageProvider - onAfterSuiteRun failed to delegate to v8 provider',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n\n debug(`[HybridCoverageProvider] ${suiteLogLabel} - Delegating to v8 provider`);\n await this.v8Provider.onAfterSuiteRun(meta);\n }\n\n debug(() => {\n const files = meta.testFiles.map(tf => relative(this.projectConfig.root, tf)).join(',');\n return `[HybridCoverageProvider] ${suiteLogLabel} - onAfterSuiteRun complete - TIMING ${(performance.now() - start).toFixed(2)} ms | testFiles: \"${files}\"`;\n });\n }\n\n /**\n * Generate unified coverage map (merging JS and AS coverage)\n *\n * Flow:\n * 1. Parse included AS source files to get sourceDebugInfo (source of truth for line numbers)\n * 1. Build merged CoverageData (all source functions + accumulated hit counts)\n * 4. Convert merged CoverageData to Istanbul format\n * 5. Get JS coverage from v8 provider\n * 6. Merge AS coverage into JS coverage\n */\n async generateCoverage(context: ReportContext): Promise<unknown> {\n const start = performance.now();\n\n debug('[HybridCoverageProvider] Generating coverage for test run');\n\n if (!this.v8Provider) {\n throw createPoolError(\n 'HybridCoverageProvider - generateCoverage failed to delegate to v8 provider',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n\n // Build AS coverage map\n let asCoverageMap = createCoverageMap();\n\n if (this.coverageOptions.globbedAssemblyScriptInclude?.length > 0) {\n debug(`[HybridCoverageProvider] Building AS coverage map with ${this.coverageOptions.globbedAssemblyScriptInclude.length} source files `);\n debug(() => {\n const accumulatedPositionCount = Object.values(this.accumulatedCoverageData.hitCountsByFileAndPosition)\n .reduce((sum, positions) => sum + Object.keys(positions)?.length, 0);\n const files = Object.keys(this.accumulatedCoverageData.hitCountsByFileAndPosition).length;\n return `[HybridCoverageProvider] Accumulated coverage data has ${accumulatedPositionCount} unique positions hit across ${files} debug source files`;\n });\n\n // parse source files with AST parser, then match to hits and convert to istanbul format\n const fileProcessingPromises = this.coverageOptions.globbedAssemblyScriptInclude.map(async (include: GlobResult) => {\n debug(`[HybridCoverageProvider] Parsing AS source for expected coverage: \"${include.absolute}\"`);\n \n const functionsByStartLine = await parseFunctionsFromFile(include.absolute, include.projectRootRelative) || {};\n debug(`[HybridCoverageProvider] Parsed ${Object.keys(functionsByStartLine).length} AS source functions in \"${include.absolute}\"`);\n\n const fileHitCountsByPosition = this.accumulatedCoverageData.hitCountsByFileAndPosition[include.absolute] ?? {};\n debug(`[HybridCoverageProvider] Accumulated AS coverage has ${Object.keys(fileHitCountsByPosition).length} positions for \"${include.absolute}\"`);\n\n // Containment matching (binary hit position → source) is performed during istanbul conversion\n return convertToIstanbulFormat(functionsByStartLine, fileHitCountsByPosition, include.absolute, this.coverageOptions.debugIstanbul);\n });\n\n // Wait for all files to complete\n const istanbulResults = await Promise.all(fileProcessingPromises);\n\n // Add all results to coverage map\n for (const istanbulData of istanbulResults) {\n asCoverageMap.addFileCoverage(istanbulData);\n }\n\n debug(`[HybridCoverageProvider] Built AS coverage map with ${Object.keys(asCoverageMap.data).length} files`);\n } else {\n debug('[HybridCoverageProvider] WARNING: No assemblyScriptInclude patterns yieldled files - Coverage Map will be empty!');\n }\n\n const asGenerateEnd = performance.now();\n debug(`[HybridCoverageProvider] TIMING AS generateCoverage: ${(asGenerateEnd - start).toFixed(2)} ms`);\n\n // Get JS coverage from v8 provider\n debug('[HybridCoverageProvider] Getting JS coverage from v8 provider');\n const jsCoverage = await this.v8Provider.generateCoverage(context) as CoverageMap;\n debug(`[HybridCoverageProvider] JS coverage has ${Object.keys(jsCoverage.data).length} files`);\n debug(`[HybridCoverageProvider] TIMING JS generateCoverage: ${(performance.now() - asGenerateEnd).toFixed(2)} ms`);\n\n // Merge AS coverage into JS coverage.\n // Use toJSON() to pass plain data instead of the CoverageMap instance. This avoids\n // instanceof failures when istanbul-lib-coverage is loaded from different module paths\n // (e.g. the pool workers resolve one copy while the coverage provider resolves another).\n if (asCoverageMap.files().length) {\n debug('[HybridCoverageProvider] Merging AS coverage into JS coverage');\n jsCoverage.merge(asCoverageMap.toJSON());\n } else {\n debug('[HybridCoverageProvider] AS coverage map empty, not merging into JS coverage');\n }\n debug(`[HybridCoverageProvider] Final merged coverage has ${Object.keys(jsCoverage.data).length} files`);\n\n debug(`[HybridCoverageProvider] TIMING Total generateCoverage: ${(performance.now() - start).toFixed(2)} ms`);\n\n return jsCoverage;\n }\n\n /**\n * Report coverage - delegate to v8 provider\n */\n async reportCoverage(coverageMap: unknown, context: ReportContext): Promise<void> {\n if (!this.v8Provider) {\n throw createPoolError(\n 'HybridCoverageProvider - reportCoverage failed to delegate to v8 provider',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n\n debug(`[HybridCoverageProvider] Reporting coverage (allTestsRun=${context.allTestsRun})`);\n await this.v8Provider.reportCoverage(coverageMap, context);\n }\n\n /**\n * Resolve options\n */\n resolveOptions(): ResolvedHybridProviderOptions {\n if (!this.v8Provider) {\n throw createPoolError(\n 'HybridCoverageProvider - resolveOptions failed to delegate to v8 provider',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n \n debug(`[HybridCoverageProvider] Resolving Coverage Options`);\n \n const definedCoverageOptions = this.projectConfig.coverage as CustomProviderOptions;\n const resolvedV8Options = this.v8Provider.resolveOptions() as ResolvedCoverageOptions<'v8'>;\n\n // For some reason the v8 provider builds its `excludes` values to include a null byte.\n // Remove null bytes for logging purposes so tools like grep won't complain about binary content.\n const sanitizedV8Options: ResolvedCoverageOptions<'v8'> = {\n ...resolvedV8Options,\n include: resolvedV8Options.include?.map(i => i.replace(/\\0/g, '')) || undefined,\n exclude: resolvedV8Options.exclude?.map(i => i.replace(/\\0/g, '')) || undefined\n };\n\n debug(`[HybridCoverageProvider] AS include: ${(definedCoverageOptions.assemblyScriptInclude || []).join(', ') || '(none)'}`);\n debug(`[HybridCoverageProvider] AS exclude: ${(definedCoverageOptions.assemblyScriptExclude || []).join(', ') || '(none)'}`);\n debug(`[HybridCoverageProvider] JS include: ${(sanitizedV8Options.include || []).join(', ') || '(none)'}`);\n debug(`[HybridCoverageProvider] JS exclude: ${(sanitizedV8Options.exclude || []).join(', ') || '(none)'}`);\n\n debug(`[HybridCoverageProvider] Globbing AS source files to include for coverage map basis`);\n const globbedAssemblyScriptInclude = globFiles(\n definedCoverageOptions.assemblyScriptInclude || [],\n definedCoverageOptions.assemblyScriptExclude || [],\n this.projectConfig.root\n );\n debug(`[HybridCoverageProvider] Including ${globbedAssemblyScriptInclude.length} AS files in coverage map`);\n \n const globbedAssemblyScriptExcludeOnly = globFiles(\n definedCoverageOptions.assemblyScriptExclude || [],\n [],\n this.projectConfig.root\n );\n debug(`[HybridCoverageProvider] Excluding ${globbedAssemblyScriptExcludeOnly.length} AS files from coverage map & instrumentation`);\n \n const resolvedCoverageOptions: ResolvedHybridProviderOptions = {\n ...resolvedV8Options,\n provider: 'custom',\n customProviderModule: definedCoverageOptions.customProviderModule,\n debugIstanbul: definedCoverageOptions.debugIstanbul ?? false,\n assemblyScriptInclude: definedCoverageOptions.assemblyScriptInclude ?? [],\n assemblyScriptExclude: definedCoverageOptions.assemblyScriptExclude ?? [],\n globbedAssemblyScriptInclude,\n globbedAssemblyScriptProjectRelativeExcludeOnly : globbedAssemblyScriptExcludeOnly.map(gr => gr.projectRootRelative)\n }; \n\n this.coverageOptions = resolvedCoverageOptions;\n return resolvedCoverageOptions;\n }\n\n async clean(clean: boolean = true): Promise<void> {\n debug('[HybridCoverageProvider] Clean coverage data - clean:', clean);\n if (clean) {\n this.accumulatedCoverageData = { hitCountsByFileAndPosition: {} };\n debug('[HybridCoverageProvider] Cleaned all internal coverage data');\n }\n\n if (this.v8Provider) {\n await this.v8Provider.clean(clean);\n debug(`[HybridCoverageProvider] V8 provider finished clean(${clean})`);\n }\n }\n}\n","/**\n * Coverage Provider Module Export\n *\n * This module exports the hybrid coverage provider for Vitest to load.\n * Users configure this via:\n * coverage.provider = 'custom'\n * coverage.customProviderModule = 'vitest-pool-assemblyscript/coverage'\n */\n\nimport { CoverageProviderModule } from 'vitest/node';\nimport v8CoverageModule from '@vitest/coverage-v8';\n\nimport { POOL_ERROR_NAMES } from '../types/constants.js';\nimport { createPoolError } from '../util/pool-errors.js';\nimport { HybridCoverageProvider } from './hybrid-coverage-provider.js';\n\n/**\n * Hybrid Coverage Provider\n *\n * This provider handles both AssemblyScript and JavaScript and coverage\n * - Converts AS coverage to Istanbul format\n * - Delegates JS coverage to Vitest's v8 provider\n * - Merges both into a unified coverage report\n */\nconst hybridProviderModule: CoverageProviderModule = {\n getProvider: (): HybridCoverageProvider => new HybridCoverageProvider(),\n\n startCoverage: async (runtimeOptions: {\n isolate: boolean\n }): Promise<unknown> => {\n if (v8CoverageModule.startCoverage) {\n return await v8CoverageModule.startCoverage(runtimeOptions);\n } else {\n throw createPoolError(\n 'HybridCoverageProvider - v8 coverage module does not provide `startCoverage`',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n },\n \n takeCoverage: async (runtimeOptions?: any): Promise<unknown> => {\n if (v8CoverageModule.takeCoverage) {\n return await v8CoverageModule.takeCoverage(runtimeOptions);\n } else {\n throw createPoolError(\n 'HybridCoverageProvider - v8 coverage module does not provide `takeCoverage`',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n },\n \n stopCoverage: async (runtimeOptions: {\n isolate: boolean\n }): Promise<unknown> => {\n if (v8CoverageModule.stopCoverage) {\n return await v8CoverageModule.stopCoverage(runtimeOptions);\n } else {\n throw createPoolError(\n 'HybridCoverageProvider - v8 coverage module does not provide `stopCoverage`',\n POOL_ERROR_NAMES.HybridCoverageProviderError\n );\n }\n },\n};\n\nexport default hybridProviderModule;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,+BACd,sBACA,MACA,QACsC;CACtC,IAAI;CACJ,IAAI,gBAAgB;CACpB,IAAI,kBAAkB;AAGtB,MAAK,MAAM,CAAC,cAAc,cAAc,OAAO,QAAQ,qBAAqB,EAAE;EAC5E,MAAM,YAAY,OAAO,aAAa;AACtC,MAAI,YAAY,KAAM;AAEtB,OAAK,MAAM,QAAQ,WAAW;GAC5B,MAAM,EAAE,UAAU;AAGlB,OAAI,CAAC,kBAAkB,MAAM,QAAQ,MAAM,CAAE;AAG7C,OAAI,YAAY,iBACX,cAAc,iBAAiB,MAAM,cAAc,iBAAkB;AACxE,gBAAY;AACZ,oBAAgB;AAChB,sBAAkB,MAAM;;;;AAK9B,QAAO;;;;;;;;;;AAWT,SAAgB,kBACd,MACA,QACA,OACS;AAET,KAAI,OAAO,MAAM,aAAa,OAAO,MAAM,QAA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M,gBACJ,+EACA,iBAAiB,4BAClB;;CAGN"}
@@ -1,4 +1,4 @@
1
- import { HybridProviderOptions } from "./types-6ta3lLJM.mjs";
1
+ import { HybridProviderOptions } from "./types-CnJC7Ydg.mjs";
2
2
  import { CoverageV8Options } from "vitest/node";
3
3
 
4
4
  //#region src/config/custom-provider-options.d.ts
@@ -23,4 +23,4 @@ declare module "vitest/node" {
23
23
  customProviderModule: string;
24
24
  }
25
25
  }
26
- //# sourceMappingURL=custom-provider-options-39YrzdqD.d.mts.map
26
+ //# sourceMappingURL=custom-provider-options-BZg2Trd5.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"custom-provider-options-39YrzdqD.d.mts","names":[],"sources":["../src/config/custom-provider-options.ts"],"mappings":";;;;;;AAE2C;;;;;;;;;;;;;YAiB/B,qBAAA,SAA8B,qBAAA,EAAuB,IAAA,CAAK,iBAAA;IAClE,QAAA;IAGD;IAAA,oBAAA;EAAA;AAAA"}
1
+ {"version":3,"file":"custom-provider-options-BZg2Trd5.d.mts","names":[],"sources":["../src/config/custom-provider-options.ts"],"mappings":";;;;;;AAE2C;;;;;;;;;;;;;YAiB/B,qBAAA,SAA8B,qBAAA,EAAuB,IAAA,CAAK,iBAAA;IAClE,QAAA;IAGD;IAAA,oBAAA;EAAA;AAAA"}
@@ -0,0 +1,82 @@
1
+ import c from "tinyrainbow";
2
+ import { dirname, resolve } from "node:path";
3
+ import { access, readFile, unlink } from "node:fs/promises";
4
+ import { versions } from "node:process";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ //#region src/util/feature-check.ts
8
+ const NATIVE_BUILD_ERROR_FILE = resolve(resolve(dirname(fileURLToPath(import.meta.url)), ".."), ".native-build-error");
9
+ /**
10
+ * Read the native build error marker file if it exists.
11
+ * Returns undefined if file doesn't exist or can't be parsed.
12
+ */
13
+ async function readNativeBuildError() {
14
+ try {
15
+ const content = await readFile(NATIVE_BUILD_ERROR_FILE, "utf8");
16
+ return JSON.parse(content);
17
+ } catch {
18
+ return;
19
+ }
20
+ }
21
+ /**
22
+ * Check if a native build error marker file exists.
23
+ * Used by compiler threads to distinguish known build failures (marker present,
24
+ * user already warned by coverage provider) from unexpected addon load failures.
25
+ */
26
+ async function hasNativeBuildError() {
27
+ try {
28
+ await access(NATIVE_BUILD_ERROR_FILE);
29
+ return true;
30
+ } catch {
31
+ return false;
32
+ }
33
+ }
34
+ /**
35
+ * Remove the native build error marker file.
36
+ * Called when the addon loads successfully at runtime, clearing any stale marker
37
+ * left from a previous failed install (e.g. after a manual rebuild).
38
+ */
39
+ async function clearNativeBuildError() {
40
+ try {
41
+ await unlink(NATIVE_BUILD_ERROR_FILE);
42
+ } catch {}
43
+ }
44
+ const NODE_VERSION = versions.node;
45
+ const NODE_MAJOR_VERSION = parseInt(NODE_VERSION.split(".")[0], 10);
46
+ function isNodeVersionSupportedForCoverage() {
47
+ return NODE_MAJOR_VERSION >= 22;
48
+ }
49
+ function warnIfASCoverageNotSupportedByNode() {
50
+ if (!isNodeVersionSupportedForCoverage()) console.warn(`\n` + c.yellow(`Warning:`) + c.gray(` Coverage config is enabled, but current Node version (${versions.node})\n does not support required WASM multi-memory features.\n Coverage collection will be `) + c.yellow(`disabled`) + c.gray(" for AssemblyScript WASM.\n Please upgrade to Node 22 or above if you need WASM coverage support."));
51
+ }
52
+ /**
53
+ * Warn that the native instrumentation addon could not be loaded.
54
+ * Used by compiler threads for unexpected failures (no marker file present).
55
+ */
56
+ function warnASInstrumentationNotLoaded(errorMessage) {
57
+ console.warn(`\n` + c.yellow(`Warning:`) + c.gray(" Coverage config is enabled, but instrumentation native addon module\n was not loaded. Tests will run with " + c.yellow(`coverage disabled`) + `. Error:\n\n${errorMessage}`));
58
+ }
59
+ const ERROR_PREVIEW_MAX_LINES = 10;
60
+ /**
61
+ * Check for a native build error marker file and warn if present.
62
+ * Called once from the coverage provider (main process), so the warning
63
+ * is not duplicated across compiler threads.
64
+ */
65
+ async function warnIfNativeBuildFailed() {
66
+ const buildError = await readNativeBuildError();
67
+ if (!buildError) return;
68
+ try {
69
+ await import("./addon-interface-_pNXcbib.mjs");
70
+ await clearNativeBuildError();
71
+ return;
72
+ } catch {}
73
+ const stageName = buildError.stage === "binaryen-download" ? "Binaryen dependency download" : "native addon compilation";
74
+ const errorLines = buildError.error.split("\n");
75
+ const truncated = errorLines.length > ERROR_PREVIEW_MAX_LINES;
76
+ const preview = errorLines.slice(-ERROR_PREVIEW_MAX_LINES).join("\n");
77
+ console.warn(`\n` + c.yellow(`Warning:`) + c.gray(` Build failed during "${stageName}" while installing.\n`) + c.gray(` vitest-pool-assemblyscript. AssemblyScript tests will run,\n`) + c.gray(` but `) + c.yellow(`coverage will be disabled`) + c.gray(`. Platform: `) + c.yellowBright(`${buildError.platform}\n`) + c.gray(` Build Error Message:\n`) + `\n` + (truncated ? c.gray(`... (truncated)\n`) : ``) + c.redBright(`${preview}`) + "\n\n" + c.gray(` Full error details: `) + c.cyan(`${NATIVE_BUILD_ERROR_FILE}`) + "\n\n" + c.gray(` To resolve, inspect the error above, ensure a C++ compiler toolchain\n`) + c.gray(` is installed (`) + c.cyan(`https://github.com/nodejs/node-gyp#installation`) + c.gray(`)\n`) + c.gray(` and then reinstall: `) + c.cyan(`npm install vitest-pool-assemblyscript`) + `\n`);
78
+ }
79
+
80
+ //#endregion
81
+ export { clearNativeBuildError, hasNativeBuildError, isNodeVersionSupportedForCoverage, warnASInstrumentationNotLoaded, warnIfASCoverageNotSupportedByNode, warnIfNativeBuildFailed };
82
+ //# sourceMappingURL=feature-check-ELxw_Mji.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"feature-check-ELxw_Mji.mjs","names":[],"sources":["../src/util/feature-check.ts"],"sourcesContent":["import { versions } from 'node:process';\nimport { access, readFile, unlink } from 'node:fs/promises';\nimport { resolve, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport c from 'tinyrainbow';\n\nimport type { NativeBuildError } from '../types/types.js';\n\n// Marker file written by install script when native build fails\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\nconst packageRoot = resolve(__dirname, '..');\nconst NATIVE_BUILD_ERROR_FILE = resolve(packageRoot, '.native-build-error');\n\n/**\n * Read the native build error marker file if it exists.\n * Returns undefined if file doesn't exist or can't be parsed.\n */\nasync function readNativeBuildError(): Promise<NativeBuildError | undefined> {\n try {\n const content = await readFile(NATIVE_BUILD_ERROR_FILE, 'utf8');\n return JSON.parse(content) as NativeBuildError;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Check if a native build error marker file exists.\n * Used by compiler threads to distinguish known build failures (marker present,\n * user already warned by coverage provider) from unexpected addon load failures.\n */\nexport async function hasNativeBuildError(): Promise<boolean> {\n try {\n await access(NATIVE_BUILD_ERROR_FILE);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Remove the native build error marker file.\n * Called when the addon loads successfully at runtime, clearing any stale marker\n * left from a previous failed install (e.g. after a manual rebuild).\n */\nexport async function clearNativeBuildError(): Promise<void> {\n try {\n await unlink(NATIVE_BUILD_ERROR_FILE);\n } catch {\n // File doesn't exist or can't be removed — non-critical\n }\n}\n\nconst NODE_VERSION = versions.node;\nconst NODE_MAJOR_VERSION = parseInt(NODE_VERSION.split('.')[0]!, 10);\n\nexport function isNodeVersionSupportedForCoverage(): boolean {\n return NODE_MAJOR_VERSION >= 22;\n}\n\nexport function warnIfASCoverageNotSupportedByNode(): void {\n if (!isNodeVersionSupportedForCoverage()) {\n console.warn(`\\n`\n + c.yellow(`Warning:`)\n + c.gray(` Coverage config is enabled, but current Node version (${versions.node})\\n`\n + ` does not support required WASM multi-memory features.\\n`\n + ` Coverage collection will be `) + c.yellow(`disabled`) + c.gray(` for AssemblyScript WASM.\\n`\n + ` Please upgrade to Node 22 or above if you need WASM coverage support.`)\n );\n }\n}\n\n/**\n * Warn that the native instrumentation addon could not be loaded.\n * Used by compiler threads for unexpected failures (no marker file present).\n */\nexport function warnASInstrumentationNotLoaded(errorMessage: string): void {\n console.warn(`\\n`\n + c.yellow(`Warning:`)\n + c.gray(` Coverage config is enabled, but instrumentation native addon module\\n`\n + ` was not loaded. Tests will run with ` + c.yellow(`coverage disabled`) + `. Error:\\n\\n`\n + `${errorMessage}`)\n );\n}\n\nconst ERROR_PREVIEW_MAX_LINES = 10;\n\n/**\n * Check for a native build error marker file and warn if present.\n * Called once from the coverage provider (main process), so the warning\n * is not duplicated across compiler threads.\n */\nexport async function warnIfNativeBuildFailed(): Promise<void> {\n const buildError = await readNativeBuildError();\n if (!buildError) return;\n\n // Before warning, check if the addon actually loads (e.g. after a manual rebuild).\n // If it loads, the marker file is stale — clear it and skip the warning.\n try {\n await import('../instrumentation/addon-interface.js');\n await clearNativeBuildError();\n return;\n } catch {\n // Addon still can't load — proceed with warning\n }\n\n const stageName = buildError.stage === 'binaryen-download'\n ? 'Binaryen dependency download'\n : 'native addon compilation';\n\n // Truncate error for display, point to file for full details\n const errorLines = buildError.error.split('\\n');\n const truncated = errorLines.length > ERROR_PREVIEW_MAX_LINES;\n const preview = errorLines.slice(-ERROR_PREVIEW_MAX_LINES).join('\\n');\n\n console.warn(`\\n`\n + c.yellow(`Warning:`) + c.gray(` Build failed during \"${stageName}\" while installing.\\n`)\n + c.gray(` vitest-pool-assemblyscript. AssemblyScript tests will run,\\n`)\n + c.gray(` but `) + c.yellow(`coverage will be disabled`) + c.gray(`. Platform: `)\n + c.yellowBright(`${buildError.platform}\\n`)\n + c.gray(` Build Error Message:\\n`)\n + `\\n`\n + (truncated ? c.gray(`... (truncated)\\n`) : ``)+ c.redBright(`${preview}`) + `\\n`\n + `\\n`\n + c.gray(` Full error details: `) + c.cyan(`${NATIVE_BUILD_ERROR_FILE}`) + `\\n`\n + `\\n`\n + c.gray(` To resolve, inspect the error above, ensure a C++ compiler toolchain\\n`)\n + c.gray(` is installed (`) + c.cyan(`https://github.com/nodejs/node-gyp#installation`) + c.gray(`)\\n`)\n + c.gray(` and then reinstall: `) + c.cyan(`npm install vitest-pool-assemblyscript`)\n + `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