@5ive-tech/cli 1.0.4

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 (139) hide show
  1. package/README.md +226 -0
  2. package/dist/assets/vm/five_vm_wasm.d.ts +762 -0
  3. package/dist/assets/vm/five_vm_wasm.js +3754 -0
  4. package/dist/assets/vm/five_vm_wasm_bg.wasm +0 -0
  5. package/dist/assets/vm/five_vm_wasm_bg.wasm.d.ts +247 -0
  6. package/dist/assets/vm/package.json +11 -0
  7. package/dist/cli.d.ts +47 -0
  8. package/dist/cli.d.ts.map +1 -0
  9. package/dist/cli.js +343 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/commands/analyze.d.ts +3 -0
  12. package/dist/commands/analyze.d.ts.map +1 -0
  13. package/dist/commands/analyze.js +435 -0
  14. package/dist/commands/analyze.js.map +1 -0
  15. package/dist/commands/build.d.ts +3 -0
  16. package/dist/commands/build.d.ts.map +1 -0
  17. package/dist/commands/build.js +66 -0
  18. package/dist/commands/build.js.map +1 -0
  19. package/dist/commands/compile.d.ts +3 -0
  20. package/dist/commands/compile.d.ts.map +1 -0
  21. package/dist/commands/compile.js +872 -0
  22. package/dist/commands/compile.js.map +1 -0
  23. package/dist/commands/config.d.ts +3 -0
  24. package/dist/commands/config.d.ts.map +1 -0
  25. package/dist/commands/config.js +431 -0
  26. package/dist/commands/config.js.map +1 -0
  27. package/dist/commands/deploy-and-execute.d.ts +3 -0
  28. package/dist/commands/deploy-and-execute.d.ts.map +1 -0
  29. package/dist/commands/deploy-and-execute.js +317 -0
  30. package/dist/commands/deploy-and-execute.js.map +1 -0
  31. package/dist/commands/deploy.d.ts +21 -0
  32. package/dist/commands/deploy.d.ts.map +1 -0
  33. package/dist/commands/deploy.js +806 -0
  34. package/dist/commands/deploy.js.map +1 -0
  35. package/dist/commands/donate.d.ts +4 -0
  36. package/dist/commands/donate.d.ts.map +1 -0
  37. package/dist/commands/donate.js +104 -0
  38. package/dist/commands/donate.js.map +1 -0
  39. package/dist/commands/execute.d.ts +6 -0
  40. package/dist/commands/execute.d.ts.map +1 -0
  41. package/dist/commands/execute.js +749 -0
  42. package/dist/commands/execute.js.map +1 -0
  43. package/dist/commands/fmt.d.ts +3 -0
  44. package/dist/commands/fmt.d.ts.map +1 -0
  45. package/dist/commands/fmt.js +327 -0
  46. package/dist/commands/fmt.js.map +1 -0
  47. package/dist/commands/help.d.ts +6 -0
  48. package/dist/commands/help.d.ts.map +1 -0
  49. package/dist/commands/help.js +224 -0
  50. package/dist/commands/help.js.map +1 -0
  51. package/dist/commands/index.d.ts +45 -0
  52. package/dist/commands/index.d.ts.map +1 -0
  53. package/dist/commands/index.js +119 -0
  54. package/dist/commands/index.js.map +1 -0
  55. package/dist/commands/init.d.ts +3 -0
  56. package/dist/commands/init.d.ts.map +1 -0
  57. package/dist/commands/init.js +887 -0
  58. package/dist/commands/init.js.map +1 -0
  59. package/dist/commands/local.d.ts +3 -0
  60. package/dist/commands/local.d.ts.map +1 -0
  61. package/dist/commands/local.js +703 -0
  62. package/dist/commands/local.js.map +1 -0
  63. package/dist/commands/namespace.d.ts +3 -0
  64. package/dist/commands/namespace.d.ts.map +1 -0
  65. package/dist/commands/namespace.js +328 -0
  66. package/dist/commands/namespace.js.map +1 -0
  67. package/dist/commands/template.d.ts +4 -0
  68. package/dist/commands/template.d.ts.map +1 -0
  69. package/dist/commands/template.js +486 -0
  70. package/dist/commands/template.js.map +1 -0
  71. package/dist/commands/test.d.ts +6 -0
  72. package/dist/commands/test.d.ts.map +1 -0
  73. package/dist/commands/test.js +890 -0
  74. package/dist/commands/test.js.map +1 -0
  75. package/dist/commands/version.d.ts +6 -0
  76. package/dist/commands/version.d.ts.map +1 -0
  77. package/dist/commands/version.js +339 -0
  78. package/dist/commands/version.js.map +1 -0
  79. package/dist/config/ConfigManager.d.ts +69 -0
  80. package/dist/config/ConfigManager.d.ts.map +1 -0
  81. package/dist/config/ConfigManager.js +261 -0
  82. package/dist/config/ConfigManager.js.map +1 -0
  83. package/dist/config/index.d.ts +10 -0
  84. package/dist/config/index.d.ts.map +1 -0
  85. package/dist/config/index.js +21 -0
  86. package/dist/config/index.js.map +1 -0
  87. package/dist/config/types.d.ts +35 -0
  88. package/dist/config/types.d.ts.map +1 -0
  89. package/dist/config/types.js +105 -0
  90. package/dist/config/types.js.map +1 -0
  91. package/dist/index.d.ts +3 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +29 -0
  94. package/dist/index.js.map +1 -0
  95. package/dist/project/ProjectLoader.d.ts +12 -0
  96. package/dist/project/ProjectLoader.d.ts.map +1 -0
  97. package/dist/project/ProjectLoader.js +115 -0
  98. package/dist/project/ProjectLoader.js.map +1 -0
  99. package/dist/types.d.ts +334 -0
  100. package/dist/types.d.ts.map +1 -0
  101. package/dist/types.js +2 -0
  102. package/dist/types.js.map +1 -0
  103. package/dist/utils/AccountFixtureGenerator.d.ts +48 -0
  104. package/dist/utils/AccountFixtureGenerator.d.ts.map +1 -0
  105. package/dist/utils/AccountFixtureGenerator.js +265 -0
  106. package/dist/utils/AccountFixtureGenerator.js.map +1 -0
  107. package/dist/utils/FiveFileManager.d.ts +96 -0
  108. package/dist/utils/FiveFileManager.d.ts.map +1 -0
  109. package/dist/utils/FiveFileManager.js +329 -0
  110. package/dist/utils/FiveFileManager.js.map +1 -0
  111. package/dist/utils/ascii-art.d.ts +72 -0
  112. package/dist/utils/ascii-art.d.ts.map +1 -0
  113. package/dist/utils/ascii-art.js +314 -0
  114. package/dist/utils/ascii-art.js.map +1 -0
  115. package/dist/utils/cli-ui.d.ts +39 -0
  116. package/dist/utils/cli-ui.d.ts.map +1 -0
  117. package/dist/utils/cli-ui.js +75 -0
  118. package/dist/utils/cli-ui.js.map +1 -0
  119. package/dist/utils/fileUtils.d.ts +25 -0
  120. package/dist/utils/fileUtils.d.ts.map +1 -0
  121. package/dist/utils/fileUtils.js +50 -0
  122. package/dist/utils/fileUtils.js.map +1 -0
  123. package/dist/utils/logger.d.ts +53 -0
  124. package/dist/utils/logger.d.ts.map +1 -0
  125. package/dist/utils/logger.js +287 -0
  126. package/dist/utils/logger.js.map +1 -0
  127. package/dist/wasm/compiler.d.ts +101 -0
  128. package/dist/wasm/compiler.d.ts.map +1 -0
  129. package/dist/wasm/compiler.js +906 -0
  130. package/dist/wasm/compiler.js.map +1 -0
  131. package/dist/wasm/loader.d.ts +2 -0
  132. package/dist/wasm/loader.d.ts.map +1 -0
  133. package/dist/wasm/loader.js +90 -0
  134. package/dist/wasm/loader.js.map +1 -0
  135. package/dist/wasm/vm.d.ts +32 -0
  136. package/dist/wasm/vm.d.ts.map +1 -0
  137. package/dist/wasm/vm.js +440 -0
  138. package/dist/wasm/vm.js.map +1 -0
  139. package/package.json +100 -0
