@algorandfoundation/puya-ts 1.0.0-beta.13 → 1.0.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ import type { ARC4Router, AWST, ContractMethod, SubroutineCallExpression } from '../nodes';
2
+ import { FunctionTraverser } from './awst-traverser';
3
+ export declare class Arc4ApprovalCallsRouter extends FunctionTraverser {
4
+ #private;
5
+ static validate(awst: AWST[]): void;
6
+ validate(approvalProgram: ContractMethod): void;
7
+ visitSubroutineCallExpression(expression: SubroutineCallExpression): void;
8
+ visitARC4Router(expression: ARC4Router): void;
9
+ }
@@ -0,0 +1,87 @@
1
+ import type { AddressConstant, AppAccountStateExpression, AppStateExpression, AppStorageDefinition, ARC4Decode, ARC4Encode, ARC4Router, ArrayConcat, ArrayExtend, ArrayPop, AssertExpression, AssignmentExpression, AssignmentStatement, BigUIntAugmentedAssignment, BigUIntBinaryOperation, BigUIntPostfixUnaryOperation, Block, BoolConstant, BooleanBinaryOperation, BoxValueExpression, BytesAugmentedAssignment, BytesBinaryOperation, BytesComparisonExpression, BytesConstant, BytesUnaryOperation, CheckedMaybe, CompiledContract, CompiledLogicSig, ConditionalExpression, Contract, ContractMemberNodeVisitor, ContractMethod, Copy, CreateInnerTransaction, DecimalConstant, Emit, Enumeration, ExpressionStatement, ExpressionVisitor, FieldExpression, ForInLoop, Goto, GroupTransactionReference, IfElse, IndexExpression, InnerTransactionField, IntegerConstant, IntersectionSliceExpression, IntrinsicCall, LogicSignature, LoopContinue, LoopExit, MethodConstant, NewArray, NewStruct, Not, NumericComparisonExpression, PuyaLibCall, Range, ReinterpretCast, ReturnStatement, Reversed, RootNodeVisitor, SingleEvaluation, SliceExpression, StateDelete, StateExists, StateGet, StateGetEx, StatementVisitor, StringConstant, SubmitInnerTransaction, Subroutine, SubroutineCallExpression, Switch, TemplateVar, TupleExpression, TupleItemExpression, UInt64AugmentedAssignment, UInt64BinaryOperation, UInt64PostfixUnaryOperation, UInt64UnaryOperation, UpdateInnerTransaction, VarExpression, VoidConstant, WhileLoop } from '../nodes';
2
+ export declare class FunctionTraverser implements ExpressionVisitor<void>, StatementVisitor<void> {
3
+ visitExpressionStatement(statement: ExpressionStatement): void;
4
+ visitBlock(statement: Block): void;
5
+ visitGoto(statement: Goto): void;
6
+ visitIfElse(statement: IfElse): void;
7
+ visitSwitch(statement: Switch): void;
8
+ visitWhileLoop(statement: WhileLoop): void;
9
+ visitLoopExit(statement: LoopExit): void;
10
+ visitLoopContinue(statement: LoopContinue): void;
11
+ visitReturnStatement(statement: ReturnStatement): void;
12
+ visitAssignmentStatement(statement: AssignmentStatement): void;
13
+ visitUInt64AugmentedAssignment(statement: UInt64AugmentedAssignment): void;
14
+ visitBigUIntAugmentedAssignment(statement: BigUIntAugmentedAssignment): void;
15
+ visitBytesAugmentedAssignment(statement: BytesAugmentedAssignment): void;
16
+ visitForInLoop(statement: ForInLoop): void;
17
+ visitAssertExpression(expression: AssertExpression): void;
18
+ visitIntegerConstant(expression: IntegerConstant): void;
19
+ visitDecimalConstant(expression: DecimalConstant): void;
20
+ visitBoolConstant(expression: BoolConstant): void;
21
+ visitBytesConstant(expression: BytesConstant): void;
22
+ visitStringConstant(expression: StringConstant): void;
23
+ visitVoidConstant(expression: VoidConstant): void;
24
+ visitTemplateVar(expression: TemplateVar): void;
25
+ visitMethodConstant(expression: MethodConstant): void;
26
+ visitAddressConstant(expression: AddressConstant): void;
27
+ visitARC4Encode(expression: ARC4Encode): void;
28
+ visitCopy(expression: Copy): void;
29
+ visitArrayConcat(expression: ArrayConcat): void;
30
+ visitArrayPop(expression: ArrayPop): void;
31
+ visitArrayExtend(expression: ArrayExtend): void;
32
+ visitARC4Decode(expression: ARC4Decode): void;
33
+ visitIntrinsicCall(expression: IntrinsicCall): void;
34
+ visitCreateInnerTransaction(expression: CreateInnerTransaction): void;
35
+ visitUpdateInnerTransaction(expression: UpdateInnerTransaction): void;
36
+ visitGroupTransactionReference(expression: GroupTransactionReference): void;
37
+ visitCheckedMaybe(expression: CheckedMaybe): void;
38
+ visitTupleExpression(expression: TupleExpression): void;
39
+ visitTupleItemExpression(expression: TupleItemExpression): void;
40
+ visitVarExpression(expression: VarExpression): void;
41
+ visitInnerTransactionField(expression: InnerTransactionField): void;
42
+ visitSubmitInnerTransaction(expression: SubmitInnerTransaction): void;
43
+ visitFieldExpression(expression: FieldExpression): void;
44
+ visitIndexExpression(expression: IndexExpression): void;
45
+ visitSliceExpression(expression: SliceExpression): void;
46
+ visitIntersectionSliceExpression(expression: IntersectionSliceExpression): void;
47
+ visitAppStateExpression(expression: AppStateExpression): void;
48
+ visitAppAccountStateExpression(expression: AppAccountStateExpression): void;
49
+ visitBoxValueExpression(expression: BoxValueExpression): void;
50
+ visitSingleEvaluation(expression: SingleEvaluation): void;
51
+ visitReinterpretCast(expression: ReinterpretCast): void;
52
+ visitNewArray(expression: NewArray): void;
53
+ visitConditionalExpression(expression: ConditionalExpression): void;
54
+ visitAssignmentExpression(expression: AssignmentExpression): void;
55
+ visitNumericComparisonExpression(expression: NumericComparisonExpression): void;
56
+ visitBytesComparisonExpression(expression: BytesComparisonExpression): void;
57
+ visitSubroutineCallExpression(expression: SubroutineCallExpression): void;
58
+ visitPuyaLibCall(expression: PuyaLibCall): void;
59
+ visitUInt64UnaryOperation(expression: UInt64UnaryOperation): void;
60
+ visitUInt64PostfixUnaryOperation(expression: UInt64PostfixUnaryOperation): void;
61
+ visitBigUIntPostfixUnaryOperation(expression: BigUIntPostfixUnaryOperation): void;
62
+ visitBytesUnaryOperation(expression: BytesUnaryOperation): void;
63
+ visitUInt64BinaryOperation(expression: UInt64BinaryOperation): void;
64
+ visitBigUIntBinaryOperation(expression: BigUIntBinaryOperation): void;
65
+ visitBytesBinaryOperation(expression: BytesBinaryOperation): void;
66
+ visitBooleanBinaryOperation(expression: BooleanBinaryOperation): void;
67
+ visitNot(expression: Not): void;
68
+ visitEmit(expression: Emit): void;
69
+ visitRange(expression: Range): void;
70
+ visitEnumeration(expression: Enumeration): void;
71
+ visitReversed(expression: Reversed): void;
72
+ visitStateGet(expression: StateGet): void;
73
+ visitStateGetEx(expression: StateGetEx): void;
74
+ visitStateExists(expression: StateExists): void;
75
+ visitStateDelete(expression: StateDelete): void;
76
+ visitNewStruct(expression: NewStruct): void;
77
+ visitCompiledContract(expression: CompiledContract): void;
78
+ visitCompiledLogicSig(expression: CompiledLogicSig): void;
79
+ visitARC4Router(expression: ARC4Router): void;
80
+ }
81
+ export declare class AwstTraverser extends FunctionTraverser implements RootNodeVisitor<void>, ContractMemberNodeVisitor<void> {
82
+ visitContractMethod(contractMemberNode: ContractMethod): void;
83
+ visitAppStorageDefinition(contractMemberNode: AppStorageDefinition): void;
84
+ visitSubroutine(rootNode: Subroutine): void;
85
+ visitLogicSignature(rootNode: LogicSignature): void;
86
+ visitContract(rootNode: Contract): void;
87
+ }
@@ -0,0 +1,2 @@
1
+ import type { AWST } from '../nodes';
2
+ export declare function validateAwst(awst: AWST[]): void;
@@ -1,5 +1,5 @@
1
1
  import type { AWST } from '../awst/nodes';
2
- import type { CompileOptions } from '../compile-options';
2
+ import type { PuyaTsCompileOptions } from '../compile-options';
3
3
  import type { CreateProgramResult } from '../parser';
4
4
  import type { CompilationSet } from './models/contract-class-model';
5
- export declare function buildAwst({ program, sourceFiles }: CreateProgramResult, options: CompileOptions): [AWST[], CompilationSet];
5
+ export declare function buildAwst({ program, sourceFiles }: CreateProgramResult, options: PuyaTsCompileOptions): [AWST[], CompilationSet];
package/bin/run-cli.mjs CHANGED
@@ -1,23 +1,24 @@
1
1
  #!/usr/bin/env node
2
2
  import '../cli.mjs';
3
- import 'tslib';
4
- import 'commander';
5
- import 'zod';
6
- import 'glob';
7
- import 'node:fs';
8
- import 'upath';
9
- import '../index-B46QirKR.js';
10
- import 'change-case';
11
- import 'node:path';
3
+ import 'argparse';
4
+ import '../compile-BcG41O6Z.js';
5
+ import 'node:async_hooks';
12
6
  import 'typescript';
13
7
  import 'node:buffer';
8
+ import 'node:fs';
14
9
  import 'node:util';
10
+ import 'upath';
15
11
  import 'polytype';
12
+ import 'change-case';
13
+ import 'node:path';
14
+ import 'tslib';
16
15
  import 'arcsecond';
16
+ import 'glob';
17
17
  import 'crypto';
18
18
  import 'fs';
19
19
  import 'os';
20
20
  import 'cross-spawn';
21
21
  import 'which';
22
+ import 'zod';
22
23
  import 'chalk';
23
24
  //# sourceMappingURL=run-cli.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-cli.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"run-cli.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,31 @@
1
+ import type { SubParser } from 'argparse';
2
+ import { LogLevel } from '../logger';
3
+ import { LocalsCoalescingStrategy } from '../puya/options';
4
+ export interface BuildCommandArgs {
5
+ command: 'build';
6
+ log_level: LogLevel;
7
+ output_awst: boolean;
8
+ output_awst_json: boolean;
9
+ dry_run: boolean;
10
+ skip_version_check: boolean;
11
+ output_teal: boolean;
12
+ output_source_map: boolean;
13
+ output_arc32: boolean;
14
+ output_arc56: boolean;
15
+ output_ssa_ir: boolean;
16
+ output_optimization_ir: boolean;
17
+ output_destructured_ir: boolean;
18
+ output_memory_ir: boolean;
19
+ output_bytecode: boolean;
20
+ match_algod_bytecode: boolean;
21
+ out_dir: string;
22
+ debug_level: string;
23
+ optimization_level: string;
24
+ target_avm_version: string;
25
+ cli_template_definitions: string[];
26
+ template_vars_prefix: string;
27
+ locals_coalescing_strategy: LocalsCoalescingStrategy;
28
+ paths: string[];
29
+ }
30
+ export declare function addBuildCommand(subparsers: SubParser): void;
31
+ export declare function buildCommand(args: BuildCommandArgs): Promise<void>;
package/cli/parse.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function parseCliArguments(): Promise<void>;
package/cli/util.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import type { ArgumentParser } from 'argparse';
2
+ export declare function addEnumArg<T>(parser: ArgumentParser, { name, enumType, default: defaultValue, help }: {
3
+ name: string;
4
+ enumType: Record<string, string>;
5
+ default?: T;
6
+ help: string;
7
+ }): void;
8
+ export declare function convertInt(val: string): number;
package/cli.mjs CHANGED
@@ -1,79 +1,24 @@
1
- import { __addDisposableResource, __disposeResources } from 'tslib';
2
- import { Command, Option } from 'commander';
3
- import { z } from 'zod';
4
- import { globSync } from 'glob';
5
- import * as fs from 'node:fs';
6
- import upath from 'upath';
7
- import { n as normalisePath, l as logger, P as PuyaError, L as LoggingContext, a as LogLevel, b as LocalsCoalescingStrategy, d as defaultPuyaOptions, c as compile } from './index-B46QirKR.js';
1
+ import { BooleanOptionalAction, ArgumentParser } from 'argparse';
2
+ import { cr as LoggingContext, cs as enumFromValue, ct as defaultPuyaOptions, cu as logger, cq as compile, cv as LogLevel, cw as LocalsCoalescingStrategy } from './compile-BcG41O6Z.js';
8
3
  import chalk from 'chalk';
