pg-proto-parser
Version:
The LaunchQL Proto parser
212 lines (211 loc) • 10.6 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateTypeImportSpecifiers = exports.convertTypeToTsInterface = exports.generateNodeUnionTypeObjectKeys = exports.generateNodeUnionType = exports.generateWrappedAstHelperMethods = exports.generateAstHelperMethods = exports.generateTypeImports = void 0;
const t = __importStar(require("@babel/types"));
const utils_1 = require("../../utils");
const constants_1 = require("../../constants");
const utils_2 = require("./utils");
/**
* Generates import statements for types from a specified source module.
* Can optionally add a suffix to imported type names (e.g., import { Type as TypeSuffix })
* Used when types need to be imported into other generated files.
*/
const generateTypeImports = (types, source, suffix) => {
return suffix ?
(0, utils_1.createNamedImportAsSuffix)(types.map(e => e.name), source, suffix) :
(0, utils_1.createNamedImport)(types.map(e => e.name), source);
};
exports.generateTypeImports = generateTypeImports;
/**
* Generates helper factory methods for creating AST node instances.
* Creates an object with camelCase methods for each type (e.g., selectStmt() for SelectStmt type).
* Each method accepts optional initial values and returns the type directly.
* Example output: { selectStmt: (_p?: SelectStmt) => SelectStmt }
*/
const generateAstHelperMethods = (types) => {
const creators = types.map((type) => {
const typeName = type.name;
const param = t.identifier('_p');
param.optional = true;
param.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(typeName)));
let init = [];
// @ts-ignore
const fields = type.fields;
const astNodeInit = t.variableDeclaration('const', [
t.variableDeclarator(t.identifier('_j'), t.tsAsExpression(t.objectExpression(init), t.tsTypeReference(t.identifier(typeName))))
]);
const setStatements = Object.entries(fields)
.map(([fName, field]) => {
const fieldName = (0, utils_1.getFieldName)(field, fName);
return t.expressionStatement(t.callExpression(t.memberExpression(t.identifier('_o'), t.identifier('set')), [
t.identifier('_j'),
t.stringLiteral(fieldName),
t.optionalMemberExpression(t.identifier('_p'), t.identifier(fieldName), false, true)
]));
});
// Ensures camel case
const methodName = (0, utils_1.toSpecialCamelCase)(typeName);
// Create the method
const method = t.objectMethod('method', t.identifier(methodName), [param], t.blockStatement([
astNodeInit,
...setStatements,
t.returnStatement(t.identifier('_j'))
]));
// Set return type to just the type
method.returnType = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(typeName)));
return method;
});
return t.exportDefaultDeclaration(t.objectExpression(creators));
};
exports.generateAstHelperMethods = generateAstHelperMethods;
/**
* Generates helper factory methods that return AST nodes wrapped in a type-specific object.
* Creates an object with camelCase methods for each type (e.g., selectStmt() for SelectStmt type).
* Each method accepts optional initial values and returns { TypeName: TypeInstance }.
* Example output: { selectStmt: (_p?: SelectStmt) => { SelectStmt: SelectStmt } }
*/
const generateWrappedAstHelperMethods = (types) => {
const creators = types.map((type) => {
const typeName = type.name;
const param = t.identifier('_p');
param.optional = true;
param.typeAnnotation = t.tsTypeAnnotation(t.tsTypeReference(t.identifier(typeName)));
let init = [];
// @ts-ignore
const fields = type.fields;
const astNodeInit = t.variableDeclaration('const', [
t.variableDeclarator(t.identifier('_j'), t.tsAsExpression(t.objectExpression(init), t.tsTypeReference(t.identifier(typeName))))
]);
const setStatements = Object.entries(fields)
.map(([fName, field]) => {
const fieldName = (0, utils_1.getFieldName)(field, fName);
return t.expressionStatement(t.callExpression(t.memberExpression(t.identifier('_o'), t.identifier('set')), [
t.identifier('_j'),
t.stringLiteral(fieldName),
t.optionalMemberExpression(t.identifier('_p'), t.identifier(fieldName), false, true)
]));
});
// Return the wrapped object
const wrappedReturn = t.returnStatement(t.objectExpression([
t.objectProperty(t.identifier(typeName), t.identifier('_j'))
]));
// Ensures camel case
const methodName = (0, utils_1.toSpecialCamelCase)(typeName);
// Create the method
const method = t.objectMethod('method', t.identifier(methodName), [param], t.blockStatement([
astNodeInit,
...setStatements,
wrappedReturn
]));
// Set return type to the wrapped type
const wrappedType = t.tsTypeLiteral([
t.tsPropertySignature(t.identifier(typeName), t.tsTypeAnnotation(t.tsTypeReference(t.identifier(typeName))))
]);
method.returnType = t.tsTypeAnnotation(wrappedType);
return method;
});
return t.exportDefaultDeclaration(t.objectExpression(creators));
};
exports.generateWrappedAstHelperMethods = generateWrappedAstHelperMethods;
/**
* Generates a TypeScript union type named 'Node' that includes all AST node types.
* Can generate either a simple union (Type1 | Type2 | ...) or wrapped objects ({ Type1: Type1 } | { Type2: Type2 } | ...)
* based on the wrappedNodeTypeExport option. This is the main type used to represent any AST node.
*/
const generateNodeUnionType = (options, types) => {
if (options.types.wrappedNodeTypeExport) {
return (0, exports.generateNodeUnionTypeObjectKeys)(types);
}
const unionTypeNames = types.map(type => t.tsTypeReference(t.identifier(type.name)));
const unionTypeAlias = t.tsTypeAliasDeclaration(t.identifier(constants_1.NODE_TYPE), null, t.tsUnionType(unionTypeNames));
return t.exportNamedDeclaration(unionTypeAlias, []);
};
exports.generateNodeUnionType = generateNodeUnionType;
/**
* Generates a Node union type where each type is wrapped in an object with the type name as key.
* Example output: type Node = { SelectStmt: SelectStmt } | { InsertStmt: InsertStmt } | ...
* This format makes it easier to determine the specific type of a node at runtime.
*/
const generateNodeUnionTypeObjectKeys = (types) => {
// Mapping types to TypeScript object type annotations
const unionTypeNames = types.map(type => t.tsTypeLiteral([
t.tsPropertySignature(t.identifier(type.name), t.tsTypeAnnotation(t.tsTypeReference(t.identifier(type.name))))
]));
// Creating the TypeScript union type
const unionTypeAlias = t.tsTypeAliasDeclaration(t.identifier(constants_1.NODE_TYPE), null, t.tsUnionType(unionTypeNames));
// Exporting the union type declaration
return t.exportNamedDeclaration(unionTypeAlias, []);
};
exports.generateNodeUnionTypeObjectKeys = generateNodeUnionTypeObjectKeys;
const extractTypeFieldsAsTsProperties = (type, options) => {
// @ts-ignore
const fields = type.fields;
const properties = Object.entries(fields)
.map(([fieldName, field]) => {
const type = (0, utils_2.resolveTypeName)(field.type);
const fieldType = field.rule === 'repeated' ?
t.tsArrayType(type) :
type;
const prop = t.tsPropertySignature(t.identifier((0, utils_1.getFieldName)(field, fieldName)), t.tsTypeAnnotation(fieldType));
prop.optional = options.types.optionalFields;
return prop;
});
return properties;
};
/**
* Converts a protobuf Type definition into a TypeScript interface declaration.
* Handles field types, arrays (repeated fields), and optional fields based on options.
* Example: Type "SelectStmt" with fields becomes: export interface SelectStmt { field1?: Type1; ... }
*/
const convertTypeToTsInterface = (type, options) => {
const typeName = type.name;
const properties = extractTypeFieldsAsTsProperties(type, options);
const interfaceDecl = t.tsInterfaceDeclaration(t.identifier(typeName), null, [], t.tsInterfaceBody(properties));
// Wrap the interface declaration in an export statement
return t.exportNamedDeclaration(interfaceDecl, []);
};
exports.convertTypeToTsInterface = convertTypeToTsInterface;
/**
* Generates import specifiers for types from the configured types source.
* Used in ast-helpers to import all the type definitions.
* Example output: import { SelectStmt, InsertStmt, ... } from './types';
*/
const generateTypeImportSpecifiers = (types, options) => {
const importSpecifiers = types.map(type => t.importSpecifier(t.identifier(type.name), t.identifier(type.name)));
const importDeclaration = t.importDeclaration(importSpecifiers, t.stringLiteral(options.utils.astHelpers.typesSource));
return importDeclaration;
};
exports.generateTypeImportSpecifiers = generateTypeImportSpecifiers;