@@ -0,0 +1,906 @@
1
+ // Five compiler WASM integration.
2
+ import { readFile, writeFile } from "fs/promises";
3
+ import { ConfigManager } from "../config/ConfigManager.js";
4
+ import { createRequire } from "module";
5
+ const require = createRequire(import.meta.url);
6
+ // Real Five VM WASM imports
7
+ let WasmFiveCompiler;
8
+ let FiveVMWasm;
9
+ let BytecodeAnalyzer;
10
+ let WasmCompilationOptions;
11
+ let wasmModuleRef = null;
12
+ export class FiveCompilerWasm {
13
+ compiler = null;
14
+ logger;
15
+ initialized = false;
16
+ constructor(logger) {
17
+ this.logger = logger;
18
+ }
19
+ async initialize() {
20
+ try {
21
+ // Try multiple candidate locations (mirrors vm.ts logic)
22
+ const cfg = await ConfigManager.getInstance().get();
23
+ const prefer = cfg.wasm?.loader || "auto";
24
+ const configured = Array.isArray(cfg.wasm?.modulePaths)
25
+ ? cfg.wasm.modulePaths
26
+ : [];
27
+ const nodeCandidates = ["../../five_vm_wasm.js", "../five_vm_wasm.js"];
28
+ const bundlerCandidates = [
29
+ "../../assets/vm/five_vm_wasm.js",
30
+ "../assets/vm/five_vm_wasm.js",
31
+ ];
32
+ let candidates = [];
33
+ candidates.push(...configured);
34
+ if (prefer === "node") {
35
+ candidates.push(...nodeCandidates);
36
+ }
37
+ else if (prefer === "bundler") {
38
+ candidates.push(...bundlerCandidates);
39
+ }
40
+ else {
41
+ candidates.push(...nodeCandidates, ...bundlerCandidates);
42
+ }
43
+ let wasmModule = null;
44
+ const tried = [];
45
+ for (const candidate of candidates) {
46
+ try {
47
+ // Use require for Node.js CommonJS WASM modules
48
+ const mod = require(candidate);
49
+ // The Node.js target (wasm-pack --target nodejs) is pre-initialized
50
+ // No need to call initSync() - just check if it has the expected exports
51
+ if (mod &&
52
+ (mod.WasmFiveCompiler || mod.FiveCompilerWasm) &&
53
+ mod.FiveVMWasm) {
54
+ wasmModule = mod;
55
+ break;
56
+ }
57
+ if (!(mod.WasmFiveCompiler || mod.FiveCompilerWasm)) {
58
+ tried.push({ path: candidate, error: "Missing WasmFiveCompiler export" });
59
+ }
60
+ else if (!mod.FiveVMWasm) {
61
+ tried.push({ path: candidate, error: "Missing FiveVMWasm export" });
62
+ }
63
+ else {
64
+ tried.push({ path: candidate, error: "Module loaded but invalid" });
65
+ }
66
+ }
67
+ catch (e) {
68
+ tried.push({ path: candidate, error: e });
69
+ }
70
+ }
71
+ if (!wasmModule) {
72
+ const attempted = tried
73
+ .map((t) => ` - ${t.path}: ${t.error instanceof Error ? t.error.message : String(t.error)}`)
74
+ .join("\n");
75
+ throw new Error(`Failed to load WASM compiler module. Attempted:\n${attempted}`);
76
+ }
77
+ wasmModuleRef = wasmModule;
78
+ WasmFiveCompiler =
79
+ wasmModule.WasmFiveCompiler || wasmModule.FiveCompilerWasm;
80
+ FiveVMWasm = wasmModule.FiveVMWasm;
81
+ BytecodeAnalyzer = wasmModule.BytecodeAnalyzer;
82
+ WasmCompilationOptions = wasmModule.WasmCompilationOptions;
83
+ // Initialize the compiler instance
84
+ this.compiler = new WasmFiveCompiler();
85
+ this.initialized = true;
86
+ // WASM compiler initialized silently
87
+ }
88
+ catch (error) {
89
+ throw this.createCompilerError(`Five VM WASM modules not found. Please run "npm run build:wasm" to build the required WebAssembly modules. Error: ${error}`, error);
90
+ }
91
+ }
92
+ /**
93
+ * Compile Five DSL source code from string (SDK compatibility)
94
+ */
95
+ async compile(source, options) {
96
+ if (!this.initialized || !this.compiler) {
97
+ throw this.createCompilerError("Compiler not initialized");
98
+ }
99
+ const startTime = Date.now();
100
+ // Extract metrics configuration at top level for scope
101
+ const metricsFormat = options?.metricsFormat || "json";
102
+ try {
103
+ // Compile source silently
104
+ // Use enhanced WASM compiler methods with rich error messages
105
+ let result;
106
+ // Compile using WASM bindings
107
+ try {
108
+ // Use unified compilation method (module already loaded in initialize)
109
+ if (!WasmCompilationOptions && wasmModuleRef) {
110
+ WasmCompilationOptions = wasmModuleRef.WasmCompilationOptions;
111
+ }
112
+ // Enable metrics if explicitly requested via metricsFormat or metricsOutput
113
+ const includeMetrics = options?.includeMetrics || Boolean(options?.metricsOutput) || Boolean(options?.metricsFormat);
114
+ const errorFormat = options?.errorFormat || "terminal";
115
+ const comprehensiveMetrics = options?.comprehensiveMetrics || Boolean(options?.metricsOutput);
116
+ const compilationOptions = new WasmCompilationOptions()
117
+ .with_mode(options?.target || "deployment")
118
+ .with_optimization_level(options?.optimizationLevel || "production")
119
+ .with_v2_preview(true)
120
+ .with_constraint_cache(false)
121
+ .with_enhanced_errors(true)
122
+ .with_metrics(includeMetrics)
123
+ .with_comprehensive_metrics(comprehensiveMetrics)
124
+ .with_metrics_format(metricsFormat)
125
+ .with_error_format(errorFormat)
126
+ .with_module_namespaces(!Boolean(options?.flatNamespace));
127
+ // Execute compilation
128
+ result = this.compiler.compile(source, compilationOptions);
129
+ // Process compilation result silently
130
+ // Log compiler errors for debugging if present
131
+ if (result.compiler_errors && result.compiler_errors.length > 0) {
132
+ this.logger.debug(`WASM returned ${result.compiler_errors.length} compiler errors`);
133
+ for (const error of result.compiler_errors) {
134
+ this.logger.debug(`Compiler error details:`, error);
135
+ // Extract error details using WASM getters
136
+ try {
137
+ const message = error.message ? error.message : "No message";
138
+ const code = error.code ? error.code : "No code";
139
+ const severity = error.severity ? error.severity : "Unknown";
140
+ const category = error.category ? error.category : "Unknown";
141
+ this.logger.error(`Detailed error: [${code}] ${severity} - ${message}`);
142
+ this.logger.error(`Category: ${category}`);
143
+ // Try to get location information
144
+ if (error.location) {
145
+ const location = error.location;
146
+ this.logger.error(`Location: line ${location.line}, column ${location.column}`);
147
+ }
148
+ }
149
+ catch (e) {
150
+ this.logger.debug(`Failed to extract error details:`, e);
151
+ this.logger.debug(`Raw error object:`, error);
152
+ }
153
+ }
154
+ }
155
+ }
156
+ catch (wasmError) {
157
+ this.logger.debug("WASM compilation threw an error:", wasmError);
158
+ throw wasmError;
159
+ }
160
+ const metricsPayload = this.extractMetrics(result, metricsFormat);
161
+ // Transform result format to match expected SDK interface
162
+ if (result.success && result.bytecode) {
163
+ return {
164
+ success: true,
165
+ bytecode: result.bytecode,
166
+ abi: this.extractAbi(result),
167
+ metadata: result.metadata,
168
+ metrics: metricsPayload,
169
+ metricsReport: metricsPayload,
170
+ formattedErrorsTerminal: typeof result.format_all_terminal === "function" ? result.format_all_terminal() : (result.formatted_errors_terminal || undefined),
171
+ formattedErrorsJson: typeof result.format_all_json === "function" ? result.format_all_json() : (result.formatted_errors_json || undefined),
172
+ };
173
+ }
174
+ else {
175
+ return {
176
+ success: false,
177
+ errors: result.compiler_errors || [],
178
+ metadata: result.metadata,
179
+ metrics: metricsPayload,
180
+ metricsReport: metricsPayload,
181
+ formattedErrorsTerminal: typeof result.format_all_terminal === "function" ? result.format_all_terminal() : (result.formatted_errors_terminal || undefined),
182
+ formattedErrorsJson: typeof result.format_all_json === "function" ? result.format_all_json() : (result.formatted_errors_json || undefined),
183
+ };
184
+ }
185
+ }
186
+ catch (error) {
187
+ throw this.createCompilerError(`Compilation error: ${error instanceof Error ? error.message : "Unknown error"}`, error);
188
+ }
189
+ }
190
+ /**
191
+ * Compile multiple modules (main + dependencies)
192
+ */
193
+ async compileModules(mainSource, modules, options, mainFileName = "input.v") {
194
+ if (!this.initialized || !this.compiler) {
195
+ throw this.createCompilerError("Compiler not initialized");
196
+ }
197
+ const startTime = Date.now();
198
+ try {
199
+ if (!WasmCompilationOptions && wasmModuleRef) {
200
+ WasmCompilationOptions = wasmModuleRef.WasmCompilationOptions;
201
+ }
202
+ const metricsFormat = options?.metricsFormat || "json";
203
+ const includeMetrics = options?.includeMetrics || Boolean(options?.metricsOutput);
204
+ const errorFormat = options?.errorFormat || "terminal";
205
+ const comprehensiveMetrics = options?.comprehensiveMetrics || false;
206
+ const compilationOptions = new WasmCompilationOptions()
207
+ .with_mode(options?.target || "deployment")
208
+ .with_optimization_level(options?.optimizationLevel || "production")
209
+ .with_v2_preview(true)
210
+ .with_constraint_cache(false)
211
+ .with_enhanced_errors(true)
212
+ .with_metrics(includeMetrics)
213
+ .with_comprehensive_metrics(comprehensiveMetrics)
214
+ .with_metrics_format(metricsFormat)
215
+ .with_error_format(errorFormat)
216
+ .with_module_namespaces(!Boolean(options?.flatNamespace))
217
+ .with_source_file(mainFileName);
218
+ // Map JS module structure (source) to Rust module structure (content)
219
+ const rustModules = modules.map(m => ({
220
+ name: m.name,
221
+ // Rust deserializer expects 'content' field
222
+ content: m.source
223
+ }));
224
+ const result = this.compiler.compile_multi(mainSource, rustModules, compilationOptions);
225
+ const metricsPayload = this.extractMetrics(result, metricsFormat);
226
+ if (result.success && result.bytecode) {
227
+ return {
228
+ success: true,
229
+ bytecode: result.bytecode,
230
+ abi: this.extractAbi(result),
231
+ metadata: result.metadata,
232
+ metrics: metricsPayload,
233
+ metricsReport: metricsPayload,
234
+ };
235
+ }
236
+ else {
237
+ return {
238
+ success: false,
239
+ errors: result.compiler_errors || [],
240
+ formattedErrorsTerminal: typeof result.format_all_terminal === "function" ? result.format_all_terminal() : result.formatted_errors_terminal,
241
+ formattedErrorsJson: typeof result.format_all_json === "function" ? result.format_all_json() : result.formatted_errors_json,
242
+ metadata: result.metadata,
243
+ metrics: metricsPayload,
244
+ metricsReport: metricsPayload,
245
+ };
246
+ }
247
+ }
248
+ catch (error) {
249
+ throw this.createCompilerError(`Compilation error: ${error instanceof Error ? error.message : "Unknown error"}`, error);
250
+ }
251
+ finally {
252
+ const compilationTime = Date.now() - startTime;
253
+ this.logger.debug(`Multi-file compilation completed in ${compilationTime}ms`);
254
+ }
255
+ }
256
+ /**
257
+ * Compile Five DSL source code from file (CLI compatibility)
258
+ */
259
+ async compileFile(options) {
260
+ if (!this.initialized || !this.compiler) {
261
+ throw this.createCompilerError("Compiler not initialized");
262
+ }
263
+ const startTime = Date.now();
264
+ // Extract metrics configuration at top level for scope
265
+ const metricsFormat = options.metricsFormat || "json";
266
+ try {
267
+ // Read source file
268
+ const sourceCode = await readFile(options.sourceFile, "utf8");
269
+ this.logger.debug(`Compiling source file: ${options.sourceFile}`);
270
+ // Use enhanced WASM compiler methods with rich error messages
271
+ let result;
272
+ // Compile using WASM bindings
273
+ try {
274
+ // Use unified compilation method (module already loaded in initialize)
275
+ if (!WasmCompilationOptions && wasmModuleRef) {
276
+ WasmCompilationOptions = wasmModuleRef.WasmCompilationOptions;
277
+ }
278
+ // Enable metrics if explicitly requested via metricsFormat or metricsOutput
279
+ const includeMetrics = options.includeMetrics || Boolean(options.metricsOutput) || Boolean(options.metricsFormat);
280
+ const errorFormat = options.errorFormat || "terminal";
281
+ const comprehensiveMetrics = options.comprehensiveMetrics || Boolean(options.metricsOutput);
282
+ const compilationOptions = new WasmCompilationOptions()
283
+ .with_mode(options.target || "deployment")
284
+ .with_optimization_level(options.optimizationLevel || "production")
285
+ .with_v2_preview(true)
286
+ .with_constraint_cache(options.enable_constraint_cache !== false)
287
+ .with_enhanced_errors(true)
288
+ .with_metrics(includeMetrics)
289
+ .with_comprehensive_metrics(comprehensiveMetrics)
290
+ .with_metrics_format(metricsFormat)
291
+ .with_error_format(errorFormat)
292
+ .with_source_file(options.sourceFile);
293
+ // Execute compilation
294
+ result = this.compiler.compile(sourceCode, compilationOptions);
295
+ // Process compilation result silently
296
+ // Log compiler errors for debugging if present
297
+ if (result.compiler_errors && result.compiler_errors.length > 0) {
298
+ this.logger.debug(`WASM returned ${result.compiler_errors.length} compiler errors`);
299
+ for (const error of result.compiler_errors) {
300
+ this.logger.debug(`Compiler error details:`, error);
301
+ // Extract error details using WASM getters
302
+ try {
303
+ const message = error.message ? error.message : "No message";
304
+ const code = error.code ? error.code : "No code";
305
+ const severity = error.severity ? error.severity : "Unknown";
306
+ const category = error.category ? error.category : "Unknown";
307
+ this.logger.error(`Detailed error: [${code}] ${severity} - ${message}`);
308
+ this.logger.error(`Category: ${category}`);
309
+ // Try to get location information
310
+ if (error.location) {
311
+ const location = error.location;
312
+ this.logger.error(`Location: line ${location.line}, column ${location.column}`);
313
+ }
314
+ }
315
+ catch (e) {
316
+ this.logger.debug(`Failed to extract error details:`, e);
317
+ this.logger.debug(`Raw error object:`, error);
318
+ }
319
+ }
320
+ }
321
+ }
322
+ catch (wasmError) {
323
+ this.logger.error("WASM compiler threw exception:", wasmError);
324
+ // If WASM throws exception, create a structured error response
325
+ result = {
326
+ success: false,
327
+ bytecode: null,
328
+ bytecode_size: 0,
329
+ compilation_time: 0,
330
+ compiler_errors: [
331
+ {
332
+ code: "E9999",
333
+ severity: "error",
334
+ category: "wasm_exception",
335
+ message: wasmError instanceof Error
336
+ ? wasmError.message
337
+ : String(wasmError),
338
+ description: "WASM compiler threw an exception",
339
+ location: null,
340
+ suggestions: [],
341
+ },
342
+ ],
343
+ error_count: 1,
344
+ warning_count: 0,
345
+ };
346
+ }
347
+ // Check if compilation failed but we have enhanced error information
348
+ if (!result.success &&
349
+ result.compiler_errors &&
350
+ result.compiler_errors.length > 0) {
351
+ // Handle compilation errors
352
+ // Log enhanced error details using WASM formatting methods
353
+ this.logger.debug(`Enhanced Error Count: ${result.error_count}`);
354
+ // Try to get formatted output from WASM
355
+ try {
356
+ const terminalOutput = result.format_all_terminal
357
+ ? result.format_all_terminal()
358
+ : null;
359
+ if (terminalOutput) {
360
+ this.logger.debug("Terminal formatted errors:", terminalOutput);
361
+ }
362
+ const jsonOutput = result.format_all_json
363
+ ? result.format_all_json()
364
+ : null;
365
+ if (jsonOutput) {
366
+ this.logger.debug("JSON formatted errors:", jsonOutput);
367
+ }
368
+ }
369
+ catch (formatError) {
370
+ this.logger.debug("Failed to get formatted errors:", formatError);
371
+ }
372
+ }
373
+ const compilationTime = Date.now() - startTime;
374
+ const metricsPayload = this.extractMetrics(result, metricsFormat);
375
+ // Use WASM-provided formatting methods to get structured error information
376
+ let convertedErrors = [];
377
+ if (result.compiler_errors && result.compiler_errors.length > 0) {
378
+ try {
379
+ // Try to get JSON formatted errors from WASM
380
+ const jsonErrors = result.format_all_json
381
+ ? result.format_all_json()
382
+ : null;
383
+ if (jsonErrors) {
384
+ const parsedErrors = JSON.parse(jsonErrors);
385
+ convertedErrors = parsedErrors.map((error) => ({
386
+ type: "enhanced",
387
+ ...error,
388
+ // Ensure proper structure for CLI display
389
+ code: error.code || "E0000",
390
+ severity: error.severity || "error",
391
+ category: error.category || "compilation",
392
+ message: error.message || "Unknown error",
393
+ }));
394
+ }
395
+ else {
396
+ // Fallback: create basic errors from the result
397
+ convertedErrors = [
398
+ {
399
+ type: "enhanced",
400
+ code: "E0004",
401
+ severity: "error",
402
+ category: "compilation",
403
+ message: "InvalidScript",
404
+ description: "The script contains syntax or semantic errors",
405
+ location: undefined,
406
+ suggestions: [],
407
+ },
408
+ ];
409
+ }
410
+ }
411
+ catch (parseError) {
412
+ this.logger.debug("Failed to parse JSON errors from WASM:", parseError);
413
+ // Fallback to basic error
414
+ convertedErrors = [
415
+ {
416
+ type: "enhanced",
417
+ code: "E0004",
418
+ severity: "error",
419
+ category: "compilation",
420
+ message: "InvalidScript",
421
+ description: "Compilation failed with enhanced error system",
422
+ location: undefined,
423
+ suggestions: [],
424
+ },
425
+ ];
426
+ }
427
+ }
428
+ // Extract ABI - get_abi() returns JSON string, parse it
429
+ let abi = undefined;
430
+ try {
431
+ const abiJson = result.get_abi();
432
+ if (abiJson) {
433
+ abi = JSON.parse(abiJson);
434
+ }
435
+ }
436
+ catch (e) {
437
+ this.logger.debug('Failed to parse ABI from get_abi():', e);
438
+ }
439
+ const compilationResult = {
440
+ success: result.success,
441
+ bytecode: result.bytecode ? new Uint8Array(result.bytecode) : undefined,
442
+ abi: abi,
443
+ errors: convertedErrors,
444
+ warnings: convertedErrors.filter((e) => e.severity === "warning") || [],
445
+ metrics: {
446
+ compilationTime: result.compilation_time || compilationTime,
447
+ bytecodeSize: result.bytecode_size || 0,
448
+ memoryUsed: 0, // Not available from WASM
449
+ optimizationTime: 0,
450
+ instructionCount: 0, // Would need analysis
451
+ functionCount: 0, // Would need analysis
452
+ },
453
+ metricsReport: metricsPayload,
454
+ formattedErrorsTerminal: typeof result.format_all_terminal === "function" ? result.format_all_terminal() : (result.formatted_errors_terminal || undefined),
455
+ formattedErrorsJson: typeof result.format_all_json === "function" ? result.format_all_json() : (result.formatted_errors_json || undefined),
456
+ };
457
+ // Write output file if specified and compilation succeeded
458
+ if (options.outputFile && compilationResult.bytecode) {
459
+ await writeFile(options.outputFile, compilationResult.bytecode);
460
+ this.logger.debug(`Bytecode written to: ${options.outputFile}`);
461
+ }
462
+ // Write ABI file if generated
463
+ if (options.abiOutputFile && compilationResult.abi) {
464
+ await writeFile(options.abiOutputFile, JSON.stringify(compilationResult.abi, null, 2));
465
+ this.logger.debug(`ABI written to: ${options.abiOutputFile}`);
466
+ }
467
+ this.logger.debug(`Compilation completed in ${compilationTime}ms`);
468
+ return compilationResult;
469
+ }
470
+ catch (error) {
471
+ const compilationTime = Date.now() - startTime;
472
+ return {
473
+ success: false,
474
+ errors: [
475
+ {
476
+ type: "runtime",
477
+ message: error instanceof Error ? error.message : String(error),
478
+ sourceLocation: options.sourceFile,
479
+ },
480
+ ],
481
+ warnings: [],
482
+ metrics: {
483
+ compilationTime,
484
+ memoryUsed: 0,
485
+ optimizationTime: 0,
486
+ bytecodeSize: 0,
487
+ instructionCount: 0,
488
+ functionCount: 0,
489
+ },
490
+ };
491
+ }
492
+ }
493
+ /**
494
+ * Generate ABI from DSL source using real WASM compiler
495
+ */
496
+ async generateABI(sourceCode) {
497
+ if (!this.initialized || !this.compiler) {
498
+ throw this.createCompilerError("Compiler not initialized");
499
+ }
500
+ try {
501
+ const abi = this.compiler.generate_abi(sourceCode);
502
+ return JSON.parse(abi);
503
+ }
504
+ catch (error) {
505
+ throw this.createCompilerError("ABI generation failed", error);
506
+ }
507
+ }
508
+ /**
509
+ * Validate DSL syntax using real WASM compiler
510
+ */
511
+ async validateSource(sourceCode) {
512
+ if (!this.initialized || !this.compiler) {
513
+ throw this.createCompilerError("Compiler not initialized");
514
+ }
515
+ try {
516
+ const result = this.compiler.validate_syntax(sourceCode);
517
+ return JSON.parse(result);
518
+ }
519
+ catch (error) {
520
+ throw this.createCompilerError("Syntax validation failed", error);
521
+ }
522
+ }
523
+ /**
524
+ * Optimize bytecode using real WASM optimizer
525
+ */
526
+ async optimizeBytecode(bytecode) {
527
+ if (!this.initialized || !this.compiler) {
528
+ throw this.createCompilerError("Compiler not initialized");
529
+ }
530
+ try {
531
+ const optimized = this.compiler.optimize_bytecode(bytecode);
532
+ return new Uint8Array(optimized);
533
+ }
534
+ catch (error) {
535
+ throw this.createCompilerError("Bytecode optimization failed", error);
536
+ }
537
+ }
538
+ /**
539
+ * Analyze bytecode using real WASM analyzer
540
+ */
541
+ async analyzeBytecode(bytecode) {
542
+ if (!this.initialized) {
543
+ throw this.createCompilerError("Compiler not initialized");
544
+ }
545
+ try {
546
+ // Use semantic analysis for detailed information
547
+ const analysis = BytecodeAnalyzer.analyze_semantic(bytecode);
548
+ return JSON.parse(analysis);
549
+ }
550
+ catch (error) {
551
+ throw this.createCompilerError("Bytecode analysis failed", error);
552
+ }
553
+ }
554
+ /**
555
+ * Get detailed instruction analysis at specific offset
556
+ */
557
+ async analyzeInstructionAt(bytecode, offset) {
558
+ if (!this.initialized) {
559
+ throw this.createCompilerError("Compiler not initialized");
560
+ }
561
+ try {
562
+ const instruction = BytecodeAnalyzer.analyze_instruction_at(bytecode, offset);
563
+ return JSON.parse(instruction);
564
+ }
565
+ catch (error) {
566
+ throw this.createCompilerError("Instruction analysis failed", error);
567
+ }
568
+ }
569
+ /**
570
+ * Get bytecode summary statistics
571
+ */
572
+ async getBytecodeStats(bytecode) {
573
+ if (!this.initialized) {
574
+ throw this.createCompilerError("Compiler not initialized");
575
+ }
576
+ try {
577
+ const stats = BytecodeAnalyzer.get_bytecode_summary(bytecode);
578
+ return JSON.parse(stats);
579
+ }
580
+ catch (error) {
581
+ throw this.createCompilerError("Bytecode stats failed", error);
582
+ }
583
+ }
584
+ /**
585
+ * Extract account definitions from DSL source
586
+ */
587
+ async extractAccountDefinitions(sourceCode) {
588
+ if (!this.initialized || !this.compiler) {
589
+ throw this.createCompilerError("Compiler not initialized");
590
+ }
591
+ try {
592
+ const definitions = this.compiler.extract_account_definitions(sourceCode);
593
+ return JSON.parse(definitions);
594
+ }
595
+ catch (error) {
596
+ throw this.createCompilerError("Account definition extraction failed", error);
597
+ }
598
+ }
599
+ /**
600
+ * Extract function signatures from DSL source
601
+ */
602
+ async extractFunctionSignatures(sourceCode) {
603
+ if (!this.initialized || !this.compiler) {
604
+ throw this.createCompilerError("Compiler not initialized");
605
+ }
606
+ try {
607
+ const signatures = this.compiler.extract_function_signatures(sourceCode);
608
+ return JSON.parse(signatures);
609
+ }
610
+ catch (error) {
611
+ throw this.createCompilerError("Function signature extraction failed", error);
612
+ }
613
+ }
614
+ /**
615
+ * Validate account constraints
616
+ */
617
+ async validateAccountConstraints(sourceCode, functionName, accounts) {
618
+ if (!this.initialized || !this.compiler) {
619
+ throw this.createCompilerError("Compiler not initialized");
620
+ }
621
+ try {
622
+ const accountsJson = JSON.stringify(accounts);
623
+ const validation = this.compiler.validate_account_constraints(sourceCode, functionName, accountsJson);
624
+ return JSON.parse(validation);
625
+ }
626
+ catch (error) {
627
+ throw this.createCompilerError("Account constraint validation failed", error);
628
+ }
629
+ }
630
+ /**
631
+ * Get compiler version and capabilities from real WASM
632
+ */
633
+ getCompilerInfo() {
634
+ if (!this.initialized || !this.compiler) {
635
+ throw this.createCompilerError("Compiler not initialized");
636
+ }
637
+ try {
638
+ const info = this.compiler.get_compiler_stats();
639
+ return JSON.parse(info);
640
+ }
641
+ catch (error) {
642
+ throw this.createCompilerError("Failed to get compiler info", error);
643
+ }
644
+ }
645
+ /**
646
+ * Create a standardized compiler error
647
+ */
648
+ createCompilerError(message, cause) {
649
+ const error = new Error(message);
650
+ error.name = "CompilerError";
651
+ error.code = "COMPILER_ERROR";
652
+ error.category = "wasm";
653
+ error.exitCode = 1;
654
+ if (cause) {
655
+ error.details = {
656
+ cause: cause.message,
657
+ stack: cause.stack,
658
+ };
659
+ }
660
+ return error;
661
+ }
662
+ extractAbi(result) {
663
+ if (!result) {
664
+ return undefined;
665
+ }
666
+ if (typeof result.get_abi === "function") {
667
+ try {
668
+ const abiJson = result.get_abi();
669
+ if (abiJson) {
670
+ return JSON.parse(abiJson);
671
+ }
672
+ }
673
+ catch (error) {
674
+ this.logger.debug("Failed to parse ABI from get_abi():", error);
675
+ }
676
+ }
677
+ const directAbi = result.abi;
678
+ if (!directAbi) {
679
+ return undefined;
680
+ }
681
+ if (typeof directAbi === "string") {
682
+ try {
683
+ return JSON.parse(directAbi);
684
+ }
685
+ catch (error) {
686
+ this.logger.debug("Failed to parse ABI from result.abi string:", error);
687
+ return undefined;
688
+ }
689
+ }
690
+ return directAbi;
691
+ }
692
+ /**
693
+ * Get opcode usage statistics from compilation
694
+ */
695
+ async getOpcodeUsage(sourceCode) {
696
+ if (!this.initialized || !this.compiler) {
697
+ throw this.createCompilerError("Compiler not initialized");
698
+ }
699
+ try {
700
+ const usage = this.compiler.get_opcode_usage(sourceCode);
701
+ return JSON.parse(usage);
702
+ }
703
+ catch (error) {
704
+ throw this.createCompilerError("Opcode usage analysis failed", error);
705
+ }
706
+ }
707
+ /**
708
+ * Get comprehensive opcode analysis showing used vs unused opcodes
709
+ */
710
+ async getOpcodeAnalysis(sourceCode) {
711
+ if (!this.initialized || !this.compiler) {
712
+ throw this.createCompilerError("Compiler not initialized");
713
+ }
714
+ try {
715
+ const analysis = this.compiler.get_opcode_analysis(sourceCode);
716
+ return JSON.parse(analysis);
717
+ }
718
+ catch (error) {
719
+ throw this.createCompilerError("Comprehensive opcode analysis failed", error);
720
+ }
721
+ }
722
+ /**
723
+ * Discover modules starting from entry point (tooling support)
724
+ */
725
+ async discoverModules(entryPoint) {
726
+ if (!this.initialized || !this.compiler) {
727
+ throw this.createCompilerError("Compiler not initialized");
728
+ }
729
+ try {
730
+ return this.compiler.discoverModules(entryPoint);
731
+ }
732
+ catch (error) {
733
+ throw this.createCompilerError(`Module discovery failed: ${error instanceof Error ? error.message : String(error)}`, error);
734
+ }
735
+ }
736
+ /**
737
+ * Compile multi-file project with automatic discovery
738
+ */
739
+ async compileWithDiscovery(entryPoint, options) {
740
+ if (!this.initialized || !this.compiler) {
741
+ throw this.createCompilerError("Compiler not initialized");
742
+ }
743
+ const startTime = Date.now();
744
+ const metricsFormat = options?.metricsFormat || "json";
745
+ try {
746
+ if (!WasmCompilationOptions && wasmModuleRef) {
747
+ WasmCompilationOptions = wasmModuleRef.WasmCompilationOptions;
748
+ }
749
+ const includeMetrics = options?.includeMetrics || Boolean(options?.metricsOutput);
750
+ const errorFormat = options?.errorFormat || "terminal";
751
+ const comprehensiveMetrics = options?.comprehensiveMetrics || false;
752
+ const compilationOptions = new WasmCompilationOptions()
753
+ .with_mode(options?.target || "deployment")
754
+ .with_optimization_level(options?.optimizationLevel || "production")
755
+ .with_v2_preview(true)
756
+ .with_constraint_cache(false)
757
+ .with_enhanced_errors(true)
758
+ .with_metrics(includeMetrics)
759
+ .with_comprehensive_metrics(comprehensiveMetrics)
760
+ .with_metrics_format(metricsFormat)
761
+ .with_error_format(errorFormat)
762
+ .with_module_namespaces(!Boolean(options?.flatNamespace))
763
+ .with_source_file(entryPoint);
764
+ const result = this.compiler.compileMultiWithDiscovery(entryPoint, compilationOptions);
765
+ const metricsPayload = this.extractMetrics(result, metricsFormat);
766
+ if (result.success && result.bytecode) {
767
+ // Extract ABI - get_abi() returns JSON string, parse it
768
+ let abi = undefined;
769
+ try {
770
+ const abiJson = result.get_abi();
771
+ if (abiJson) {
772
+ abi = JSON.parse(abiJson);
773
+ }
774
+ }
775
+ catch (e) {
776
+ this.logger.debug('Failed to parse ABI from get_abi():', e);
777
+ }
778
+ return {
779
+ success: true,
780
+ bytecode: result.bytecode,
781
+ abi: abi,
782
+ metadata: result.metadata,
783
+ metrics: metricsPayload,
784
+ metricsReport: metricsPayload,
785
+ };
786
+ }
787
+ else {
788
+ return {
789
+ success: false,
790
+ errors: result.compiler_errors || [],
791
+ formattedErrorsTerminal: typeof result.format_all_terminal === "function" ? result.format_all_terminal() : result.formatted_errors_terminal,
792
+ formattedErrorsJson: typeof result.format_all_json === "function" ? result.format_all_json() : result.formatted_errors_json,
793
+ metadata: result.metadata,
794
+ metrics: metricsPayload,
795
+ metricsReport: metricsPayload,
796
+ };
797
+ }
798
+ }
799
+ catch (error) {
800
+ throw this.createCompilerError(`Compilation error: ${error instanceof Error ? error.message : "Unknown error"}`, error);
801
+ }
802
+ }
803
+ /**
804
+ * Compile multi-file project with explicit module list (paths)
805
+ */
806
+ async compileModulesExplicit(moduleFiles, entryPoint, options) {
807
+ if (!this.initialized || !this.compiler) {
808
+ throw this.createCompilerError("Compiler not initialized");
809
+ }
810
+ const startTime = Date.now();
811
+ const metricsFormat = options?.metricsFormat || "json";
812
+ try {
813
+ if (!WasmCompilationOptions && wasmModuleRef) {
814
+ WasmCompilationOptions = wasmModuleRef.WasmCompilationOptions;
815
+ }
816
+ const includeMetrics = options?.includeMetrics || Boolean(options?.metricsOutput);
817
+ const errorFormat = options?.errorFormat || "terminal";
818
+ const comprehensiveMetrics = options?.comprehensiveMetrics || false;
819
+ const compilationOptions = new WasmCompilationOptions()
820
+ .with_mode(options?.target || "deployment")
821
+ .with_optimization_level(options?.optimizationLevel || "production")
822
+ .with_v2_preview(true)
823
+ .with_constraint_cache(false)
824
+ .with_enhanced_errors(true)
825
+ .with_metrics(includeMetrics)
826
+ .with_comprehensive_metrics(comprehensiveMetrics)
827
+ .with_metrics_format(metricsFormat)
828
+ .with_error_format(errorFormat)
829
+ .with_module_namespaces(!Boolean(options?.flatNamespace))
830
+ .with_source_file(entryPoint);
831
+ const result = this.compiler.compileModules(moduleFiles, entryPoint, compilationOptions);
832
+ const metricsPayload = this.extractMetrics(result, metricsFormat);
833
+ if (result.success && result.bytecode) {
834
+ // Extract ABI - get_abi() returns JSON string, parse it
835
+ let abi = undefined;
836
+ try {
837
+ const abiJson = result.get_abi();
838
+ if (abiJson) {
839
+ abi = JSON.parse(abiJson);
840
+ }
841
+ }
842
+ catch (e) {
843
+ this.logger.debug('Failed to parse ABI from get_abi():', e);
844
+ }
845
+ return {
846
+ success: true,
847
+ bytecode: result.bytecode,
848
+ abi: abi,
849
+ metadata: result.metadata,
850
+ metrics: metricsPayload,
851
+ metricsReport: metricsPayload,
852
+ };
853
+ }
854
+ else {
855
+ return {
856
+ success: false,
857
+ errors: result.compiler_errors || [],
858
+ metadata: result.metadata,
859
+ metrics: metricsPayload,
860
+ metricsReport: metricsPayload,
861
+ };
862
+ }
863
+ }
864
+ catch (error) {
865
+ throw this.createCompilerError(`Compilation error: ${error instanceof Error ? error.message : "Unknown error"}`, error);
866
+ }
867
+ }
868
+ extractMetrics(result, defaultFormat) {
869
+ if (!result || typeof result !== "object") {
870
+ return undefined;
871
+ }
872
+ const exported = result.metrics;
873
+ if (!exported) {
874
+ return undefined;
875
+ }
876
+ const format = result.metrics_format || defaultFormat;
877
+ let detailed;
878
+ try {
879
+ const getDetailed = result.get_metrics_detailed;
880
+ if (typeof getDetailed === "function") {
881
+ detailed = getDetailed.call(result);
882
+ }
883
+ else {
884
+ const getObject = result.get_metrics_object;
885
+ if (typeof getObject === "function") {
886
+ detailed = getObject.call(result);
887
+ }
888
+ }
889
+ }
890
+ catch (metricError) {
891
+ // Ignore metrics errors
892
+ }
893
+ return {
894
+ format,
895
+ exported,
896
+ detailed,
897
+ };
898
+ }
899
+ /**
900
+ * Check if compiler is ready
901
+ */
902
+ isReady() {
903
+ return this.initialized && this.compiler !== null;
904
+ }
905
+ }
906
+ //# sourceMappingURL=compiler.js.map