9
- import 'change-case';
10
- import 'node:path';
4
+ import 'node:async_hooks';
11
5
  import 'typescript';
12
6
  import 'node:buffer';
7
+ import 'node:fs';
13
8
  import 'node:util';
9
+ import 'upath';
14
10
  import 'polytype';
11
+ import 'change-case';
12
+ import 'node:path';
13
+ import 'tslib';
15
14
  import 'arcsecond';
15
+ import 'glob';
16
16
  import 'crypto';
17
17
  import 'fs';
18
18
  import 'os';
19
19
  import 'cross-spawn';
20
20
  import 'which';
21
-
22
- const buildCompileOptions = ({ paths, workingDirectory = process.cwd(), outDir, ...rest }) => {
23
- const filePaths = [];
24
- for (const p of paths) {
25
- if (p.endsWith('.algo.ts')) {
26
- if (fs.existsSync(p)) {
27
- const actualPath = normalisePath(p, workingDirectory);
28
- filePaths.push({
29
- matchedInput: p,
30
- sourceFile: actualPath,
31
- outDir: upath.isAbsolute(outDir) ? upath.normalize(outDir) : upath.join(upath.dirname(actualPath), outDir),
32
- });
33
- }
34
- else {
35
- logger.warn(undefined, `File ${p} could not be found`);
36
- }
37
- }
38
- else if (p.endsWith('.ts')) {
39
- logger.warn(undefined, `Ignoring path ${p} as it does use the .algo.ts extension`);
40
- }
41
- else {
42
- const matches = globSync(upath.join(p, '**/*.algo.ts'));
43
- if (matches.length) {
44
- for (const match of matches) {
45
- filePaths.push({
46
- matchedInput: p,
47
- sourceFile: normalisePath(match, workingDirectory),
48
- outDir: upath.join(upath.isAbsolute(outDir) ? outDir : upath.join(p, outDir), upath.relative(p, upath.dirname(match))),
49
- });
50
- }
51
- }
52
- else {
53
- logger.warn(undefined, `Path '${p}' did not match any .algo.ts files`);
54
- }
55
- }
56
- }
57
- if (filePaths.length === 0) {
58
- throw new PuyaError('Input paths did not match any .algo.ts files');
59
- }
60
- return {
61
- filePaths: filePaths.map(replaceOutDirTokens),
62
- ...rest,
63
- getFileFromSource(sourceFile) {
64
- return this.filePaths.find((p) => p.sourceFile === sourceFile);
65
- },
66
- };
67
- };
68
- function replaceOutDirTokens(algoFile) {
69
- const replacements = {
70
- name: upath.basename(algoFile.sourceFile).replace('.algo.ts', ''),
71
- };
72
- return {
73
- ...algoFile,
74
- outDir: algoFile.outDir.replaceAll('[name]', replacements.name),
75
- };
76
- }
21
+ import 'zod';
77
22
 
78
23
  const levelConfig = {
79
24
  /* eslint-disable no-console */
@@ -111,144 +56,212 @@ class ConsoleLogSink {
111
56
  }
112
57
  }
113
58
 
114
- const cmdInteger = () => z.preprocess((x) => (typeof x === 'string' && x.length > 0 ? Number(x) : x), z.number().int());
115
- const cliOptionsSchema = z.object({
116
- outputAwst: z.boolean(),
117
- outputAwstJson: z.boolean(),
118
- outDir: z.string(),
119
- dryRun: z.boolean(),
120
- logLevel: z.nativeEnum(LogLevel),
121
- isolatedFiles: z.boolean(),
122
- // Puya options
123
- outputSourceMap: z.boolean(),
124
- outputTeal: z.boolean(),
125
- outputArc32: z.boolean(),
126
- outputArc56: z.boolean(),
127
- outputSsaIr: z.boolean(),
128
- outputOptimizationIr: z.boolean(),
129
- outputDestructuredIr: z.boolean(),
130
- outputMemoryIr: z.boolean(),
131
- outputBytecode: z.boolean(),
132
- matchAlgodBytecode: z.boolean(),
133
- debugLevel: cmdInteger(),
134
- optimizationLevel: cmdInteger(),
135
- targetAvmVersion: cmdInteger(),
136
- cliTemplateDefinitions: z.preprocess((x) => x ?? [], z.array(z.string())),
137
- templateVarsPrefix: z.string(),
138
- localsCoalescingStrategy: z.nativeEnum(LocalsCoalescingStrategy),
139
- });
140
- const cliArgumentsSchema = z.array(z.string());
141
- function cli() {
142
- const commander = new Command().name('puya-ts').description('Algo-TS to Algorand smart contract compiler');
143
- commander.helpCommand(true);
144
- commander
145
- .command('build')
146
- .argument('<paths...>', 'The path, or paths to search for compatible .algo.ts files')
147
- .addOption(new Option('--log-level [level]', 'The minimum log level to output')
148
- .choices([LogLevel.Debug, LogLevel.Info, LogLevel.Warning, LogLevel.Error, LogLevel.Critical])
149
- .default(LogLevel.Info))
150
- .addOption(new Option('--output-awst', 'Output debugging awst file per parsed file').default(false))
151
- .addOption(new Option('--output-awst-json', 'Output debugging awst json file per parsed file').default(false))
152
- .addOption(new Option('--out-dir [outDir]').default('out'))
153
- .addOption(new Option('--dry-run', "Just parse typescript files, don't invoke puya compiler").default(false))
154
- .addOption(new Option('--isolated-files', 'Invoke compilation on each input file individually').default(false))
155
- .addOption(new Option('--no-output-teal', 'Do not output TEAL code').default(defaultPuyaOptions.outputTeal))
156
- .addOption(new Option('--output-source-map', 'Output debug source maps ').default(defaultPuyaOptions.outputSourceMap))
157
- .addOption(new Option('--no-output-arc32', 'Do not output {contract}.arc32.json ARC-32 app spec file. Only applicable to ARC4 contracts').default(defaultPuyaOptions.outputArc32))
158
- .addOption(new Option('--output-arc56', 'Output {contract}.arc56.json ARC-56 app spec file. Only applicable to ARC4 contracts').default(defaultPuyaOptions.outputArc56))
159
- .addOption(new Option('--output-ssa-ir', 'Output IR (in SSA form) before optimisations').default(defaultPuyaOptions.outputSsaIr))
160
- .addOption(new Option('--output-optimization-ir', 'Output IR after each optimization').default(defaultPuyaOptions.outputOptimizationIr))
161
- .addOption(new Option('--output-destructured-ir', 'Output IR after SSA destructuring and before MIR').default(defaultPuyaOptions.outputDestructuredIr))
162
- .addOption(new Option('--output-memory-ir', 'Output MIR before lowering to TealOps').default(defaultPuyaOptions.outputMemoryIr))
163
- .addOption(new Option('--output-bytecode', 'Output AVM bytecode').default(defaultPuyaOptions.outputBytecode))
164
- .addOption(new Option('--match-algod-bytecode', 'When outputting bytecode, ensure bytecode matches algod output').default(defaultPuyaOptions.matchAlgodBytecode))
165
- .addOption(new Option('--debug-level [level]', 'Output debug information level, 0 = none, 1 = debug, 2 = reserved for future use')
166
- .choices(['0', '1', '2'])
167
- .default(defaultPuyaOptions.debugLevel))
168
- .addOption(new Option('--optimization-level [level]', 'Set optimization level of output TEAL / AVM bytecode')
169
- .choices(['0', '1', '2'])
170
- .default(defaultPuyaOptions.optimizationLevel))
171
- .addOption(new Option('--target-avm-version [version]', '').choices(['10', '11']).default(10))
172
- .addOption(new Option('--cli-template-definitions <...definitions>', 'Define template vars for use when assembling via --output-bytecode, should be specified without the prefix (see --template-vars-prefix)'))
173
- .addOption(new Option('--template-vars-prefix [prefix]', 'Define the prefix to use with --template-var').default(defaultPuyaOptions.templateVarsPrefix))
174
- .addOption(new Option('--locals-coalescing-strategy', '')
175
- .default(defaultPuyaOptions.localsCoalescingStrategy)
176
- .choices([
177
- LocalsCoalescingStrategy.root_operand,
178
- LocalsCoalescingStrategy.root_operand_excluding_args,
179
- LocalsCoalescingStrategy.aggressive,
180
- ]))
181
- .action((a, o) => {
182
- const env_1 = { stack: [], error: void 0, hasError: false };
59
+ function addEnumArg(parser, { name, enumType, default: defaultValue, help }) {
60
+ parser.add_argument(name, {
61
+ type: (v) => enumFromValue(v, enumType),
62
+ choices: Array.from(Object.values(enumType)),
63
+ default: defaultValue,
64
+ help,
65
+ });
66
+ }
67
+ function convertInt(val) {
68
+ const res = Number(val);
69
+ if (isNaN(res) || Math.round(res) !== res) {
70
+ throw new Error(`'${val}' could not be converted to a number`);
71
+ }
72
+ return res;
73
+ }
74
+
75
+ function addBuildCommand(subparsers) {
76
+ const buildParser = subparsers.add_parser('build', {
77
+ description: 'Build a smart contract or logic signature',
78
+ help: `When provided with a directory or .algo.ts file, parses and compiles all smart contracts and logic signatures found in the directory or file and outputs compilation artifacts.`,
79
+ });
80
+ addEnumArg(buildParser, {
81
+ name: '--log-level',
82
+ default: LogLevel.Info,
83
+ enumType: LogLevel,
84
+ help: 'The minimum log level to output',
85
+ });
86
+ buildParser.add_argument('--output-awst', {
87
+ help: 'Output debugging awst file per parsed file',
88
+ default: false,
89
+ action: BooleanOptionalAction,
90
+ });
91
+ buildParser.add_argument('--output-awst-json', {
92
+ action: BooleanOptionalAction,
93
+ default: false,
94
+ help: 'Output debugging awst json file per parsed file',
95
+ });
96
+ buildParser.add_argument('--dry-run', {
97
+ action: BooleanOptionalAction,
98
+ default: false,
99
+ help: "Just parse typescript files, don't invoke puya compiler",
100
+ });
101
+ buildParser.add_argument('--skip-version-check', {
102
+ action: BooleanOptionalAction,
103
+ default: false,
104
+ help: "Don't verify installed puya compiler version matches targeted version",
105
+ });
106
+ buildParser.add_argument('--output-teal', {
107
+ action: BooleanOptionalAction,
108
+ help: 'Output TEAL code',
109
+ default: defaultPuyaOptions.outputTeal,
110
+ });
111
+ buildParser.add_argument('--output-source-map', {
112
+ action: BooleanOptionalAction,
113
+ help: 'Output debug source maps ',
114
+ default: defaultPuyaOptions.outputSourceMap,
115
+ });
116
+ buildParser.add_argument('--output-arc32', {
117
+ action: BooleanOptionalAction,
118
+ help: 'Output {contract}.arc32.json ARC-32 app spec file. Only applicable to ARC4 contracts ',
119
+ default: defaultPuyaOptions.outputArc32,
120
+ });
121
+ buildParser.add_argument('--output-arc56', {
122
+ action: BooleanOptionalAction,
123
+ help: 'Output {contract}.arc56.json ARC-56 app spec file. Only applicable to ARC4 contracts ',
124
+ default: defaultPuyaOptions.outputArc56,
125
+ });
126
+ buildParser.add_argument('--output-ssa-ir', {
127
+ action: BooleanOptionalAction,
128
+ help: 'Output IR (in SSA form) before optimisations',
129
+ default: defaultPuyaOptions.outputSsaIr,
130
+ });
131
+ buildParser.add_argument('--output-optimization-ir', {
132
+ action: BooleanOptionalAction,
133
+ help: 'Output IR after each optimization',
134
+ default: defaultPuyaOptions.outputOptimizationIr,
135
+ });
136
+ buildParser.add_argument('--output-destructured-ir', {
137
+ action: BooleanOptionalAction,
138
+ help: 'Output IR after SSA destructuring and before MIR',
139
+ default: defaultPuyaOptions.outputDestructuredIr,
140
+ });
141
+ buildParser.add_argument('--output-memory-ir', {
142
+ action: BooleanOptionalAction,
143
+ help: 'Output MIR before lowering to TealOps',
144
+ default: defaultPuyaOptions.outputMemoryIr,
145
+ });
146
+ buildParser.add_argument('--output-bytecode', {
147
+ action: BooleanOptionalAction,
148
+ help: 'Output AVM bytecode',
149
+ default: defaultPuyaOptions.outputBytecode,
150
+ });
151
+ buildParser.add_argument('--match-algod-bytecode', {
152
+ action: BooleanOptionalAction,
153
+ help: 'When outputting bytecode, ensure bytecode matches algod output',
154
+ default: defaultPuyaOptions.matchAlgodBytecode,
155
+ });
156
+ buildParser.add_argument('--out-dir', {
157
+ action: 'store',
158
+ help: 'Where to output builder artifacts. Can use [name] placeholder to include contract name in path',
159
+ default: 'out',
160
+ });
161
+ buildParser.add_argument('--debug-level', {
162
+ default: defaultPuyaOptions.debugLevel.toString(),
163
+ choices: ['0', '1', '2'],
164
+ help: 'Output debug information level, 0 = none, 1 = debug, 2 = reserved for future use',
165
+ });
166
+ buildParser.add_argument('--optimization-level', {
167
+ default: defaultPuyaOptions.optimizationLevel.toString(),
168
+ choices: ['0', '1', '2'],
169
+ help: 'Set optimization level of output TEAL / AVM bytecode, 0 = none, 1 = normal, 2 = intensive',
170
+ });
171
+ buildParser.add_argument('--target-avm-version', {
172
+ default: defaultPuyaOptions.targetAvmVersion.toString(),
173
+ choices: ['10', '11'],
174
+ help: 'Select the targeted AVM version for compilation output',
175
+ });
176
+ buildParser.add_argument('--cli-template-definitions', {
177
+ metavar: 'VAR=VALUE',
178
+ nargs: '+',
179
+ help: 'Define template vars for use when assembling via --output-bytecode, should be specified without the prefix (see --template-vars-prefix)',
180
+ });
181
+ buildParser.add_argument('--template-vars-prefix', {
182
+ help: 'Define the prefix to use with --template-var',
183
+ default: defaultPuyaOptions.templateVarsPrefix,
184
+ });
185
+ addEnumArg(buildParser, {
186
+ name: '--locals-coalescing-strategy',
187
+ enumType: LocalsCoalescingStrategy,
188
+ help: 'Strategy choice for out-of-ssa local variable coalescing. The best choice for your app is best determined through experimentation',
189
+ default: defaultPuyaOptions.localsCoalescingStrategy,
190
+ });
191
+ buildParser.add_argument('paths', {
192
+ metavar: 'PATHS',
193
+ nargs: '+',
194
+ help: 'The path, or paths to search for compatible .algo.ts files',
195
+ });
196
+ buildParser.set_defaults({
197
+ command: 'build',
198
+ });
199
+ }
200
+ async function buildCommand(args) {
201
+ const logCtx = LoggingContext.create();
202
+ return logCtx.run(async () => {
203
+ logger.configure([new ConsoleLogSink(args.log_level)]);
183
204
  try {
184
- const logCtx = __addDisposableResource(env_1, LoggingContext.create(), false);
185
- logger.configure([new ConsoleLogSink(LogLevel.Warning)]);
186
- try {
187
- const paths = cliArgumentsSchema.parse(a);
188
- const cliOptions = cliOptionsSchema.parse(o);
189
- logger.configure([new ConsoleLogSink(cliOptions.logLevel)]);
190
- const compileOptions = buildCompileOptions({
191
- paths,
192
- ...cliOptions,
193
- });
194
- const passThroughOptions = cliOptions;
195
- if (cliOptions.isolatedFiles) {
196
- let anyHasErrors = false;
197
- for (const file of compileOptions.filePaths) {
198
- const env_2 = { stack: [], error: void 0, hasError: false };
199
- try {
200
- const logCtx = __addDisposableResource(env_2, LoggingContext.create(), false);
201
- try {
202
- compile({
203
- ...compileOptions,
204
- filePaths: [file],
205
- }, passThroughOptions);
206
- }
207
- catch (e) {
208
- logger.critical(undefined, `Compilation failure: ${e}`);
209
- }
210
- anyHasErrors ||= logCtx.hasErrors();
211
- }
212
- catch (e_1) {
213
- env_2.error = e_1;
214
- env_2.hasError = true;
215
- }
216
- finally {
217
- __disposeResources(env_2);
218
- }
219
- }
220
- if (anyHasErrors) {
221
- process.exit(-1);
222
- }
223
- }
224
- else {
225
- compile(compileOptions, passThroughOptions);
226
- logCtx.exitIfErrors();
227
- }
205
+ await compile({
206
+ paths: args.paths,
207
+ outputAwst: args.output_awst,
208
+ outputAwstJson: args.output_awst_json,
209
+ outDir: args.out_dir,
210
+ skipVersionCheck: args.skip_version_check,
211
+ dryRun: args.dry_run,
212
+ logLevel: args.log_level,
213
+ outputTeal: args.output_teal,
214
+ outputArc32: args.output_arc32,
215
+ outputArc56: args.output_arc56,
216
+ outputSsaIr: args.output_ssa_ir,
217
+ outputOptimizationIr: args.output_optimization_ir,
218
+ outputDestructuredIr: args.output_destructured_ir,
219
+ outputMemoryIr: args.output_memory_ir,
220
+ outputBytecode: args.output_bytecode,
221
+ outputSourceMap: args.output_source_map,
222
+ matchAlgodBytecode: args.match_algod_bytecode,
223
+ debugLevel: convertInt(args.debug_level),
224
+ optimizationLevel: convertInt(args.optimization_level),
225
+ targetAvmVersion: convertInt(args.target_avm_version),
226
+ cliTemplateDefinitions: args.cli_template_definitions,
227
+ templateVarsPrefix: args.template_vars_prefix,
228
+ localsCoalescingStrategy: args.locals_coalescing_strategy,
229
+ });
230
+ logCtx.exitIfErrors();
231
+ }
232
+ catch (e) {
233
+ if (e instanceof Error) {
234
+ logger.error(e);
228
235
  }
229
- catch (e) {
230
- if (e instanceof Error) {
231
- logger.error(e);
232
- }
233
- else {
234
- throw e;
235
- }
236
+ else {
237
+ throw e;
236
238
  }
237
239
  }
238
- catch (e_2) {
239
- env_1.error = e_2;
240
- env_1.hasError = true;
241
- }
242
- finally {
243
- __disposeResources(env_1);
244
- }
245
240
  });
246
- if (process.argv.length < 3) {
247
- commander.help();
248
- }
249
- else {
250
- commander.parse(process.argv);
241
+ }
242
+
243
+ async function parseCliArguments() {
244
+ const parser = new ArgumentParser({
245
+ prog: 'puya-ts',
246
+ });
247
+ parser.add_argument('--version', {
248
+ action: 'version',
249
+ version: 'puya-ts TODO',
250
+ });
251
+ parser.set_defaults({
252
+ command: 'none',
253
+ });
254
+ addBuildCommand(parser.add_subparsers());
255
+ const result = parser.parse_args();
256
+ switch (result.command) {
257
+ case 'build':
258
+ await buildCommand(result);
259
+ break;
260
+ default:
261
+ parser.print_help();
262
+ break;
251
263
  }
252
264
  }
253
- cli();
265
+
266
+ void parseCliArguments();
254
267
  //# sourceMappingURL=cli.mjs.map