diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index af9f253..7d1e243 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -21,19 +21,6 @@ jobs: npx --yes wait-on tcp:4001 -t 30000 audit-script: | npm run audit - pull_request_debug_package: - uses: makerxstudio/shared-config/.github/workflows/node-ci.yml@main - with: - node-version: 18.x - working-directory: ./debug-utils - run-commit-lint: true - run-build: true - pre-test-script: | - pipx install algokit - algokit localnet start - npx --yes wait-on tcp:4001 -t 30000 - audit-script: | - npm run audit check_docs: runs-on: ubuntu-latest steps: diff --git a/.prettierignore b/.prettierignore index 72717bb..e2ce3dd 100644 --- a/.prettierignore +++ b/.prettierignore @@ -12,5 +12,3 @@ coverage .idea # don't format auto generated code docs docs/code -# don't format test contract artifacts -tests/example-contracts/**/*.json diff --git a/README.md b/README.md index 342f20e..02fa70f 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,30 @@ -# AlgoKit TypeScript Utilities +# AlgoKit TypeScript AVM Debugging Utilities -A set of core Algorand utilities written in TypeScript and released via npm that make it easier to build solutions on Algorand. This project is part of [AlgoKit](https://github.com/algorandfoundation/algokit-cli). +An optional addon package for [algokit-utils-ts](https://github.com/algorandfoundation/algokit-utils-ts) that provides **node** specific utilities that automatically gather artifacts required for instantiating [AlgoKit AVM VSCode Debugger Extension](https://github.com/algorandfoundation/algokit-avm-vscode-debugger). This project is part of [AlgoKit](https://github.com/algorandfoundation/algokit-cli). -The goal of this library is to provide intuitive, productive utility functions that make it easier, quicker and safer to build applications on Algorand. Largely these functions wrap the underlying Algorand SDK, but provide a higher level interface with sensible defaults and capabilities for common tasks. +Note: [Python's version of algokit-utils](https://github.com/algorandfoundation/algokit-utils-py) contains the same functionality without requiring a separate package install. Consider using that if you are building your AlgoKit project in Python. -Note: If you prefer Python there's an equivalent [Python utility library](https://github.com/algorandfoundation/algokit-utils-py). - -[Install](#install) | [Documentation](docs/README.md) +[Install](#install) | [Documentation](docs/code/README.md) ## Install This library can be installed from NPM using your favourite npm client, e.g.: ``` -npm install @algorandfoundation/algokit-utils +npm install @algorandfoundation/algokit-utils-debug ``` -Then to import it: +Then to import it and activate `utils-ts` debugging: ```typescript -import { AlgorandClient, Config } from '@algorandfoundation/algokit-utils' +import { Config } from '@algorandfoundation/algokit-utils' +import { registerDebugHandlers } from '@algorandfoundation/algokit-utils-debug' + +Config.configure({ + debug: true, + traceAll: true, // optional, defaults to ignoring simulate on successfull transactions. +}) +registerDebugHandlers() // must be called before any transactions are submitted. ``` See [usage](./docs/README.md#usage) for more. @@ -28,28 +33,6 @@ See [usage](./docs/README.md#usage) for more. This library follows the [Guiding Principles of AlgoKit](https://github.com/algorandfoundation/algokit-cli/blob/main/docs/algokit.md#guiding-principles). -## NextJS compatibility - -`algokit-utils-ts` has a set of `node` specific utilities used for simplifying aggregation of artifacts for [AlgoKit VSCode Debugger Extension](https://github.com/algorandfoundation/algokit-avm-vscode-debugger). Which causes Next.js based projects to fail on `fs` module not found. To fix this issue, you can add the following to your `next.config.js` file: - -```js - webpack: (config, { isServer }) => { - // Fix for Module not found: Can't resolve 'fs' - if (!isServer) { - config.resolve.fallback.fs = false; - } - return config; - }, -``` - -The root cause is due to the fact that, unlike many frameworks, Next.js allows you to import server-only (Node.js APIs that don't work in a browser) code into your page files. When Next.js builds your project, it removes server only code from your client-side bundle by checking which code exists inside one any of the following built-in methods (code splitting): - -- getServerSideProps -- getStaticProps -- getStaticPaths - -The Module not found: can't resolve 'xyz' error happens when you try to use server only code outside of these methods. Despite `algokit-utils` lazy loading the node specific code dynamically, Next.js does not seem to correctly identify whether a dynamic import is specific to server or client side. Hence the above fix disables the fallback for `fs` module so it ignores polyfilling it on client side. - ## Contributing This is an open source project managed by the Algorand Foundation. See the [AlgoKit contributing page](https://github.com/algorandfoundation/algokit-cli/blob/main/CONTRIBUTING.md) to learn about making improvements. diff --git a/docs/code/classes/types_debugging.AVMDebuggerSourceMap.md b/docs/code/classes/types_debugging.AVMDebuggerSourceMap.md index c1b2164..fd99889 100644 --- a/docs/code/classes/types_debugging.AVMDebuggerSourceMap.md +++ b/docs/code/classes/types_debugging.AVMDebuggerSourceMap.md @@ -29,8 +29,8 @@ AVM debugger source map class. #### Parameters -| Name | Type | -| :---------------- | :---------------------------------------------------------------------------- | +| Name | Type | +| :------ | :------ | | `txnGroupSources` | [`AVMDebuggerSourceMapEntry`](types_debugging.AVMDebuggerSourceMapEntry.md)[] | #### Returns @@ -39,7 +39,7 @@ AVM debugger source map class. #### Defined in -[types/debugging.ts:60](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L60) +[types/debugging.ts:60](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L60) ## Properties @@ -49,7 +49,7 @@ AVM debugger source map class. #### Defined in -[types/debugging.ts:54](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L54) +[types/debugging.ts:54](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L54) ## Methods @@ -67,9 +67,9 @@ The dictionary #### Defined in -[types/debugging.ts:79](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L79) +[types/debugging.ts:79](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L79) ---- +___ ### fromDict @@ -79,9 +79,9 @@ Creates a source map from a dictionary of source map data. #### Parameters -| Name | Type | Description | -| :----- | :-------------------------------------------------------------------------------------- | :---------- | -| `data` | [`AVMDebuggerSourceMapDict`](../interfaces/types_debugging.AVMDebuggerSourceMapDict.md) | The data | +| Name | Type | Description | +| :------ | :------ | :------ | +| `data` | [`AVMDebuggerSourceMapDict`](../interfaces/types_debugging.AVMDebuggerSourceMapDict.md) | The data | #### Returns @@ -91,4 +91,4 @@ The source map #### Defined in -[types/debugging.ts:69](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L69) +[types/debugging.ts:69](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L69) diff --git a/docs/code/classes/types_debugging.AVMDebuggerSourceMapEntry.md b/docs/code/classes/types_debugging.AVMDebuggerSourceMapEntry.md index 5af51f7..80eee09 100644 --- a/docs/code/classes/types_debugging.AVMDebuggerSourceMapEntry.md +++ b/docs/code/classes/types_debugging.AVMDebuggerSourceMapEntry.md @@ -32,10 +32,10 @@ Create an AVM debugger source map entry. #### Parameters -| Name | Type | Description | -| :------------ | :------- | :---------------------------------------------- | -| `location` | `string` | The location of the file the source map is for. | -| `programHash` | `string` | The hash of the TEAL binary. | +| Name | Type | Description | +| :------ | :------ | :------ | +| `location` | `string` | The location of the file the source map is for. | +| `programHash` | `string` | The hash of the TEAL binary. | #### Returns @@ -43,7 +43,7 @@ Create an AVM debugger source map entry. #### Defined in -[types/debugging.ts:36](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L36) +[types/debugging.ts:36](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L36) ## Properties @@ -55,9 +55,9 @@ The location of the file the source map is for. #### Defined in -[types/debugging.ts:37](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L37) +[types/debugging.ts:37](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L37) ---- +___ ### programHash @@ -67,7 +67,7 @@ The hash of the TEAL binary. #### Defined in -[types/debugging.ts:38](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L38) +[types/debugging.ts:38](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L38) ## Methods @@ -77,8 +77,8 @@ The hash of the TEAL binary. #### Parameters -| Name | Type | -| :------ | :-------------------------------------------------------------------------- | +| Name | Type | +| :------ | :------ | | `other` | [`AVMDebuggerSourceMapEntry`](types_debugging.AVMDebuggerSourceMapEntry.md) | #### Returns @@ -87,9 +87,9 @@ The hash of the TEAL binary. #### Defined in -[types/debugging.ts:41](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L41) +[types/debugging.ts:41](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L41) ---- +___ ### toString @@ -101,4 +101,4 @@ The hash of the TEAL binary. #### Defined in -[types/debugging.ts:45](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L45) +[types/debugging.ts:45](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L45) diff --git a/docs/code/classes/types_debugging.PersistSourceMapInput.md b/docs/code/classes/types_debugging.PersistSourceMapInput.md index f1d2cd4..8c0a952 100644 --- a/docs/code/classes/types_debugging.PersistSourceMapInput.md +++ b/docs/code/classes/types_debugging.PersistSourceMapInput.md @@ -40,11 +40,11 @@ Note: rawTeal and compiledTeal are mutually exclusive. Only one of them should b #### Parameters -| Name | Type | -| :-------------- | :-------------------------------------------------------------- | -| `appName` | `string` | -| `fileName` | `string` | -| `rawTeal?` | `string` | +| Name | Type | +| :------ | :------ | +| `appName` | `string` | +| `fileName` | `string` | +| `rawTeal?` | `string` | | `compiledTeal?` | [`CompiledTeal`](../interfaces/types_debugging.CompiledTeal.md) | #### Returns @@ -53,7 +53,7 @@ Note: rawTeal and compiledTeal are mutually exclusive. Only one of them should b #### Defined in -[types/debugging.ts:95](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L95) +[types/debugging.ts:95](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L95) ## Properties @@ -63,9 +63,9 @@ Note: rawTeal and compiledTeal are mutually exclusive. Only one of them should b #### Defined in -[types/debugging.ts:92](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L92) +[types/debugging.ts:92](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L92) ---- +___ ### \_rawTeal @@ -73,9 +73,9 @@ Note: rawTeal and compiledTeal are mutually exclusive. Only one of them should b #### Defined in -[types/debugging.ts:93](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L93) +[types/debugging.ts:93](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L93) ---- +___ ### appName @@ -83,9 +83,9 @@ Note: rawTeal and compiledTeal are mutually exclusive. Only one of them should b #### Defined in -[types/debugging.ts:90](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L90) +[types/debugging.ts:90](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L90) ---- +___ ### compiledTeal @@ -93,7 +93,7 @@ Note: rawTeal and compiledTeal are mutually exclusive. Only one of them should b #### Defined in -[types/debugging.ts:91](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L91) +[types/debugging.ts:91](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L91) ## Accessors @@ -109,9 +109,9 @@ Get the file name #### Defined in -[types/debugging.ts:136](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L136) +[types/debugging.ts:136](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L136) ---- +___ ### rawTeal @@ -125,7 +125,7 @@ Get the underlying raw teal #### Defined in -[types/debugging.ts:125](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L125) +[types/debugging.ts:125](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L125) ## Methods @@ -137,8 +137,8 @@ Strips the '.teal' extension from a filename, if present. #### Parameters -| Name | Type | Description | -| :--------- | :------- | :---------------------------------------- | +| Name | Type | Description | +| :------ | :------ | :------ | | `fileName` | `string` | The filename to strip the extension from. | #### Returns @@ -149,9 +149,9 @@ The filename without the '.teal' extension. #### Defined in -[types/debugging.ts:146](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L146) +[types/debugging.ts:146](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L146) ---- +___ ### fromCompiledTeal @@ -161,11 +161,11 @@ Returns debugger source maps input from compiled TEAL code. #### Parameters -| Name | Type | Description | -| :------------- | :-------------------------------------------------------------- | :--------------------------------- | -| `compiledTeal` | [`CompiledTeal`](../interfaces/types_debugging.CompiledTeal.md) | The compiled TEAL code | -| `appName` | `string` | The name of the app | -| `fileName` | `string` | The name of the file to persist to | +| Name | Type | Description | +| :------ | :------ | :------ | +| `compiledTeal` | [`CompiledTeal`](../interfaces/types_debugging.CompiledTeal.md) | The compiled TEAL code | +| `appName` | `string` | The name of the app | +| `fileName` | `string` | The name of the file to persist to | #### Returns @@ -175,9 +175,9 @@ The persist source map input #### Defined in -[types/debugging.ts:120](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L120) +[types/debugging.ts:120](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L120) ---- +___ ### fromRawTeal @@ -187,10 +187,10 @@ Returns debugger source maps input from raw TEAL code. #### Parameters -| Name | Type | Description | -| :--------- | :------- | :--------------------------------- | -| `rawTeal` | `string` | The raw TEAL code | -| `appName` | `string` | The name of the app | +| Name | Type | Description | +| :------ | :------ | :------ | +| `rawTeal` | `string` | The raw TEAL code | +| `appName` | `string` | The name of the app | | `fileName` | `string` | The name of the file to persist to | #### Returns @@ -201,4 +201,4 @@ The persist source map input #### Defined in -[types/debugging.ts:109](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L109) +[types/debugging.ts:109](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L109) diff --git a/docs/code/interfaces/types_debugging.AVMDebuggerSourceMapDict.md b/docs/code/interfaces/types_debugging.AVMDebuggerSourceMapDict.md index 6c82c62..22d57c5 100644 --- a/docs/code/interfaces/types_debugging.AVMDebuggerSourceMapDict.md +++ b/docs/code/interfaces/types_debugging.AVMDebuggerSourceMapDict.md @@ -16,8 +16,8 @@ AVM debugger source map format. ### txn-group-sources -• **txn-group-sources**: \{ `hash`: `string` ; `sourcemap-location`: `string` }[] +• **txn-group-sources**: \{ `hash`: `string` ; `sourcemap-location`: `string` }[] #### Defined in -[types/debugging.ts:21](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L21) +[types/debugging.ts:21](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L21) diff --git a/docs/code/interfaces/types_debugging.CompiledTeal.md b/docs/code/interfaces/types_debugging.CompiledTeal.md index 8b4fa97..156dd2f 100644 --- a/docs/code/interfaces/types_debugging.CompiledTeal.md +++ b/docs/code/interfaces/types_debugging.CompiledTeal.md @@ -24,9 +24,9 @@ The compiled code #### Defined in -[types/debugging.ts:8](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L8) +[types/debugging.ts:8](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L8) ---- +___ ### compiledBase64ToBytes @@ -36,9 +36,9 @@ The base64 encoded code as a byte array #### Defined in -[types/debugging.ts:12](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L12) +[types/debugging.ts:12](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L12) ---- +___ ### compiledHash @@ -48,9 +48,9 @@ The has returned by the compiler #### Defined in -[types/debugging.ts:10](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L10) +[types/debugging.ts:10](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L10) ---- +___ ### sourceMap @@ -60,9 +60,9 @@ Source map from the compilation #### Defined in -[types/debugging.ts:14](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L14) +[types/debugging.ts:14](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L14) ---- +___ ### teal @@ -72,4 +72,4 @@ Original TEAL code #### Defined in -[types/debugging.ts:6](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L6) +[types/debugging.ts:6](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L6) diff --git a/docs/code/interfaces/types_debugging.PersistSourceMapsParams.md b/docs/code/interfaces/types_debugging.PersistSourceMapsParams.md index b7408cc..6fd57a3 100644 --- a/docs/code/interfaces/types_debugging.PersistSourceMapsParams.md +++ b/docs/code/interfaces/types_debugging.PersistSourceMapsParams.md @@ -10,24 +10,24 @@ Parameters to a call that persists source maps ### Properties -- [client](types_debugging.PersistSourceMapsParams.md#client) +- [algod](types_debugging.PersistSourceMapsParams.md#algod) - [projectRoot](types_debugging.PersistSourceMapsParams.md#projectroot) - [sources](types_debugging.PersistSourceMapsParams.md#sources) - [withSources](types_debugging.PersistSourceMapsParams.md#withsources) ## Properties -### client +### algod -• **client**: `default` +• **algod**: `default` An Algodv2 client to perform the compilation. #### Defined in -[types/debugging.ts:161](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L161) +[types/debugging.ts:161](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L161) ---- +___ ### projectRoot @@ -37,21 +37,21 @@ The root directory of the project. #### Defined in -[types/debugging.ts:159](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L159) +[types/debugging.ts:159](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L159) ---- +___ ### sources -• **sources**: \{ `appName`: `string` ; `compiledTeal`: [`CompiledTeal`](types_debugging.CompiledTeal.md) ; `fileName`: `string` }[] +• **sources**: \{ `appName`: `string` ; `compiledTeal`: [`CompiledTeal`](types_debugging.CompiledTeal.md) ; `fileName`: `string` }[] An array of PersistSourceMapInput objects. Each object can either contain rawTeal, in which case the function will execute a compile to obtain byte code, or it can accept an object of type CompiledTeal provided by algokit, which is used for source codes that have already been compiled and contain the traces. #### Defined in -[types/debugging.ts:157](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L157) +[types/debugging.ts:157](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L157) ---- +___ ### withSources @@ -61,4 +61,4 @@ A boolean indicating whether to include the source files in the output. #### Defined in -[types/debugging.ts:163](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L163) +[types/debugging.ts:163](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L163) diff --git a/docs/code/interfaces/types_debugging.SimulateAndPersistResponseParams.md b/docs/code/interfaces/types_debugging.SimulateAndPersistResponseParams.md index 28a9110..da28443 100644 --- a/docs/code/interfaces/types_debugging.SimulateAndPersistResponseParams.md +++ b/docs/code/interfaces/types_debugging.SimulateAndPersistResponseParams.md @@ -25,9 +25,9 @@ algod An Algodv2 client to perform the simulation. #### Defined in -[types/debugging.ts:171](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L171) +[types/debugging.ts:171](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L171) ---- +___ ### atc @@ -37,9 +37,9 @@ The AtomicTransactionComposer with transaction(s) loaded. #### Defined in -[types/debugging.ts:173](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L173) +[types/debugging.ts:173](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L173) ---- +___ ### bufferSizeMb @@ -49,9 +49,9 @@ bufferSizeMb The buffer size in megabytes. #### Defined in -[types/debugging.ts:177](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L177) +[types/debugging.ts:177](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L177) ---- +___ ### projectRoot @@ -61,4 +61,4 @@ projectRoot The root directory of the project. #### Defined in -[types/debugging.ts:175](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/types/debugging.ts#L175) +[types/debugging.ts:175](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/types/debugging.ts#L175) diff --git a/docs/code/modules/index.md b/docs/code/modules/index.md index 1a8c652..d20bf7d 100644 --- a/docs/code/modules/index.md +++ b/docs/code/modules/index.md @@ -4,75 +4,141 @@ ## Table of contents +### References + +- [AVMDebuggerSourceMap](index.md#avmdebuggersourcemap) +- [AVMDebuggerSourceMapEntry](index.md#avmdebuggersourcemapentry) +- [PersistSourceMapInput](index.md#persistsourcemapinput) +- [PersistSourceMapsParams](index.md#persistsourcemapsparams) +- [SimulateAndPersistResponseParams](index.md#simulateandpersistresponseparams) + ### Functions -- [performAtomicTransactionComposerSimulate](index.md#performatomictransactioncomposersimulate) - [persistSourceMaps](index.md#persistsourcemaps) +- [registerNodeDebugHandlers](index.md#registernodedebughandlers) +- [setAlgoKitProjectRoot](index.md#setalgokitprojectroot) - [simulateAndPersistResponse](index.md#simulateandpersistresponse) +## References + +### AVMDebuggerSourceMap + +Re-exports [AVMDebuggerSourceMap](../classes/types_debugging.AVMDebuggerSourceMap.md) + +___ + +### AVMDebuggerSourceMapEntry + +Re-exports [AVMDebuggerSourceMapEntry](../classes/types_debugging.AVMDebuggerSourceMapEntry.md) + +___ + +### PersistSourceMapInput + +Re-exports [PersistSourceMapInput](../classes/types_debugging.PersistSourceMapInput.md) + +___ + +### PersistSourceMapsParams + +Re-exports [PersistSourceMapsParams](../interfaces/types_debugging.PersistSourceMapsParams.md) + +___ + +### SimulateAndPersistResponseParams + +Re-exports [SimulateAndPersistResponseParams](../interfaces/types_debugging.SimulateAndPersistResponseParams.md) + ## Functions -### performAtomicTransactionComposerSimulate +### persistSourceMaps -▸ **performAtomicTransactionComposerSimulate**(`atc`, `algod`): `Promise`\<`SimulateResponse`\> +▸ **persistSourceMaps**(`params`): `Promise`\<`void`\> -Performs a simulation of the transactions loaded into the given AtomicTransactionComposer. +Persists the source maps for the given sources. #### Parameters -| Name | Type | Description | -| :------ | :-------------------------- | :-------------------------------------------------------- | -| `atc` | `AtomicTransactionComposer` | The AtomicTransactionComposer with transaction(s) loaded. | -| `algod` | `default` | An Algod client to perform the simulation. | +| Name | Type | Description | +| :------ | :------ | :------ | +| `params` | [`PersistSourceMapsParams`](../interfaces/types_debugging.PersistSourceMapsParams.md) | The parameters to define the source maps to persist. | #### Returns -`Promise`\<`SimulateResponse`\> +`Promise`\<`void`\> -The simulation result, which includes various details about how the transactions would be processed. +A promise that resolves when the source maps have been persisted. + +**`Throws`** + +Will throw an error if not running in a Node.js environment. #### Defined in -[debugging/simulate-and-persist-response.ts:25](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/debugging/simulate-and-persist-response.ts#L25) +[debugging/persistSourceMaps.ts:15](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/debugging/persistSourceMaps.ts#L15) ---- +___ -### persistSourceMaps +### registerNodeDebugHandlers -▸ **persistSourceMaps**(`params`): `Promise`\<`void`\> +▸ **registerNodeDebugHandlers**(): `void` + +Registers event handlers for various debugging events. + +This function sets up listeners for the following events: +- 'persistSourceMaps': Calls the `persistSourceMaps` function with the provided data. +- 'simulateAndPersistResponse': Calls the `simulateAndPersistResponse` function with the provided data. +- 'configureProjectRoot': Calls the `setAlgoKitProjectRoot` function with the provided data. + +#### Returns + +`void` + +#### Defined in + +[index.ts:23](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/index.ts#L23) -This function persists the source maps for the given sources. +___ + +### setAlgoKitProjectRoot + +▸ **setAlgoKitProjectRoot**(`params`): `Promise`\<`void`\> + +Sets the AlgoKit project root directory by searching for the `.algokit.toml` file. #### Parameters -| Name | Type | -| :------- | :------------------------------------------------------------------------------------ | -| `params` | [`PersistSourceMapsParams`](../interfaces/types_debugging.PersistSourceMapsParams.md) | +| Name | Type | Description | +| :------ | :------ | :------ | +| `params` | `Object` | The parameters for setting the project root. | +| `params.maxSearchDepth` | `number` | The maximum depth to search for the `.algokit.toml` file. | #### Returns `Promise`\<`void`\> -A promise that resolves when the source maps have been persisted. +**`Throws`** + +Will throw an error if called outside of a Node.js environment. #### Defined in -[debugging/debugging.ts:72](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/debugging/debugging.ts#L72) +[debugging/setAlgoKitProjectRoot.ts:13](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/debugging/setAlgoKitProjectRoot.ts#L13) ---- +___ ### simulateAndPersistResponse -▸ **simulateAndPersistResponse**(`param0`): `Promise`\<`SimulateResponse`\> +▸ **simulateAndPersistResponse**(`param`): `Promise`\<`SimulateResponse`\> -This function simulates the atomic transactions using the provided `AtomicTransactionComposer` object and `Algodv2` object, +Simulates the atomic transactions using the provided `AtomicTransactionComposer` object and `Algodv2` object, and persists the simulation response to an AlgoKit AVM Debugger compliant JSON file. #### Parameters -| Name | Type | Description | -| :------- | :------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------- | -| `param0` | [`SimulateAndPersistResponseParams`](../interfaces/types_debugging.SimulateAndPersistResponseParams.md) | The parameters to control the simulation and persistence. | +| Name | Type | Description | +| :------ | :------ | :------ | +| `param` | [`SimulateAndPersistResponseParams`](../interfaces/types_debugging.SimulateAndPersistResponseParams.md) | The parameters to control the simulation and persistence of Atomic Transaction Composer call and response. | #### Returns @@ -83,15 +149,15 @@ The simulation result, which includes various details about how the transactions **`Example`** ```ts -const atc = new AtomicTransactionComposer() -const algod = new algosdk.Algodv2(token, server, port) -const projectRoot = '/path/to/project' -const bufferSizeMb = 10 +const atc = new AtomicTransactionComposer(); +const algod = new algosdk.Algodv2(token, server, port); +const projectRoot = '/path/to/project'; +const bufferSizeMb = 10; -const result = await simulateAndPersistResponse({ atc, projectRoot, algod, bufferSizeMb }) -console.log(result) +const result = await simulateAndPersistResponse({ atc, projectRoot, algod, bufferSizeMb }); +console.log(result); ``` #### Defined in -[debugging/simulate-and-persist-response.ts:65](https://github.com/algorandfoundation/algokit-utils-ts/blob/main/debug-utils/src/debugging/simulate-and-persist-response.ts#L65) +[debugging/simulateAndPersistResponse.ts:65](https://github.com/algorandfoundation/algokit-utils-ts-debug/blob/main/src/debugging/simulateAndPersistResponse.ts#L65) diff --git a/package-lock.json b/package-lock.json index 96accd1..bf9f8d2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,7 @@ "buffer": "^6.0.3" }, "devDependencies": { - "@algorandfoundation/algokit-utils": "github:algorandfoundation/algokit-utils-ts#feat/puya-debug", + "@algorandfoundation/algokit-utils": "algorandfoundation/algokit-utils-ts#feat/puya-debug", "@commitlint/cli": "^18.4.2", "@commitlint/config-conventional": "^17.7.0", "@makerx/eslint-config": "^3.1.0", @@ -51,6 +51,7 @@ "node": ">=18.0" }, "peerDependencies": { + "@algorandfoundation/algokit-utils": "algorandfoundation/algokit-utils-ts#feat/puya-debug", "algosdk": "^2.7.0" } }, @@ -127,7 +128,7 @@ }, "node_modules/@algorandfoundation/algokit-utils": { "version": "0.1.0", - "resolved": "git+ssh://git@github.com/algorandfoundation/algokit-utils-ts.git#dab8085ffdd8583b410a98cba4de53030dc03ebe", + "resolved": "git+ssh://git@github.com/algorandfoundation/algokit-utils-ts.git#e0d1382fd8e47c8dd6b0276a4f30731863ffbf97", "dev": true, "license": "MIT", "dependencies": { @@ -2152,9 +2153,9 @@ } }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.21.3.tgz", - "integrity": "sha512-MmKSfaB9GX+zXl6E8z4koOr/xU63AMVleLEa64v7R0QF/ZloMs5vcD1sHgM64GXXS1csaJutG+ddtzcueI/BLg==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.22.4.tgz", + "integrity": "sha512-Fxamp4aEZnfPOcGA8KSNEohV8hX7zVHOemC8jVBoBUHu5zpJK/Eu3uJwt6BMgy9fkvzxDaurgj96F/NiLukF2w==", "cpu": [ "arm" ], @@ -2165,9 +2166,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.21.3.tgz", - "integrity": "sha512-zrt8ecH07PE3sB4jPOggweBjJMzI1JG5xI2DIsUbkA+7K+Gkjys6eV7i9pOenNSDJH3eOr/jLb/PzqtmdwDq5g==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.22.4.tgz", + "integrity": "sha512-VXoK5UMrgECLYaMuGuVTOx5kcuap1Jm8g/M83RnCHBKOqvPPmROFJGQaZhGccnsFtfXQ3XYa4/jMCJvZnbJBdA==", "cpu": [ "arm64" ], @@ -2178,9 +2179,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.21.3.tgz", - "integrity": "sha512-P0UxIOrKNBFTQaXTxOH4RxuEBVCgEA5UTNV6Yz7z9QHnUJ7eLX9reOd/NYMO3+XZO2cco19mXTxDMXxit4R/eQ==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.22.4.tgz", + "integrity": "sha512-xMM9ORBqu81jyMKCDP+SZDhnX2QEVQzTcC6G18KlTQEzWK8r/oNZtKuZaCcHhnsa6fEeOBionoyl5JsAbE/36Q==", "cpu": [ "arm64" ], @@ -2191,9 +2192,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.21.3.tgz", - "integrity": "sha512-L1M0vKGO5ASKntqtsFEjTq/fD91vAqnzeaF6sfNAy55aD+Hi2pBI5DKwCO+UNDQHWsDViJLqshxOahXyLSh3EA==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.22.4.tgz", + "integrity": "sha512-aJJyYKQwbHuhTUrjWjxEvGnNNBCnmpHDvrb8JFDbeSH3m2XdHcxDd3jthAzvmoI8w/kSjd2y0udT+4okADsZIw==", "cpu": [ "x64" ], @@ -2204,9 +2205,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.21.3.tgz", - "integrity": "sha512-btVgIsCjuYFKUjopPoWiDqmoUXQDiW2A4C3Mtmp5vACm7/GnyuprqIDPNczeyR5W8rTXEbkmrJux7cJmD99D2g==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.22.4.tgz", + "integrity": "sha512-j63YtCIRAzbO+gC2L9dWXRh5BFetsv0j0va0Wi9epXDgU/XUi5dJKo4USTttVyK7fGw2nPWK0PbAvyliz50SCQ==", "cpu": [ "arm" ], @@ -2217,9 +2218,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.21.3.tgz", - "integrity": "sha512-zmjbSphplZlau6ZTkxd3+NMtE4UKVy7U4aVFMmHcgO5CUbw17ZP6QCgyxhzGaU/wFFdTfiojjbLG3/0p9HhAqA==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.22.4.tgz", + "integrity": "sha512-dJnWUgwWBX1YBRsuKKMOlXCzh2Wu1mlHzv20TpqEsfdZLb3WoJW2kIEsGwLkroYf24IrPAvOT/ZQ2OYMV6vlrg==", "cpu": [ "arm" ], @@ -2230,9 +2231,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.21.3.tgz", - "integrity": "sha512-nSZfcZtAnQPRZmUkUQwZq2OjQciR6tEoJaZVFvLHsj0MF6QhNMg0fQ6mUOsiCUpTqxTx0/O6gX0V/nYc7LrgPw==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.22.4.tgz", + "integrity": "sha512-AdPRoNi3NKVLolCN/Sp4F4N1d98c4SBnHMKoLuiG6RXgoZ4sllseuGioszumnPGmPM2O7qaAX/IJdeDU8f26Aw==", "cpu": [ "arm64" ], @@ -2243,9 +2244,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.21.3.tgz", - "integrity": "sha512-MnvSPGO8KJXIMGlQDYfvYS3IosFN2rKsvxRpPO2l2cum+Z3exiExLwVU+GExL96pn8IP+GdH8Tz70EpBhO0sIQ==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.22.4.tgz", + "integrity": "sha512-Gl0AxBtDg8uoAn5CCqQDMqAx22Wx22pjDOjBdmG0VIWX3qUBHzYmOKh8KXHL4UpogfJ14G4wk16EQogF+v8hmA==", "cpu": [ "arm64" ], @@ -2256,9 +2257,9 @@ ] }, "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.21.3.tgz", - "integrity": "sha512-+W+p/9QNDr2vE2AXU0qIy0qQE75E8RTwTwgqS2G5CRQ11vzq0tbnfBd6brWhS9bCRjAjepJe2fvvkvS3dno+iw==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.22.4.tgz", + "integrity": "sha512-3aVCK9xfWW1oGQpTsYJJPF6bfpWfhbRnhdlyhak2ZiyFLDaayz0EP5j9V1RVLAAxlmWKTDfS9wyRyY3hvhPoOg==", "cpu": [ "ppc64" ], @@ -2269,9 +2270,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.21.3.tgz", - "integrity": "sha512-yXH6K6KfqGXaxHrtr+Uoy+JpNlUlI46BKVyonGiaD74ravdnF9BUNC+vV+SIuB96hUMGShhKV693rF9QDfO6nQ==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.22.4.tgz", + "integrity": "sha512-ePYIir6VYnhgv2C5Xe9u+ico4t8sZWXschR6fMgoPUK31yQu7hTEJb7bCqivHECwIClJfKgE7zYsh1qTP3WHUA==", "cpu": [ "riscv64" ], @@ -2282,9 +2283,9 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.21.3.tgz", - "integrity": "sha512-R8cwY9wcnApN/KDYWTH4gV/ypvy9yZUHlbJvfaiXSB48JO3KpwSpjOGqO4jnGkLDSk1hgjYkTbTt6Q7uvPf8eg==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.22.4.tgz", + "integrity": "sha512-GqFJ9wLlbB9daxhVlrTe61vJtEY99/xB3C8e4ULVsVfflcpmR6c8UZXjtkMA6FhNONhj2eA5Tk9uAVw5orEs4Q==", "cpu": [ "s390x" ], @@ -2295,9 +2296,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.21.3.tgz", - "integrity": "sha512-kZPbX/NOPh0vhS5sI+dR8L1bU2cSO9FgxwM8r7wHzGydzfSjLRCFAT87GR5U9scj2rhzN3JPYVC7NoBbl4FZ0g==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.22.4.tgz", + "integrity": "sha512-87v0ol2sH9GE3cLQLNEy0K/R0pz1nvg76o8M5nhMR0+Q+BBGLnb35P0fVz4CQxHYXaAOhE8HhlkaZfsdUOlHwg==", "cpu": [ "x64" ], @@ -2308,9 +2309,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.21.3.tgz", - "integrity": "sha512-S0Yq+xA1VEH66uiMNhijsWAafffydd2X5b77eLHfRmfLsRSpbiAWiRHV6DEpz6aOToPsgid7TI9rGd6zB1rhbg==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.22.4.tgz", + "integrity": "sha512-UV6FZMUgePDZrFjrNGIWzDo/vABebuXBhJEqrHxrGiU6HikPy0Z3LfdtciIttEUQfuDdCn8fqh7wiFJjCNwO+g==", "cpu": [ "x64" ], @@ -2321,9 +2322,9 @@ ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.21.3.tgz", - "integrity": "sha512-9isNzeL34yquCPyerog+IMCNxKR8XYmGd0tHSV+OVx0TmE0aJOo9uw4fZfUuk2qxobP5sug6vNdZR6u7Mw7Q+Q==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.22.4.tgz", + "integrity": "sha512-BjI+NVVEGAXjGWYHz/vv0pBqfGoUH0IGZ0cICTn7kB9PyjrATSkX+8WkguNjWoj2qSr1im/+tTGRaY+4/PdcQw==", "cpu": [ "arm64" ], @@ -2334,9 +2335,9 @@ ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.21.3.tgz", - "integrity": "sha512-nMIdKnfZfzn1Vsk+RuOvl43ONTZXoAPUUxgcU0tXooqg4YrAqzfKzVenqqk2g5efWh46/D28cKFrOzDSW28gTA==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.22.4.tgz", + "integrity": "sha512-SiWG/1TuUdPvYmzmYnmd3IEifzR61Tragkbx9D3+R8mzQqDBz8v+BvZNDlkiTtI9T15KYZhP0ehn3Dld4n9J5g==", "cpu": [ "ia32" ], @@ -2347,9 +2348,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.21.3.tgz", - "integrity": "sha512-fOvu7PCQjAj4eWDEuD8Xz5gpzFqXzGlxHZozHP4b9Jxv9APtdxL6STqztDzMLuRXEc4UpXGGhx029Xgm91QBeA==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.22.4.tgz", + "integrity": "sha512-j8pPKp53/lq9lMXN57S8cFz0MynJk8OWNuUnXct/9KCpKU7DgU3bYMJhwWmcqC0UU29p8Lr0/7KEVcaM6bf47Q==", "cpu": [ "x64" ], @@ -12768,9 +12769,9 @@ } }, "node_modules/rollup": { - "version": "4.21.3", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.21.3.tgz", - "integrity": "sha512-7sqRtBNnEbcBtMeRVc6VRsJMmpI+JU1z9VTvW8D4gXIYQFz0aLcsE6rRkyghZkLfEgUZgVvOG7A5CVz/VW5GIA==", + "version": "4.22.4", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.22.4.tgz", + "integrity": "sha512-vD8HJ5raRcWOyymsR6Z3o6+RzfEPCnVLMFJ6vRslO1jt4LO6dUo5Qnpg7y4RkZFM2DMe3WUirkI5c16onjrc6A==", "dev": true, "dependencies": { "@types/estree": "1.0.5" @@ -12783,22 +12784,22 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.21.3", - "@rollup/rollup-android-arm64": "4.21.3", - "@rollup/rollup-darwin-arm64": "4.21.3", - "@rollup/rollup-darwin-x64": "4.21.3", - "@rollup/rollup-linux-arm-gnueabihf": "4.21.3", - "@rollup/rollup-linux-arm-musleabihf": "4.21.3", - "@rollup/rollup-linux-arm64-gnu": "4.21.3", - "@rollup/rollup-linux-arm64-musl": "4.21.3", - "@rollup/rollup-linux-powerpc64le-gnu": "4.21.3", - "@rollup/rollup-linux-riscv64-gnu": "4.21.3", - "@rollup/rollup-linux-s390x-gnu": "4.21.3", - "@rollup/rollup-linux-x64-gnu": "4.21.3", - "@rollup/rollup-linux-x64-musl": "4.21.3", - "@rollup/rollup-win32-arm64-msvc": "4.21.3", - "@rollup/rollup-win32-ia32-msvc": "4.21.3", - "@rollup/rollup-win32-x64-msvc": "4.21.3", + "@rollup/rollup-android-arm-eabi": "4.22.4", + "@rollup/rollup-android-arm64": "4.22.4", + "@rollup/rollup-darwin-arm64": "4.22.4", + "@rollup/rollup-darwin-x64": "4.22.4", + "@rollup/rollup-linux-arm-gnueabihf": "4.22.4", + "@rollup/rollup-linux-arm-musleabihf": "4.22.4", + "@rollup/rollup-linux-arm64-gnu": "4.22.4", + "@rollup/rollup-linux-arm64-musl": "4.22.4", + "@rollup/rollup-linux-powerpc64le-gnu": "4.22.4", + "@rollup/rollup-linux-riscv64-gnu": "4.22.4", + "@rollup/rollup-linux-s390x-gnu": "4.22.4", + "@rollup/rollup-linux-x64-gnu": "4.22.4", + "@rollup/rollup-linux-x64-musl": "4.22.4", + "@rollup/rollup-win32-arm64-msvc": "4.22.4", + "@rollup/rollup-win32-ia32-msvc": "4.22.4", + "@rollup/rollup-win32-x64-msvc": "4.22.4", "fsevents": "~2.3.2" } }, diff --git a/package.json b/package.json index db96ab9..1432edb 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "@algorandfoundation/algokit-utils-debug", "version": "0.1.0", "private": false, - "description": "A set of core Algorand utilities written in TypeScript and released via npm that make it easier to build solutions on Algorand.", + "description": "A set of addon utilities for generating artifacts for use with AlgoKit AVM Debugger VSCode extension.", "author": "Algorand Foundation", "license": "MIT", "engines": { @@ -26,15 +26,12 @@ "import": "./types/*.mjs", "require": "./types/*.js" }, - "./testing": { - "types": "./testing/index.d.ts", - "import": "./testing/index.mjs", - "require": "./testing/index.js" - }, "./index.d.ts": "./index.d.ts", "./package.json": "./package.json" }, "scripts": { + "prepare": "npm run build && npm run github:prepare", + "github:prepare": "npx -y rimraf '!({dist,package.json,README.md})' && npx -y cpy 'dist/**/*' '.' --parents && npx -y rimraf dist", "build": "run-s build:*", "build:0-clean": "rimraf dist coverage", "build:1-compile": "rollup -c --configPlugin typescript --verbose", @@ -61,10 +58,11 @@ "buffer": "^6.0.3" }, "peerDependencies": { - "algosdk": "^2.7.0" + "algosdk": "^2.7.0", + "@algorandfoundation/algokit-utils": "algorandfoundation/algokit-utils-ts#feat/puya-debug" }, "devDependencies": { - "@algorandfoundation/algokit-utils": "github:algorandfoundation/algokit-utils-ts#feat/puya-debug", + "@algorandfoundation/algokit-utils": "algorandfoundation/algokit-utils-ts#feat/puya-debug", "@commitlint/cli": "^18.4.2", "@commitlint/config-conventional": "^17.7.0", "@makerx/eslint-config": "^3.1.0", diff --git a/src/constants.ts b/src/constants.ts new file mode 100644 index 0000000..263773c --- /dev/null +++ b/src/constants.ts @@ -0,0 +1,7 @@ +const ALGOKIT_DIR = '.algokit' +const SOURCES_DIR = 'sources' +const TEAL_FILE_EXT = '.teal' +const TEAL_SOURCEMAP_EXT = '.teal.tok.map' +const DEFAULT_MAX_SEARCH_DEPTH = 10 + +export { ALGOKIT_DIR, DEFAULT_MAX_SEARCH_DEPTH, SOURCES_DIR, TEAL_FILE_EXT, TEAL_SOURCEMAP_EXT } diff --git a/src/debugging/debugging.ts b/src/debugging/debugging.ts deleted file mode 100644 index c8c676a..0000000 --- a/src/debugging/debugging.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { AlgorandClient } from '@algorandfoundation/algokit-utils' -import { ClientManager } from '@algorandfoundation/algokit-utils/types/client-manager' -import * as crypto from 'crypto' -import { AVMDebuggerSourceMapEntry, CompiledTeal, PersistSourceMapsParams } from '../types/debugging' -import { isNode } from '../utils' - -const ALGOKIT_DIR = '.algokit' -const SOURCES_DIR = 'sources' -const TEAL_FILE_EXT = '.teal' -const TEAL_SOURCEMAP_EXT = '.teal.tok.map' - -// === Internal methods === - -async function writeToFile(filePath: string, content: string): Promise { - const path = await import('path') - const fs = await import('fs') - - await fs.promises.mkdir(path.dirname(filePath), { recursive: true }) - await fs.promises.writeFile(filePath, content, 'utf8') -} - -async function buildAVMSourcemap({ - rawTeal, - compiledTeal, - appName, - fileName, - outputPath, - algorandClient, - withSources = true, -}: { - rawTeal?: string - compiledTeal?: CompiledTeal - appName: string - fileName: string - outputPath: string - algorandClient: AlgorandClient - withSources?: boolean -}): Promise { - if (!rawTeal && !compiledTeal) { - throw new Error('Either rawTeal or compiledTeal must be provided.') - } - const path = await import('path') - - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const result = rawTeal ? await algorandClient.app.compileTeal(rawTeal) : compiledTeal! - const programHash = crypto.createHash('SHA-512/256').update(Buffer.from(result.compiled, 'base64')).digest('base64') - const sourceMap = result.sourceMap - sourceMap.sources = withSources ? [`${fileName}${TEAL_FILE_EXT}`] : [] - - const outputDirPath = path.join(outputPath, ALGOKIT_DIR, SOURCES_DIR, appName) - const sourceMapOutputPath = path.join(outputDirPath, `${fileName}${TEAL_SOURCEMAP_EXT}`) - const tealOutputPath = path.join(outputDirPath, `${fileName}${TEAL_FILE_EXT}`) - await writeToFile(sourceMapOutputPath, JSON.stringify(sourceMap)) - - if (withSources && result) { - await writeToFile(tealOutputPath, result.teal) - } - - return new AVMDebuggerSourceMapEntry(sourceMapOutputPath, programHash) -} - -// === Public facing methods === - -/** - * - * This function persists the source maps for the given sources. - * - * @param param0 The parameters to define the persistence - * - * @returns A promise that resolves when the source maps have been persisted. - */ -export async function persistSourceMaps(params: PersistSourceMapsParams): Promise { - if (!isNode()) { - throw new Error('Sourcemaps can only be persisted in a Node.js environment.') - } - - const algorandClient = AlgorandClient.fromConfig({ - algodConfig: ClientManager.getDefaultLocalNetConfig('algod'), - }) - - try { - const { sources, projectRoot, withSources } = params - await Promise.all( - sources.map((source) => - buildAVMSourcemap({ - // Update property access to match new format - rawTeal: source.compiledTeal.teal, - compiledTeal: source.compiledTeal, - appName: source.appName, - fileName: source.fileName, - outputPath: projectRoot, - algorandClient, - withSources, - }), - ), - ) - } catch (error) { - const err = error instanceof Error ? error : new Error(String(error)) - throw err - } -} diff --git a/src/debugging/index.ts b/src/debugging/index.ts index 2d08a42..d7d5056 100644 --- a/src/debugging/index.ts +++ b/src/debugging/index.ts @@ -1,2 +1,3 @@ -export * from './debugging' -export * from './simulate-and-persist-response' +export * from './persistSourceMaps' +export * from './setAlgoKitProjectRoot' +export * from './simulateAndPersistResponse' diff --git a/src/debugging/debugging.spec.ts b/src/debugging/persistSourceMaps.spec.ts similarity index 53% rename from src/debugging/debugging.spec.ts rename to src/debugging/persistSourceMaps.spec.ts index 7a444c1..a03b292 100644 --- a/src/debugging/debugging.spec.ts +++ b/src/debugging/persistSourceMaps.spec.ts @@ -1,10 +1,11 @@ import { Config } from '@algorandfoundation/algokit-utils' import { algorandFixture } from '@algorandfoundation/algokit-utils/testing' -import { describe, test } from '@jest/globals' +import { describe, expect, test } from '@jest/globals' +import algosdk from 'algosdk' import * as fs from 'fs/promises' import * as os from 'os' import * as path from 'path' -import '../index' +import { registerNodeDebugHandlers } from '../index' async function fileExists(filePath: string): Promise { try { @@ -15,11 +16,14 @@ async function fileExists(filePath: string): Promise { } } -describe('debug utils tests', () => { +describe('persistSourceMaps tests', () => { const localnet = algorandFixture() const timeout = 10e6 - beforeAll(localnet.beforeEach) + beforeAll(async () => { + registerNodeDebugHandlers() + return localnet.beforeEach() + }) test( 'build teal sourceMaps', @@ -34,26 +38,36 @@ int 1 #pragma version 9 int 1 ` - const compiledApproval = await localnet.context.algorand.client.algod.compile(approval).do() - const compiledClear = await localnet.context.algorand.client.algod.compile(clear).do() + const compiledApproval = await localnet.context.algorand.client.algod.compile(approval).sourcemap(true).do() + const compiledClear = await localnet.context.algorand.client.algod.compile(clear).sourcemap(true).do() await Config.events.emitAsync('persistSourceMaps', { - data: { - sources: [ - { - compiledTeal: compiledApproval, - appName: 'cool_app', - fileName: 'approval', + sources: [ + { + compiledTeal: { + teal: approval, + compiled: compiledApproval.result, + compiledHash: compiledApproval.hash, + compiledBase64ToBytes: new Uint8Array(Buffer.from(compiledApproval.result, 'base64')), + sourceMap: new algosdk.SourceMap(compiledApproval['sourcemap']), }, - { - compiledTeal: compiledClear, - appName: 'cool_app', - fileName: 'clear', + appName: 'cool_app', + fileName: 'approval', + }, + { + compiledTeal: { + teal: clear, + compiled: compiledClear.result, + compiledHash: compiledClear.hash, + compiledBase64ToBytes: new Uint8Array(Buffer.from(compiledClear.result, 'base64')), + sourceMap: new algosdk.SourceMap(compiledClear['sourcemap']), }, - ], - projectRoot: cwd, - appManager: localnet.algorand.app, - }, + appName: 'cool_app', + fileName: 'clear', + }, + ], + projectRoot: cwd, + algod: localnet.context.algorand.client.algod, }) const rootPath = path.join(cwd, '.algokit', 'sources') diff --git a/src/debugging/persistSourceMaps.ts b/src/debugging/persistSourceMaps.ts new file mode 100644 index 0000000..41401a9 --- /dev/null +++ b/src/debugging/persistSourceMaps.ts @@ -0,0 +1,48 @@ +import { AlgorandClient } from '@algorandfoundation/algokit-utils' +import { ClientManager } from '@algorandfoundation/algokit-utils/types/client-manager' +import { PersistSourceMapsParams } from '../types/debugging' +import { buildAVMSourcemap, isNode } from '../utils' + +/** + * Persists the source maps for the given sources. + * + * @param params - The parameters to define the source maps to persist. + * + * @returns A promise that resolves when the source maps have been persisted. + * + * @throws Will throw an error if not running in a Node.js environment. + */ +export async function persistSourceMaps(params: PersistSourceMapsParams): Promise { + if (!isNode()) { + throw new Error('Sourcemaps can only be persisted in a Node.js environment.') + } + + try { + const { sources, projectRoot, withSources, algod } = params + + const algorandClient = algod + ? AlgorandClient.fromClients({ + algod: algod, + }) + : AlgorandClient.fromConfig({ + algodConfig: ClientManager.getDefaultLocalNetConfig('algod'), + }) + + await Promise.all( + sources.map((source) => + buildAVMSourcemap({ + rawTeal: source.compiledTeal.teal, + compiledTeal: source.compiledTeal, + appName: source.appName, + fileName: source.fileName, + outputPath: projectRoot, + algorandClient, + withSources, + }), + ), + ) + } catch (error) { + const err = error instanceof Error ? error : new Error(JSON.stringify(error)) + throw err + } +} diff --git a/src/debugging/setAlgoKitProjectRoot.spec.ts b/src/debugging/setAlgoKitProjectRoot.spec.ts new file mode 100644 index 0000000..6df4325 --- /dev/null +++ b/src/debugging/setAlgoKitProjectRoot.spec.ts @@ -0,0 +1,29 @@ +import { Config } from '@algorandfoundation/algokit-utils' +import { algorandFixture } from '@algorandfoundation/algokit-utils/testing' +import { describe, expect, jest, test } from '@jest/globals' +import * as fs from 'fs/promises' +import * as os from 'os' +import * as path from 'path' +import { registerNodeDebugHandlers } from '../index' + +describe('setAlgoKitProjectRoot tests', () => { + const localnet = algorandFixture() + + beforeAll(async () => { + registerNodeDebugHandlers() + return localnet.beforeEach() + }) + + test('configure project root', async () => { + const mockConfigureSpy = jest.spyOn(Config, 'configure') + const cwd = await fs.mkdtemp(path.join(os.tmpdir(), 'cwd')) + + jest.spyOn(process, 'cwd').mockReturnValue(cwd) + await fs.writeFile(path.join(cwd, '.algokit.toml'), '') + + await Config.events.emitAsync('configureProjectRoot', { maxSearchDepth: 1 }) + + expect(mockConfigureSpy).toHaveBeenCalledWith({ projectRoot: expect.any(String) }) + jest.restoreAllMocks() + }) +}) diff --git a/src/debugging/setAlgoKitProjectRoot.ts b/src/debugging/setAlgoKitProjectRoot.ts new file mode 100644 index 0000000..161a622 --- /dev/null +++ b/src/debugging/setAlgoKitProjectRoot.ts @@ -0,0 +1,30 @@ +import { Config } from '@algorandfoundation/algokit-utils' +import { DEFAULT_MAX_SEARCH_DEPTH } from '../constants' +import { isNode } from '../utils' + +/** + * Sets the AlgoKit project root directory by searching for the `.algokit.toml` file. + * + * @param params - The parameters for setting the project root. + * @param params.maxSearchDepth - The maximum depth to search for the `.algokit.toml` file. + * + * @throws Will throw an error if called outside of a Node.js environment. + */ +export async function setAlgoKitProjectRoot(params: { maxSearchDepth: number }): Promise { + if (!isNode()) { + throw new Error('`configureProjectRoot` can only be called in Node.js environment.') + } + + const fs = await import('fs') + const path = await import('path') + + let currentPath = process.cwd() + const maxDepth = params.maxSearchDepth ?? DEFAULT_MAX_SEARCH_DEPTH + for (let i = 0; i < maxDepth; i++) { + if (fs.existsSync(`${currentPath}/.algokit.toml`)) { + Config.configure({ projectRoot: currentPath }) + break + } + currentPath = path.dirname(currentPath) + } +} diff --git a/src/debugging/simulateAndPersistResponse.spec.ts b/src/debugging/simulateAndPersistResponse.spec.ts new file mode 100644 index 0000000..042776b --- /dev/null +++ b/src/debugging/simulateAndPersistResponse.spec.ts @@ -0,0 +1,46 @@ +import { Config } from '@algorandfoundation/algokit-utils' +import { algorandFixture } from '@algorandfoundation/algokit-utils/testing' +import { describe, expect, test } from '@jest/globals' +import algosdk, { makeEmptyTransactionSigner } from 'algosdk' +import * as fs from 'fs/promises' +import * as os from 'os' +import * as path from 'path' +import { registerNodeDebugHandlers } from '../index' +import { SimulateAndPersistResponseParams } from '../types/debugging' + +describe('simulateAndPersistResponse tests', () => { + const localnet = algorandFixture() + + beforeAll(async () => { + registerNodeDebugHandlers() + return localnet.beforeEach() + }) + + test('simulate and persist response', async () => { + const cwd = await fs.mkdtemp(path.join(os.tmpdir(), 'cwd')) + const mockAtc = new algosdk.AtomicTransactionComposer() + const mockPay = await localnet.context.algorand.transactions.payment({ + sender: 'BOB4H2EFAL3OKDEE2FATYKJRQZSKGLXM7KB6CKSSIBENJCO2SVXDLZ6IBI', + receiver: 'BOB4H2EFAL3OKDEE2FATYKJRQZSKGLXM7KB6CKSSIBENJCO2SVXDLZ6IBI', + amount: (0).algo(), + }) + mockAtc.addTransaction({ txn: mockPay, signer: makeEmptyTransactionSigner() }) + const mockAlgod = localnet.context.algorand.client.algod + + const params: SimulateAndPersistResponseParams = { + algod: mockAlgod, + atc: mockAtc, + projectRoot: cwd, + bufferSizeMb: 10, + } + + await Config.events.emitAsync('simulateAndPersistResponse', params) + + const debugTracesDir = path.join(cwd, 'debug_traces') + const files = await fs.readdir(debugTracesDir) + expect(files.length).toBeGreaterThan(0) + expect(files[0]).toMatch(/\.trace\.avm\.json$/) + const traceContent = JSON.parse(await fs.readFile(path.join(debugTracesDir, files[0]), 'utf8')) + expect(traceContent['txn-groups'][0]['txn-results'][0]['txn-result'].txn.txn.snd).toBe('C4PD6IUC9uUMhNFBPCkxhmSjLuz6g+EqUkBI1InalW4=') + }) +}) diff --git a/src/debugging/simulate-and-persist-response.ts b/src/debugging/simulateAndPersistResponse.ts similarity index 93% rename from src/debugging/simulate-and-persist-response.ts rename to src/debugging/simulateAndPersistResponse.ts index 22b8692..6520698 100644 --- a/src/debugging/simulate-and-persist-response.ts +++ b/src/debugging/simulateAndPersistResponse.ts @@ -1,10 +1,10 @@ import algosdk from 'algosdk' +import { SimulateAndPersistResponseParams } from '../types/debugging' +import { isNode } from '../utils' import Algodv2 = algosdk.Algodv2 import AtomicTransactionComposer = algosdk.AtomicTransactionComposer import EncodedSignedTransaction = algosdk.EncodedSignedTransaction import modelsv2 = algosdk.modelsv2 -import { SimulateAndPersistResponseParams } from '../types/debugging' -import { isNode } from '../utils' const TRACES_FILE_EXT = '.trace.avm.json' const DEBUG_TRACES_DIR = 'debug_traces' @@ -18,8 +18,9 @@ interface ErrnoException extends Error { /** * Performs a simulation of the transactions loaded into the given AtomicTransactionComposer. - * @param atc The AtomicTransactionComposer with transaction(s) loaded. - * @param algod An Algod client to perform the simulation. + * + * @param atc - The AtomicTransactionComposer with transaction(s) loaded. + * @param algod - An Algod client to perform the simulation. * @returns The simulation result, which includes various details about how the transactions would be processed. */ export async function performAtomicTransactionComposerSimulate(atc: AtomicTransactionComposer, algod: Algodv2) { @@ -46,11 +47,10 @@ export async function performAtomicTransactionComposerSimulate(atc: AtomicTransa } /** - * This function simulates the atomic transactions using the provided `AtomicTransactionComposer` object and `Algodv2` object, + * Simulates the atomic transactions using the provided `AtomicTransactionComposer` object and `Algodv2` object, * and persists the simulation response to an AlgoKit AVM Debugger compliant JSON file. * - * @param param0 The parameters to control the simulation and persistence. - * + * @param param - The parameters to control the simulation and persistence of Atomic Transaction Composer call and response. * @returns The simulation result, which includes various details about how the transactions would be processed. * * @example diff --git a/src/index.ts b/src/index.ts index 825d55c..b18b74f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,15 +1,45 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { Config } from '@algorandfoundation/algokit-utils' -import { persistSourceMaps, simulateAndPersistResponse } from './debugging' +import { persistSourceMaps, setAlgoKitProjectRoot, simulateAndPersistResponse } from './debugging' +import { + AVMDebuggerSourceMap, + AVMDebuggerSourceMapEntry, + PersistSourceMapInput, + PersistSourceMapsParams, + SimulateAndPersistResponseParams, +} from './types/debugging' +/** + * Registers event handlers for various debugging events. + * + * This function sets up listeners for the following events: + * - 'persistSourceMaps': Calls the `persistSourceMaps` function with the provided data. + * - 'simulateAndPersistResponse': Calls the `simulateAndPersistResponse` function with the provided data. + * - 'configureProjectRoot': Calls the `setAlgoKitProjectRoot` function with the provided data. + * + * @returns {void} + */ // eslint-disable-next-line @typescript-eslint/no-explicit-any -const registerNodeDebugHandlers = () => { +const registerNodeDebugHandlers = (): void => { Config.events.on('persistSourceMaps', async (data: any) => { await persistSourceMaps(data) }) Config.events.on('simulateAndPersistResponse', async (data: any) => { await simulateAndPersistResponse(data) }) + Config.events.on('configureProjectRoot', async (data: any) => { + await setAlgoKitProjectRoot(data) + }) +} + +export { + AVMDebuggerSourceMap, + AVMDebuggerSourceMapEntry, + PersistSourceMapInput, + persistSourceMaps, + registerNodeDebugHandlers, + setAlgoKitProjectRoot, + simulateAndPersistResponse, } -export { registerNodeDebugHandlers } +export type { PersistSourceMapsParams, SimulateAndPersistResponseParams } diff --git a/src/types/debugging.ts b/src/types/debugging.ts index 6a52dc2..b88bbb3 100644 --- a/src/types/debugging.ts +++ b/src/types/debugging.ts @@ -158,7 +158,7 @@ export interface PersistSourceMapsParams { /** The root directory of the project. */ projectRoot: string /** An Algodv2 client to perform the compilation. */ - client: algosdk.Algodv2 | AlgodClient + algod: algosdk.Algodv2 | AlgodClient /** A boolean indicating whether to include the source files in the output. */ withSources?: boolean } diff --git a/src/utils.ts b/src/utils.ts index e94c441..0c0b52a 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,3 +1,60 @@ +import { AlgorandClient } from '@algorandfoundation/algokit-utils' +import { createHash } from 'crypto' // Import the createHash method from the crypto module +import { ALGOKIT_DIR, SOURCES_DIR, TEAL_FILE_EXT, TEAL_SOURCEMAP_EXT } from './constants' +import { AVMDebuggerSourceMapEntry, CompiledTeal } from './types/debugging' + export const isNode = () => { return typeof process !== 'undefined' && process.versions != null && process.versions.node != null } + +export async function writeToFile(filePath: string, content: string): Promise { + const path = await import('path') + const fs = await import('fs') + + await fs.promises.mkdir(path.dirname(filePath), { recursive: true }) + await fs.promises.writeFile(filePath, content, 'utf8') +} + +export async function buildAVMSourcemap({ + rawTeal, + compiledTeal, + appName, + fileName, + outputPath, + algorandClient, + withSources = true, +}: { + rawTeal?: string + compiledTeal?: CompiledTeal + appName: string + fileName: string + outputPath: string + algorandClient: AlgorandClient + withSources?: boolean +}): Promise { + if (!isNode()) { + throw new Error('`buildAVMSourcemap` can only be called in Node.js environment.') + } + + if (!rawTeal && !compiledTeal) { + throw new Error('Either rawTeal or compiledTeal must be provided.') + } + const path = await import('path') + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const result = rawTeal ? await algorandClient.app.compileTeal(rawTeal) : compiledTeal! + const programHash = createHash('SHA-512/256').update(Buffer.from(result.compiled, 'base64')).digest('base64') + const sourceMap = result.sourceMap + sourceMap.sources = withSources ? [`${fileName}${TEAL_FILE_EXT}`] : [] + + const outputDirPath = path.join(outputPath, ALGOKIT_DIR, SOURCES_DIR, appName) + const sourceMapOutputPath = path.join(outputDirPath, `${fileName}${TEAL_SOURCEMAP_EXT}`) + const tealOutputPath = path.join(outputDirPath, `${fileName}${TEAL_FILE_EXT}`) + await writeToFile(sourceMapOutputPath, JSON.stringify(sourceMap)) + + if (withSources && result) { + await writeToFile(tealOutputPath, result.teal) + } + + return new AVMDebuggerSourceMapEntry(sourceMapOutputPath, programHash) +}