Python TypeScript AST Generator - Create TypeScript code from Python
Project description
pytsast - Python TypeScript AST Generator
Generate TypeScript code from Python using TypeScript's AST factory API.
This library provides a Python interface to TypeScript's AST factory functions, allowing you to build TypeScript AST nodes programmatically and serialize them to JSON for consumption by TypeScript parsers like @pyts/tsparser.
Installation
pip install pytsast
Usage
Basic Example
from pytsast import factory as ts
# Create a simple identifier
identifier = ts.createIdentifier("myVariable")
# Serialize to JSON
json_output = identifier.serialize()
print(json_output.model_dump_json(indent=2))
Creating Complex Structures
from pytsast import factory as ts
# Create an import declaration
import_decl = ts.createImportDeclaration(
None,
ts.createImportClause(
None,
ts.createIdentifier("zod"),
ts.createNamedImports([
ts.createImportSpecifier(
False, None, ts.createIdentifier("output")
)
]),
),
ts.createStringLiteral("zod"),
None,
)
# Create a function declaration
func_decl = ts.createFunctionDeclaration(
None,
None,
ts.createIdentifier("greet"),
None,
[
ts.createParameterDeclaration(
None, None, ts.createIdentifier("name"), None,
ts.createTypeReferenceNode(ts.createIdentifier("string"), None), None
)
],
ts.createTypeReferenceNode(ts.createIdentifier("string"), None),
ts.createBlock([
ts.createReturnStatement(
ts.createBinaryExpression(
ts.createStringLiteral("Hello, "),
ts.createToken(ts.SyntaxKind.PlusToken),
ts.createIdentifier("name")
)
)
], True)
)
# Serialize both
print("Import:", import_decl.serialize().model_dump_json())
print("Function:", func_decl.serialize().model_dump_json())
Low-Level Node Creation
from pytsast.core import Node
from pytsast.nodes.misc import Parameter
# Create nodes directly
param = Parameter(
decorators=None,
modifiers=None,
dot_dot_dot_token=None,
name=ts.createIdentifier("arg"),
question_token=None,
type_annotation=ts.createTypeReferenceNode(ts.createIdentifier("number"), None),
initializer=None
)
API
Factory Functions
The factory module mirrors TypeScript's ts.factory API:
createIdentifier(text: str)- Create identifier nodecreateStringLiteral(text: str)- Create string literalcreateNumericLiteral(value: str | int | float)- Create numeric literalcreateImportDeclaration(decorators, modifiers, import_clause, module_specifier, assert_clause)- Create import statementcreateFunctionDeclaration(decorators, modifiers, asterisk_token, name, type_parameters, parameters, type, body)- Create function declarationcreateClassDeclaration(decorators, modifiers, name, type_parameters, heritage_clauses, members)- Create class declarationcreateVariableStatement(modifiers, declaration_list)- Create variable statementcreateTypeAliasDeclaration(modifiers, name, type_parameters, type)- Create type alias- And many more...
Core Classes
Node- Base AST node class with serializationSyntaxKind- Enum of TypeScript syntax kindsNodeFlags- Node flags enum
Node Types
Statement- Base for statements (function declarations, etc.)Expression- Base for expressions (identifiers, literals, etc.)Declaration- Base for declarationsTypeNode- Base for type annotations
Serialization Format
Nodes serialize to JSON objects that can be consumed by TypeScript parsers:
{
"type": "factory",
"name": "createIdentifier",
"args": [
{
"type": "literal",
"value": "myVariable"
}
]
}
Node Types
- literal:
{ "type": "literal", "value": null | boolean | string } - number:
{ "type": "number", "value": number | string } - undefined:
{ "type": "undefined" } - factory:
{ "type": "factory", "name": string, "args": SerializedNode[] }
Integration with tsparser
pytsast is designed to work with @pyts/tsparser to generate actual TypeScript code:
# Python side (pytsast)
from pytsast import factory as ts
import json
node = ts.createIdentifier("hello")
json_str = json.dumps(node.serialize().model_dump())
# Send json_str to TypeScript side
// TypeScript side (@pyts/tsparser)
import { parseAndPrint } from '@pyts/tsparser';
const jsonFromPython = '...'; // JSON from Python
const tsCode = parseAndPrint(jsonFromPython);
console.log(tsCode); // hello
Complete Example
# Python: Generate a complete TypeScript interface
from pytsast import factory as ts
import json
interface = ts.createInterfaceDeclaration(
None, # decorators
None, # modifiers
ts.createIdentifier("User"),
None, # type parameters
None, # heritage clauses
[
ts.createPropertySignature(
None, # modifiers
ts.createIdentifier("id"),
None, # question token
ts.createTypeReferenceNode(ts.createIdentifier("number"), None)
),
ts.createPropertySignature(
None,
ts.createIdentifier("name"),
None,
ts.createTypeReferenceNode(ts.createIdentifier("string"), None)
)
]
)
json_output = json.dumps(interface.serialize().model_dump(), indent=2)
print(json_output)
// TypeScript: Parse and generate code
import { parseAndPrint } from '@pyts/tsparser';
const jsonFromPython = `...`; // The JSON above
const tsCode = parseAndPrint(jsonFromPython);
console.log(tsCode);
// Output:
// interface User {
// id: number;
// name: string;
// }
Architecture
pytsast/core/- Base types, serialization, and syntax kindspytsast/nodes/- AST node definitions and implementationspytsast/factory.py- Factory functions (mirrorsts.factory)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pytsast-0.1.6.tar.gz.
File metadata
- Download URL: pytsast-0.1.6.tar.gz
- Upload date:
- Size: 32.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
86a5d943253ab1c23d198b9f5a269fd74e4cdc8ae3591a86ee3b9e2dade58d0c
|
|
| MD5 |
37e768ecc28fb054fd2246ecf9dbdf77
|
|
| BLAKE2b-256 |
0295ad97a44e1292a7af45548e1537211b081595468e9425aa9b80f761895f60
|
Provenance
The following attestation bundles were made for pytsast-0.1.6.tar.gz:
Publisher:
release-please.yaml on jraylan/pytsast
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pytsast-0.1.6.tar.gz -
Subject digest:
86a5d943253ab1c23d198b9f5a269fd74e4cdc8ae3591a86ee3b9e2dade58d0c - Sigstore transparency entry: 799029124
- Sigstore integration time:
-
Permalink:
jraylan/pytsast@f4d79d7ccf706d308b9a24d865bda2a8e05f9d46 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/jraylan
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release-please.yaml@f4d79d7ccf706d308b9a24d865bda2a8e05f9d46 -
Trigger Event:
push
-
Statement type:
File details
Details for the file pytsast-0.1.6-py3-none-any.whl.
File metadata
- Download URL: pytsast-0.1.6-py3-none-any.whl
- Upload date:
- Size: 39.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d90a0bc04d43420bec2e957f9ddb5daa0d0bb91d4a7a1d4ad89e9e10f9526839
|
|
| MD5 |
62cc6da3967107779e6615d626b0bd14
|
|
| BLAKE2b-256 |
13dd4773c59676f694087f60be5fb04e1da695dfa2db698cd180d4c08ef0064f
|
Provenance
The following attestation bundles were made for pytsast-0.1.6-py3-none-any.whl:
Publisher:
release-please.yaml on jraylan/pytsast
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pytsast-0.1.6-py3-none-any.whl -
Subject digest:
d90a0bc04d43420bec2e957f9ddb5daa0d0bb91d4a7a1d4ad89e9e10f9526839 - Sigstore transparency entry: 799029125
- Sigstore integration time:
-
Permalink:
jraylan/pytsast@f4d79d7ccf706d308b9a24d865bda2a8e05f9d46 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/jraylan
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release-please.yaml@f4d79d7ccf706d308b9a24d865bda2a8e05f9d46 -
Trigger Event:
push
-
Statement type: