New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@potygen/cli

Package Overview
Dependencies
Maintainers
1
Versions
82
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@potygen/cli - npm Package Compare versions

Comparing version
0.8.2
to
0.9.0
+77
dist/emitter.d.ts
import { LoadContext } from '@potygen/potygen';
/**
* Handle both "last updated" checks on files as well as actually checking file contents.
*/
export declare class CacheStore {
/**
* Path to the cache file
*/
fileName: string;
/**
* If enabled is false, do not perform any caching
*/
enabled: boolean;
/**
* If true, initialize the cache with empty values so that after save everything is overwritten
*/
cacheClear: boolean;
/**
* Current version of the cache, if version mismatch, clear the cache
*/
cacheVersion: string;
contents: Map<string, {
path: string;
content: string;
} | undefined>;
updates: Map<string, number>;
constructor(
/**
* Path to the cache file
*/
fileName: string,
/**
* If enabled is false, do not perform any caching
*/
enabled?: boolean,
/**
* If true, initialize the cache with empty values so that after save everything is overwritten
*/
cacheClear?: boolean,
/**
* Current version of the cache, if version mismatch, clear the cache
*/
cacheVersion?: string);
/**
* Check the file's last modified time (mtime).
* If its after the time stored in cache, consider the file stale.
*/
isStale(path: string): Promise<boolean>;
/**
* For a given path and file content, check if content is present in the cache.
* If it is not, run the process function and store the results in the cache,
* keyed by md5 of the initial content
*/
cachedOrProcessed(path: string, content: string, process: (path: string, content: string) => Promise<{
path: string;
content: string;
} | undefined>): Promise<{
path: string;
content: string;
isCached?: boolean;
} | undefined>;
/**
* Load the cache from file
*/
load(): Promise<void>;
/**
* Save current state in the cache file
*/
save(): Promise<void>;
}
export declare const toEmitter: (ctx: LoadContext, cacheStore: CacheStore, options: {
root: string;
template: string;
typePrefix?: string;
}) => Promise<(path: string) => Promise<{
path: string;
} | undefined>>;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toEmitter = exports.CacheStore = void 0;
const fs_1 = require("fs");
const typescript_1 = require("typescript");
const path_1 = require("path");
const potygen_1 = require("@potygen/potygen");
const typescript_printer_1 = require("./typescript-printer");
const promises_1 = require("fs/promises");
const crypto_1 = require("crypto");
/**
* Handle both "last updated" checks on files as well as actually checking file contents.
*/
class CacheStore {
constructor(
/**
* Path to the cache file
*/
fileName,
/**
* If enabled is false, do not perform any caching
*/
enabled = false,
/**
* If true, initialize the cache with empty values so that after save everything is overwritten
*/
cacheClear = false,
/**
* Current version of the cache, if version mismatch, clear the cache
*/
cacheVersion = '1.0') {
this.fileName = fileName;
this.enabled = enabled;
this.cacheClear = cacheClear;
this.cacheVersion = cacheVersion;
this.contents = new Map();
this.updates = new Map();
}
/**
* Check the file's last modified time (mtime).
* If its after the time stored in cache, consider the file stale.
*/
async isStale(path) {
if (!this.enabled) {
return true;
}
const mtime = (await (0, promises_1.stat)(path)).mtime.getTime();
const currentMtime = this.updates.get(path);
return !(currentMtime && mtime === currentMtime);
}
/**
* For a given path and file content, check if content is present in the cache.
* If it is not, run the process function and store the results in the cache,
* keyed by md5 of the initial content
*/
async cachedOrProcessed(path, content, process) {
if (!this.enabled) {
return await process(path, content);
}
const key = (0, crypto_1.createHash)('md5').update(content).digest('hex');
const cached = this.contents.get(key);
if (cached) {
return { ...cached, isCached: true };
}
else {
const processed = await process(path, content);
const mtime = (await (0, promises_1.stat)(path)).mtime.getTime();
this.contents.set(key, processed);
this.updates.set(path, mtime);
return processed;
}
}
/**
* Load the cache from file
*/
async load() {
if (!this.cacheClear && (0, fs_1.existsSync)(this.fileName)) {
const cache = JSON.parse(await (0, promises_1.readFile)(this.fileName, 'utf-8'));
if (typeof cache === 'object' && cache !== null && 'version' in cache && cache.version === this.cacheVersion) {
this.updates = new Map(Object.entries(cache.updates));
this.contents = new Map(Object.entries(cache.contents));
}
}
}
/**
* Save current state in the cache file
*/
async save() {
await (0, promises_1.mkdir)((0, path_1.dirname)(this.fileName), { recursive: true });
await (0, promises_1.writeFile)(this.fileName, JSON.stringify({
updates: Object.fromEntries(this.updates),
contents: Object.fromEntries(this.contents),
version: this.cacheVersion,
}), 'utf-8');
}
}
exports.CacheStore = CacheStore;
const toTemplateParent = (node) => (0, typescript_1.isCallExpression)(node.parent) ? toTemplateParent(node.parent) : node.parent;
/**
* Extract the sql tagged template literals from a typescript ast
*/
const getTemplateTagQueries = (ast) => {
const queries = [];
let tagPropertyName = 'sql';
const visitor = (node) => {
if ((0, typescript_1.isImportDeclaration)(node) &&
(0, typescript_1.isStringLiteral)(node.moduleSpecifier) &&
node.importClause?.namedBindings &&
(0, typescript_1.isNamedImports)(node.importClause.namedBindings) &&
node.moduleSpecifier.text === '@potygen/potygen') {
tagPropertyName =
node.importClause?.namedBindings.elements.find(({ propertyName, name }) => (propertyName ?? name).text === 'sql')?.name.text ?? tagPropertyName;
}
else if ((0, typescript_1.isTaggedTemplateExpression)(node) &&
(0, typescript_1.isNoSubstitutionTemplateLiteral)(node.template) &&
(0, typescript_1.isIdentifier)(node.tag) &&
node.tag.text === tagPropertyName) {
const tag = {
name: toTemplateParent(node).getChildAt(0).getText(),
pos: node.template.pos + 1,
template: node.template.text,
};
try {
queries.push({ ...tag, queryInterface: (0, potygen_1.toQueryInterface)((0, potygen_1.parser)(node.template.text).ast) });
}
catch (error) {
throw new potygen_1.ParseError(tag, `Error parsing sql: ${String(error)}`);
}
}
else {
node.forEachChild(visitor);
}
};
visitor(ast);
return queries;
};
const parseFile = (path, content) => {
if (path.endsWith('.ts')) {
const source = (0, typescript_1.createSourceFile)((0, path_1.basename)(path), content, typescript_1.ScriptTarget.ES2021, true);
const file = { type: 'ts', source, path, queries: getTemplateTagQueries(source) };
return file.queries.length > 0 ? file : undefined;
}
else {
return { type: 'sql', path, content, queryInterface: (0, potygen_1.toQueryInterface)((0, potygen_1.parser)(content).ast) };
}
};
const isError = (error) => error instanceof potygen_1.LoadError || error instanceof potygen_1.ParseError;
const toLoadFile = (data) => (file) => {
if (file.type === 'sql') {
try {
return { ...file, loadedQuery: (0, potygen_1.toLoadedQueryInterface)(data)(file.queryInterface) };
}
catch (error) {
throw isError(error) ? new potygen_1.ParsedSqlFileLoadError(file, error) : error;
}
}
else {
return {
...file,
queries: file.queries.map((template) => {
try {
return { ...template, loadedQuery: (0, potygen_1.toLoadedQueryInterface)(data)(template.queryInterface) };
}
catch (error) {
throw isError(error) ? new potygen_1.ParsedTypescriptFileLoadError(file, template, error) : error;
}
}),
};
}
};
const toEmitter = async (ctx, cacheStore, options) => {
const data = await (0, potygen_1.loadAllData)(ctx, []);
const loadFile = toLoadFile(data);
const typeScriptPrinter = (0, typescript_printer_1.toTypeScriptPrinter)(options.root, options.template, options.typePrefix);
return async (path) => {
const start = process.hrtime();
const relPath = (0, path_1.relative)(options.root ?? '.', path);
try {
if (await cacheStore.isStale(path)) {
const content = await (0, promises_1.readFile)(path, 'utf-8');
const output = await cacheStore.cachedOrProcessed(path, content, async (path, content) => {
const file = parseFile(path, content);
return file ? await typeScriptPrinter(loadFile(file)) : undefined;
});
if (output) {
await (0, promises_1.mkdir)((0, path_1.dirname)(output.path), { recursive: true });
await (0, promises_1.writeFile)(output.path, output.content, 'utf-8');
const elapsed = (0, potygen_1.toMilliseconds)(process.hrtime(start));
ctx.logger.info(`[${output.isCached ? 'Cached' : 'Generated'}]: ${relPath} (${elapsed}ms)`);
}
}
else {
ctx.logger.info(`[Not modified]: ${relPath}`);
}
return { path };
}
catch (error) {
const elapsed = (0, potygen_1.toMilliseconds)(process.hrtime(start));
ctx.logger.error(`[Error]: ${relPath} (${elapsed})ms`);
throw error;
}
};
};
exports.toEmitter = toEmitter;
//# sourceMappingURL=emitter.js.map
{"version":3,"file":"emitter.js","sourceRoot":"","sources":["../src/emitter.ts"],"names":[],"mappings":";;;AAAA,2BAAgC;AAChC,2CAYoB;AACpB,+BAAmD;AACnD,8CAe0B;AAC1B,6DAA2D;AAC3D,0CAA+D;AAC/D,mCAAoC;AAEpC;;GAEG;AACH,MAAa,UAAU;IAIrB;IACE;;OAEG;IACI,QAAgB;IACvB;;OAEG;IACI,UAAmB,KAAK;IAC/B;;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,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;oBACtD,MAAM,OAAO,GAAG,IAAA,wBAAc,EAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;oBACtD,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,WAAW,MAAM,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC;iBAC7F;aACF;iBAAM;gBACL,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,mBAAmB,OAAO,EAAE,CAAC,CAAC;aAC/C;YACD,OAAO,EAAE,IAAI,EAAE,CAAC;SACjB;QAAC,OAAO,KAAK,EAAE;YACd,MAAM,OAAO,GAAG,IAAA,wBAAc,EAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;YACtD,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,YAAY,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC;YACvD,MAAM,KAAK,CAAC;SACb;IACH,CAAC,CAAC;AACJ,CAAC,CAAC;AAnCW,QAAA,SAAS,aAmCpB"}
import { SourceFile } from 'typescript';
import { LoadedFile, Type } from '@potygen/potygen';
export declare const compactTypes: (types: Type[]) => Type[];
/**
* Convert a potygen {@link LoadedFile} into a typescript {@link SourceFile}.
*
* @param file
* @param typePrefix prefix all class names with this string
* @returns
*/
export declare const toTypeSource: (file: LoadedFile, typePrefix?: string) => SourceFile;
export declare const toTypeScriptPrinter: (root: string, template: string, typePrefix?: string) => (file: LoadedFile) => Promise<{
path: string;
content: string;
}>;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toTypeScriptPrinter = exports.toTypeSource = exports.compactTypes = void 0;
const path_1 = require("path");
const typescript_1 = require("typescript");
const potygen_1 = require("@potygen/potygen");
const isIdentifierRegExp = /^[$A-Z_][0-9A-Z_$]*$/i;
const parseTemplate = (root, template, path) => Object.entries({ ...(0, path_1.parse)((0, path_1.relative)(root, path)), root }).reduce((acc, [name, value]) => acc.replace(`{{${name}}}`, value), template);
const jsDoc = (doc) => `*\n${doc
.split('\n')
.map((line) => ` * ${line}`)
.join('\n')}\n `;
const withJSDoc = (doc, node) => doc === undefined ? node : (0, typescript_1.addSyntheticLeadingComment)(node, typescript_1.SyntaxKind.MultiLineCommentTrivia, jsDoc(doc), true);
const compactTypes = (types) => types
.map((type) => ((0, potygen_1.isTypeOptional)(type) ? { ...type.value, nullable: type.nullable } : type))
.filter((item, index, all) => (0, potygen_1.isTypeLiteral)(item) && item.literal !== undefined
? !all.some((other, otherIndex) => index !== otherIndex && other.type === item.type && other.literal === undefined)
: true)
.filter((0, potygen_1.isUniqueBy)(potygen_1.isTypeEqual));
exports.compactTypes = compactTypes;
const toPropertyType = (context) => (type) => {
if ((0, potygen_1.isTypeComposite)(type)) {
return { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.StringKeyword) };
}
else if ((0, potygen_1.isTypeObjectLiteral)(type)) {
return type.items.reduce((acc, item) => {
const itemType = toPropertyType({ ...acc, name: context.name + toClassCase(item.name) })(item.type);
const memeber = typescript_1.factory.createPropertySignature(undefined, item.name.includes(' ')
? typescript_1.factory.createComputedPropertyName(typescript_1.factory.createStringLiteral(item.name))
: item.name, 'nullable' in item.type && item.type.nullable ? typescript_1.factory.createToken(typescript_1.SyntaxKind.QuestionToken) : undefined, itemType.type);
return { ...itemType, type: typescript_1.factory.createTypeLiteralNode(acc.type.members.concat(memeber)) };
}, { ...context, type: typescript_1.factory.createTypeLiteralNode([]) });
}
else if ((0, potygen_1.isTypeArray)(type)) {
const itemsType = toPropertyType(context)(type.items);
return { ...itemsType, type: typescript_1.factory.createArrayTypeNode(itemsType.type) };
}
else if ((0, potygen_1.isTypeUnion)(type)) {
const unionTypes = (0, exports.compactTypes)(type.items);
return (0, potygen_1.isEmpty)(unionTypes)
? { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword) }
: unionTypes.reduce((acc, item, index) => {
const itemType = toPropertyType({ ...acc, name: context.name + index })(item);
return { ...itemType, type: typescript_1.factory.createUnionTypeNode(acc.type.types.concat(itemType.type)) };
}, { ...context, type: typescript_1.factory.createUnionTypeNode([]) });
}
else if ((0, potygen_1.isTypeOptional)(type)) {
return type.value
? toPropertyType(context)(type.value)
: { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword) };
}
else {
switch (type.type) {
case 6 /* TypeName.Date */:
return { ...context, type: typescript_1.factory.createTypeReferenceNode('Date') };
case 0 /* TypeName.Buffer */:
return { ...context, type: typescript_1.factory.createTypeReferenceNode('Buffer') };
case 5 /* TypeName.Boolean */:
return {
...context,
type: type.literal !== undefined
? typescript_1.factory.createLiteralTypeNode(type.literal ? typescript_1.factory.createTrue() : typescript_1.factory.createFalse())
: typescript_1.factory.createToken(typescript_1.SyntaxKind.BooleanKeyword),
};
case 8 /* TypeName.Json */:
return {
...context,
refs: context.refs.concat(context.name),
type: context.toJson
? typescript_1.factory.createTypeReferenceNode('Json', [typescript_1.factory.createTypeReferenceNode(context.name)])
: typescript_1.factory.createTypeReferenceNode(context.name),
};
case 7 /* TypeName.Null */:
return { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.UndefinedKeyword) };
case 3 /* TypeName.Number */:
case 4 /* TypeName.BigInt */:
return {
...context,
type: type.literal !== undefined
? typescript_1.factory.createLiteralTypeNode(typescript_1.factory.createStringLiteral(String(type.literal)))
: typescript_1.factory.createToken(typescript_1.SyntaxKind.NumberKeyword),
};
case 2 /* TypeName.String */:
return {
...context,
type: type.literal !== undefined
? typescript_1.factory.createLiteralTypeNode(typescript_1.factory.createStringLiteral(type.literal))
: typescript_1.factory.createToken(typescript_1.SyntaxKind.StringKeyword),
};
case 9 /* TypeName.Unknown */:
return { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword) };
case 1 /* TypeName.Any */:
return { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.AnyKeyword) };
}
}
};
const toClassCase = (identifier) => identifier[0].toUpperCase() + identifier.slice(1);
const toAstImports = (names) => typescript_1.factory.createImportDeclaration(undefined, typescript_1.factory.createImportClause(false, undefined, typescript_1.factory.createNamedImports(names.map((name) => typescript_1.factory.createImportSpecifier(false, undefined, typescript_1.factory.createIdentifier(name))))), typescript_1.factory.createStringLiteral('@potygen/potygen'));
const toLoadedQueryTypeNodes = (refs, name, loadedQuery) => {
const params = loadedQuery.params.reduce((acc, item) => {
const itemType = toPropertyType({ toJson: false, name: 'TParam' + toClassCase(item.name), refs: acc.refs })(item.type);
const prop = typescript_1.factory.createPropertySignature(undefined, item.name, 'nullable' in item.type && item.type.nullable ? typescript_1.factory.createToken(typescript_1.SyntaxKind.QuestionToken) : undefined, itemType.type);
return { ...itemType, props: acc.props.concat(prop) };
}, { refs, props: [] });
const results = loadedQuery.results.reduce((acc, item) => {
const itemType = toPropertyType({ toJson: true, name: 'T' + toClassCase(item.name), refs: acc.refs })(item.type);
const prop = withJSDoc(item.type.comment ?? undefined, typescript_1.factory.createPropertySignature(undefined, isIdentifierRegExp.test(item.name) ? item.name : typescript_1.factory.createStringLiteral(item.name), 'nullable' in item.type && item.type.nullable ? typescript_1.factory.createToken(typescript_1.SyntaxKind.QuestionToken) : undefined, itemType.type));
return { ...itemType, props: acc.props.concat(prop) };
}, { refs: [], props: [] });
return {
resultRefs: results.refs,
statements: [
typescript_1.factory.createInterfaceDeclaration([typescript_1.factory.createModifier(typescript_1.SyntaxKind.ExportKeyword)], `${name}Params`, params.refs.map((ref) => typescript_1.factory.createTypeParameterDeclaration([], ref, undefined, typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword))), undefined, params.props),
typescript_1.factory.createInterfaceDeclaration([typescript_1.factory.createModifier(typescript_1.SyntaxKind.ExportKeyword)], `${name}Result`, results.refs.map((ref) => typescript_1.factory.createTypeParameterDeclaration([], ref, undefined, typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword))), undefined, results.props),
typescript_1.factory.createInterfaceDeclaration([typescript_1.factory.createModifier(typescript_1.SyntaxKind.ExportKeyword)], `${name}Query`, [...params.refs, ...results.refs].map((ref) => typescript_1.factory.createTypeParameterDeclaration([], ref, undefined, typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword))), undefined, [
typescript_1.factory.createPropertySignature(undefined, 'params', undefined, typescript_1.factory.createTypeReferenceNode(`${name}Params`, params.refs.map((ref) => typescript_1.factory.createTypeReferenceNode(ref)))),
typescript_1.factory.createPropertySignature(undefined, 'result', undefined, typescript_1.factory.createArrayTypeNode(typescript_1.factory.createTypeReferenceNode(`${name}Result`, results.refs.map((ref) => typescript_1.factory.createTypeReferenceNode(ref))))),
]),
],
};
};
/**
* Convert a potygen {@link LoadedFile} into a typescript {@link SourceFile}.
*
* @param file
* @param typePrefix prefix all class names with this string
* @returns
*/
const toTypeSource = (file, typePrefix = '') => {
const content = file.type === 'ts'
? file.queries.reduce((acc, query) => {
const { statements, resultRefs } = toLoadedQueryTypeNodes(acc.resultRefs, typePrefix + toClassCase(query.name), query.loadedQuery);
return { resultRefs, statements: acc.statements.concat(statements) };
}, { resultRefs: [], statements: [] })
: toLoadedQueryTypeNodes([], typePrefix, file.loadedQuery);
return typescript_1.factory.updateSourceFile((0, typescript_1.createSourceFile)(file.path, '', typescript_1.ScriptTarget.ES2021, true), content.resultRefs.length > 0 ? [toAstImports(['Json']), ...content.statements] : content.statements);
};
exports.toTypeSource = toTypeSource;
const toTypeScriptPrinter = (root, template, typePrefix) => {
const printer = (0, typescript_1.createPrinter)({ newLine: typescript_1.NewLineKind.LineFeed });
return async (file) => {
const path = parseTemplate(root, template, file.path);
return { path, content: printer.printFile((0, exports.toTypeSource)(file, typePrefix)) };
};
};
exports.toTypeScriptPrinter = toTypeScriptPrinter;
//# sourceMappingURL=typescript-printer.js.map
{"version":3,"file":"typescript-printer.js","sourceRoot":"","sources":["../src/typescript-printer.ts"],"names":[],"mappings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UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CACrG,CAAC;AACJ,CAAC,CAAC;AApBW,QAAA,YAAY,gBAoBvB;AAEK,MAAM,mBAAmB,GAAG,CAAC,IAAY,EAAE,QAAgB,EAAE,UAAmB,EAAE,EAAE;IACzF,MAAM,OAAO,GAAG,IAAA,0BAAa,EAAC,EAAE,OAAO,EAAE,wBAAW,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjE,OAAO,KAAK,EAAE,IAAgB,EAA8C,EAAE;QAC5E,MAAM,IAAI,GAAG,aAAa,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QACtD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,CAAC,SAAS,CAAC,IAAA,oBAAY,EAAC,IAAI,EAAE,UAAU,CAAC,CAAC,EAAE,CAAC;IAC9E,CAAC,CAAC;AACJ,CAAC,CAAC;AANW,QAAA,mBAAmB,uBAM9B"}
+0
-1

@@ -11,3 +11,2 @@ import { Record, Optional, Static, String, Boolean } from 'runtypes';

typePrefix: Optional<String>;
preload: Optional<Boolean>;
cache: Optional<Boolean>;

@@ -14,0 +13,0 @@ cacheFile: Optional<String>;

@@ -14,3 +14,2 @@ "use strict";

typePrefix: (0, runtypes_1.Optional)(runtypes_1.String),
preload: (0, runtypes_1.Optional)(runtypes_1.Boolean),
cache: (0, runtypes_1.Optional)(runtypes_1.Boolean),

@@ -24,3 +23,2 @@ cacheFile: (0, runtypes_1.Optional)(runtypes_1.String),

root: process.cwd(),
preload: false,
template: '{{dir}}/{{name}}.queries.ts',

@@ -27,0 +25,0 @@ connection: 'postgres://localhost:5432/db',

@@ -1,1 +0,1 @@

{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mapp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"mappings":";;;AAAA,uCAAqE;AAExD,QAAA,MAAM,GAAG,IAAA,iBAAM,EAAC;IAC3B,KAAK,EAAE,IAAA,mBAAQ,EAAC,iBAAM,CAAC;IACvB,KAAK,EAAE,IAAA,mBAAQ,EAAC,kBAAO,CAAC;IACxB,IAAI,EAAE,IAAA,mBAAQ,EAAC,iBAAM,CAAC;IACtB,UAAU,EAAE,IAAA,mBAAQ,EAAC,iBAAM,CAAC;IAC5B,QAAQ,EAAE,IAAA,mBAAQ,EAAC,iBAAM,CAAC;IAC1B,OAAO,EAAE,IAAA,mBAAQ,EAAC,kBAAO,CAAC;IAC1B,MAAM,EAAE,IAAA,mBAAQ,EAAC,kBAAO,CAAC;IACzB,UAAU,EAAE,IAAA,mBAAQ,EAAC,iBAAM,CAAC;IAC5B,KAAK,EAAE,IAAA,mBAAQ,EAAC,kBAAO,CAAC;IACxB,SAAS,EAAE,IAAA,mBAAQ,EAAC,iBAAM,CAAC;IAC3B,UAAU,EAAE,IAAA,mBAAQ,EAAC,kBAAO,CAAC;CAC9B,CAAC,CAAC;AAKI,MAAM,QAAQ,GAAG,CAAC,MAAe,EAAkB,EAAE,CAAC,CAAC;IAC5D,KAAK,EAAE,UAAU;IACjB,SAAS,EAAE,sBAAsB;IACjC,IAAI,EAAE,OAAO,CAAC,GAAG,EAAE;IACnB,QAAQ,EAAE,6BAA6B;IACvC,UAAU,EAAE,8BAA8B;IAC1C,KAAK,EAAE,KAAK;IACZ,OAAO,EAAE,KAAK;IACd,MAAM,EAAE,KAAK;IACb,KAAK,EAAE,KAAK;IACZ,UAAU,EAAE,KAAK;IACjB,UAAU,EAAE,EAAE;IACd,GAAG,cAAM,CAAC,KAAK,CAAC,MAAM,CAAC;CACxB,CAAC,CAAC;AAbU,QAAA,QAAQ,YAalB"}

@@ -1,4 +0,3 @@

export { SqlRead, QueryLoader } from './traverse';
export { Config, ConfigType, FullConfigType, toConfig } from './config';
export { emitLoadedFile, toTypeSource, compactTypes } from './emit';
export { toTypeScriptPrinter, toTypeSource, compactTypes } from './typescript-printer';
export { glob } from './glob';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.glob = exports.compactTypes = exports.toTypeSource = exports.emitLoadedFile = exports.toConfig = exports.Config = exports.QueryLoader = exports.SqlRead = void 0;
var traverse_1 = require("./traverse");
Object.defineProperty(exports, "SqlRead", { enumerable: true, get: function () { return traverse_1.SqlRead; } });
Object.defineProperty(exports, "QueryLoader", { enumerable: true, get: function () { return traverse_1.QueryLoader; } });
exports.glob = exports.compactTypes = exports.toTypeSource = exports.toTypeScriptPrinter = exports.toConfig = exports.Config = void 0;
var config_1 = require("./config");
Object.defineProperty(exports, "Config", { enumerable: true, get: function () { return config_1.Config; } });
Object.defineProperty(exports, "toConfig", { enumerable: true, get: function () { return config_1.toConfig; } });
var emit_1 = require("./emit");
Object.defineProperty(exports, "emitLoadedFile", { enumerable: true, get: function () { return emit_1.emitLoadedFile; } });
Object.defineProperty(exports, "toTypeSource", { enumerable: true, get: function () { return emit_1.toTypeSource; } });
Object.defineProperty(exports, "compactTypes", { enumerable: true, get: function () { return emit_1.compactTypes; } });
var typescript_printer_1 = require("./typescript-printer");
Object.defineProperty(exports, "toTypeScriptPrinter", { enumerable: true, get: function () { return typescript_printer_1.toTypeScriptPrinter; } });
Object.defineProperty(exports, "toTypeSource", { enumerable: true, get: function () { return typescript_printer_1.toTypeSource; } });
Object.defineProperty(exports, "compactTypes", { enumerable: true, get: function () { return typescript_printer_1.compactTypes; } });
var glob_1 = require("./glob");
Object.defineProperty(exports, "glob", { enumerable: true, get: function () { return glob_1.glob; } });
//# sourceMappingURL=index.js.map

@@ -1,1 +0,1 @@

{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uCAAkD;AAAzC,mGAAA,OAAO,OAAA;AAAE,uGAAA,WAAW,OAAA;AAC7B,mCAAwE;AAA/D,gGAAA,MAAM,OAAA;AAA8B,kGAAA,QAAQ,OAAA;AACrD,+BAAoE;AAA3D,sGAAA,cAAc,OAAA;AAAE,oGAAA,YAAY,OAAA;AAAE,oGAAA,YAAY,OAAA;AACnD,+BAA8B;AAArB,4FAAA,IAAI,OAAA"}
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,mCAAwE;AAA/D,gGAAA,MAAM,OAAA;AAA8B,kGAAA,QAAQ,OAAA;AACrD,2DAAuF;AAA9E,yHAAA,mBAAmB,OAAA;AAAE,kHAAA,YAAY,OAAA;AAAE,kHAAA,YAAY,OAAA;AACxD,+BAA8B;AAArB,4FAAA,IAAI,OAAA"}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.potygen = void 0;
const potygen_1 = require("@potygen/potygen");
const promise_pool_1 = require("@supercharge/promise-pool");
const fs_1 = require("fs");
const util_1 = require("util");
const pg_1 = require("pg");
const stream_1 = require("stream");
const commander_1 = require("commander");
const traverse_1 = require("./traverse");
const emitter_1 = require("./emitter");
const config_1 = require("./config");
const cache_1 = require("./cache");
const asyncPipeline = (0, util_1.promisify)(stream_1.pipeline);
const glob_1 = require("./glob");
var LogLevel;

@@ -25,3 +25,3 @@ (function (LogLevel) {

if (this.level >= LogLevel.error) {
console.info(...args);
console.error(...args);
}

@@ -42,3 +42,3 @@ }

.description('Convert postgres query files into typescript types')
.version('0.8.2')
.version('0.9.0')
.option('-c, --config <config>', 'A configuration file to load', 'potygen.config.json')

@@ -52,4 +52,3 @@ .option('-f, --files <files>', 'A glob pattern to search files by (default: "**/*.sql")')

.option('-s, --silent', 'Only show error logs')
.option('-p, --typePrefix <typePrefix>', 'Prefix generated types')
.option('-l, --preload', 'Load all data at once. Slower start but faster for a lot of files')
.option('-p, --type-prefix <typePrefix>', 'Prefix generated types')
.option('-r, --root <root>', `Set the root directory (default: ${process.cwd()})`)

@@ -60,7 +59,6 @@ .option('-n, --connection <connection>', 'Connection to the postgres database. URI (default: "postgres://localhost:5432/db")')

const { config, ...rest } = options;
const { root, connection, watch, files, template, verbose, silent, typePrefix, preload, cache, cacheFile, cacheClear, } = (0, config_1.toConfig)({
const { root, connection, watch, files, template, verbose, silent, typePrefix, cache, cacheFile, cacheClear } = (0, config_1.toConfig)({
...((0, fs_1.existsSync)(config) ? JSON.parse((0, fs_1.readFileSync)(config, 'utf-8')) : {}),
...rest,
});
const cacheStore = new cache_1.CacheStore(cacheFile, cache, cacheClear);
const logger = overwriteLogger ?? new LogLevelConsole(verbose ? LogLevel.debug : silent ? LogLevel.error : LogLevel.info);

@@ -71,18 +69,28 @@ logger.debug(`Potygen Config: ${(0, util_1.inspect)({ root, connection, watch, files, template })}`);

try {
const sqls = new traverse_1.SqlRead({ path: files, root, watch, logger, cacheStore });
const sink = new traverse_1.QueryLoader({ db, root, template, logger, typePrefix, preload, cacheStore });
logger.info(`Potygen started processing ("${files}", watch: ${watch})`);
await asyncPipeline(sqls, sink);
cacheStore.save();
}
catch (error) {
if (process.env.POTYGEN_DEBUG && error instanceof Error) {
logger.error(error.stack);
const cacheStore = new emitter_1.CacheStore(cacheFile, cache, cacheClear);
await cacheStore.load();
const emit = await (0, emitter_1.toEmitter)({ db, logger }, cacheStore, { root, template, typePrefix });
const { results, errors } = await promise_pool_1.PromisePool.withConcurrency(20)
.for(Array.from((0, glob_1.glob)(files, root)))
.process(emit);
if (errors.length) {
logger.error('Errors:');
logger.error('------------------------------');
for (const error of errors) {
logger.error(`[${error.item}]`);
logger.error(process.env.POTYGEN_DEBUG ? error.stack : String(error.raw));
logger.error('\n');
}
}
else {
logger.error(String(error));
if (watch) {
for (const { path } of results.filter(potygen_1.isNil)) {
(0, fs_1.watchFile)(path, () => emit(path));
}
}
await cacheStore.save();
}
finally {
await db.end();
if (!watch) {
await db.end();
}
}

@@ -89,0 +97,0 @@ });

@@ -1,1 +0,1 @@

{"version":3,"file":"potygen.js","sourceRoot":"","sources":["../src/potygen.ts"],"names":[],"mappings":";;;AACA,2BAA8C;AAC9C,+BAA0C;AAC1C,2BAA4B;AAC5B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AS;QACR,IAAI,CAAC,KAAK,EAAE;YACV,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC;SAChB;KACF;AACH,CAAC,CAAC,CAAC;AAjEM,QAAA,OAAO,WAiEb"}
{
"name": "@potygen/cli",
"version": "0.8.2",
"version": "0.9.0",
"homepage": "https://github.com/ivank/potygen/tree/main/packages/cli",

@@ -23,2 +23,3 @@ "description": "Command line interface for potygen (Postgres Typescript Generator)",

"@potygen/potygen": "0.7.1",
"@supercharge/promise-pool": "^2.3.2",
"@types/pg": "^8.6.0",

@@ -25,0 +26,0 @@ "commander": "^8.3.0",

export declare class CacheStore {
fileName: string;
enabled: boolean;
cacheClear: boolean;
store: Map<string, number>;
constructor(fileName: string, enabled?: boolean, cacheClear?: boolean);
shouldParseFile(path: string): boolean;
cacheFile(path: string): void;
save(): void;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheStore = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
class CacheStore {
constructor(fileName, enabled = false, cacheClear = false) {
this.fileName = fileName;
this.enabled = enabled;
this.cacheClear = cacheClear;
this.store = new Map();
if (this.enabled && !this.cacheClear) {
if ((0, fs_1.existsSync)(fileName)) {
this.store = new Map(Object.entries(JSON.parse((0, fs_1.readFileSync)(fileName, 'utf-8'))));
}
}
}
shouldParseFile(path) {
if (!this.enabled) {
return true;
}
else {
const mtime = (0, fs_1.statSync)(path).mtime.getTime();
const currentMtime = this.store.get(path);
if (currentMtime && mtime === currentMtime) {
return false;
}
}
return true;
}
cacheFile(path) {
const mtime = (0, fs_1.statSync)(path).mtime.getTime();
this.store.set(path, mtime);
}
save() {
if (this.enabled) {
(0, fs_1.mkdirSync)((0, path_1.dirname)(this.fileName), { recursive: true });
(0, fs_1.writeFileSync)(this.fileName, JSON.stringify(Object.fromEntries(this.store)), 'utf-8');
}
}
}
exports.CacheStore = CacheStore;
//# sourceMappingURL=cache.js.map
{"version":3,"file":"cache.js","sourceRoot":"","sources":["../src/cache.ts"],"names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AAA,cAAO,EAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YACvD,IAAA,kBAAa,EAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;SACvF;IACH,CAAC;CACF;AAnCD,gCAmCC"}
import { SourceFile } from 'typescript';
import { LoadedFile, Type } from '@potygen/potygen';
import { CacheStore } from './cache';
export declare const compactTypes: (types: Type[]) => Type[];
export declare const toTypeSource: (file: LoadedFile, typePrefix?: string) => SourceFile;
export declare const emitLoadedFile: (root: string, template: string, cacheStore: CacheStore, typePrefix?: string) => (file: LoadedFile) => Promise<void>;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.emitLoadedFile = exports.toTypeSource = exports.compactTypes = void 0;
const fs_1 = require("fs");
const util_1 = require("util");
const path_1 = require("path");
const typescript_1 = require("typescript");
const potygen_1 = require("@potygen/potygen");
const mkdirAsync = (0, util_1.promisify)(fs_1.mkdir);
const writeFileAsync = (0, util_1.promisify)(fs_1.writeFile);
const isIdentifierRegExp = /^[$A-Z_][0-9A-Z_$]*$/i;
const parseTemplate = (root, template, path) => Object.entries({ ...(0, path_1.parse)((0, path_1.relative)(root, path)), root }).reduce((acc, [name, value]) => acc.replace(`{{${name}}}`, value), template);
const jsDoc = (doc) => `*\n${doc
.split('\n')
.map((line) => ` * ${line}`)
.join('\n')}\n `;
const withJSDoc = (doc, node) => doc === undefined ? node : (0, typescript_1.addSyntheticLeadingComment)(node, typescript_1.SyntaxKind.MultiLineCommentTrivia, jsDoc(doc), true);
const compactTypes = (types) => types
.map((type) => ((0, potygen_1.isTypeOptional)(type) ? { ...type.value, nullable: type.nullable } : type))
.filter((item, index, all) => (0, potygen_1.isTypeLiteral)(item) && item.literal !== undefined
? !all.some((other, otherIndex) => index !== otherIndex && other.type === item.type && other.literal === undefined)
: true)
.filter((0, potygen_1.isUniqueBy)(potygen_1.isTypeEqual));
exports.compactTypes = compactTypes;
const toPropertyType = (context) => (type) => {
if ((0, potygen_1.isTypeComposite)(type)) {
return { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.StringKeyword) };
}
else if ((0, potygen_1.isTypeObjectLiteral)(type)) {
return type.items.reduce((acc, item) => {
const itemType = toPropertyType({ ...acc, name: context.name + toClassCase(item.name) })(item.type);
const memeber = typescript_1.factory.createPropertySignature(undefined, item.name.includes(' ')
? typescript_1.factory.createComputedPropertyName(typescript_1.factory.createStringLiteral(item.name))
: item.name, 'nullable' in item.type && item.type.nullable ? typescript_1.factory.createToken(typescript_1.SyntaxKind.QuestionToken) : undefined, itemType.type);
return { ...itemType, type: typescript_1.factory.createTypeLiteralNode(acc.type.members.concat(memeber)) };
}, { ...context, type: typescript_1.factory.createTypeLiteralNode([]) });
}
else if ((0, potygen_1.isTypeArray)(type)) {
const itemsType = toPropertyType(context)(type.items);
return { ...itemsType, type: typescript_1.factory.createArrayTypeNode(itemsType.type) };
}
else if ((0, potygen_1.isTypeUnion)(type)) {
const unionTypes = (0, exports.compactTypes)(type.items);
return (0, potygen_1.isEmpty)(unionTypes)
? { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword) }
: unionTypes.reduce((acc, item, index) => {
const itemType = toPropertyType({ ...acc, name: context.name + index })(item);
return { ...itemType, type: typescript_1.factory.createUnionTypeNode(acc.type.types.concat(itemType.type)) };
}, { ...context, type: typescript_1.factory.createUnionTypeNode([]) });
}
else if ((0, potygen_1.isTypeOptional)(type)) {
return type.value
? toPropertyType(context)(type.value)
: { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword) };
}
else {
switch (type.type) {
case 6 /* TypeName.Date */:
return { ...context, type: typescript_1.factory.createTypeReferenceNode('Date') };
case 0 /* TypeName.Buffer */:
return { ...context, type: typescript_1.factory.createTypeReferenceNode('Buffer') };
case 5 /* TypeName.Boolean */:
return {
...context,
type: type.literal !== undefined
? typescript_1.factory.createLiteralTypeNode(type.literal ? typescript_1.factory.createTrue() : typescript_1.factory.createFalse())
: typescript_1.factory.createToken(typescript_1.SyntaxKind.BooleanKeyword),
};
case 8 /* TypeName.Json */:
return {
...context,
refs: context.refs.concat(context.name),
type: context.toJson
? typescript_1.factory.createTypeReferenceNode('Json', [typescript_1.factory.createTypeReferenceNode(context.name)])
: typescript_1.factory.createTypeReferenceNode(context.name),
};
case 7 /* TypeName.Null */:
return { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.UndefinedKeyword) };
case 3 /* TypeName.Number */:
case 4 /* TypeName.BigInt */:
return {
...context,
type: type.literal !== undefined
? typescript_1.factory.createLiteralTypeNode(typescript_1.factory.createStringLiteral(String(type.literal)))
: typescript_1.factory.createToken(typescript_1.SyntaxKind.NumberKeyword),
};
case 2 /* TypeName.String */:
return {
...context,
type: type.literal !== undefined
? typescript_1.factory.createLiteralTypeNode(typescript_1.factory.createStringLiteral(type.literal))
: typescript_1.factory.createToken(typescript_1.SyntaxKind.StringKeyword),
};
case 9 /* TypeName.Unknown */:
return { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword) };
case 1 /* TypeName.Any */:
return { ...context, type: typescript_1.factory.createToken(typescript_1.SyntaxKind.AnyKeyword) };
}
}
};
const toClassCase = (identifier) => identifier[0].toUpperCase() + identifier.slice(1);
const toAstImports = (names) => typescript_1.factory.createImportDeclaration(undefined, undefined, typescript_1.factory.createImportClause(false, undefined, typescript_1.factory.createNamedImports(names.map((name) => typescript_1.factory.createImportSpecifier(false, undefined, typescript_1.factory.createIdentifier(name))))), typescript_1.factory.createStringLiteral('@potygen/potygen'));
const toLoadedQueryTypeNodes = (refs, name, loadedQuery) => {
const params = loadedQuery.params.reduce((acc, item) => {
const itemType = toPropertyType({ toJson: false, name: 'TParam' + toClassCase(item.name), refs: acc.refs })(item.type);
const prop = typescript_1.factory.createPropertySignature(undefined, item.name, 'nullable' in item.type && item.type.nullable ? typescript_1.factory.createToken(typescript_1.SyntaxKind.QuestionToken) : undefined, itemType.type);
return { ...itemType, props: acc.props.concat(prop) };
}, { refs, props: [] });
const results = loadedQuery.results.reduce((acc, item) => {
const itemType = toPropertyType({ toJson: true, name: 'T' + toClassCase(item.name), refs: acc.refs })(item.type);
const prop = withJSDoc(item.type.comment ?? undefined, typescript_1.factory.createPropertySignature(undefined, isIdentifierRegExp.test(item.name) ? item.name : typescript_1.factory.createStringLiteral(item.name), 'nullable' in item.type && item.type.nullable ? typescript_1.factory.createToken(typescript_1.SyntaxKind.QuestionToken) : undefined, itemType.type));
return { ...itemType, props: acc.props.concat(prop) };
}, { refs: [], props: [] });
return {
resultRefs: results.refs,
statements: [
typescript_1.factory.createInterfaceDeclaration([typescript_1.factory.createModifier(typescript_1.SyntaxKind.ExportKeyword)], `${name}Params`, params.refs.map((ref) => typescript_1.factory.createTypeParameterDeclaration([], ref, undefined, typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword))), undefined, params.props),
typescript_1.factory.createInterfaceDeclaration([typescript_1.factory.createModifier(typescript_1.SyntaxKind.ExportKeyword)], `${name}Result`, results.refs.map((ref) => typescript_1.factory.createTypeParameterDeclaration([], ref, undefined, typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword))), undefined, results.props),
typescript_1.factory.createInterfaceDeclaration([typescript_1.factory.createModifier(typescript_1.SyntaxKind.ExportKeyword)], `${name}Query`, [...params.refs, ...results.refs].map((ref) => typescript_1.factory.createTypeParameterDeclaration([], ref, undefined, typescript_1.factory.createToken(typescript_1.SyntaxKind.UnknownKeyword))), undefined, [
typescript_1.factory.createPropertySignature(undefined, 'params', undefined, typescript_1.factory.createTypeReferenceNode(`${name}Params`, params.refs.map((ref) => typescript_1.factory.createTypeReferenceNode(ref)))),
typescript_1.factory.createPropertySignature(undefined, 'result', undefined, typescript_1.factory.createArrayTypeNode(typescript_1.factory.createTypeReferenceNode(`${name}Result`, results.refs.map((ref) => typescript_1.factory.createTypeReferenceNode(ref))))),
]),
],
};
};
const toTypeSource = (file, typePrefix = '') => {
const content = file.type === 'ts'
? file.queries.reduce((acc, query) => {
const { statements, resultRefs } = toLoadedQueryTypeNodes(acc.resultRefs, typePrefix + toClassCase(query.name), query.loadedQuery);
return { resultRefs, statements: acc.statements.concat(statements) };
}, { resultRefs: [], statements: [] })
: toLoadedQueryTypeNodes([], typePrefix, file.loadedQuery);
return typescript_1.factory.updateSourceFile((0, typescript_1.createSourceFile)(file.path, '', typescript_1.ScriptTarget.ES2021, true), content.resultRefs.length > 0 ? [toAstImports(['Json']), ...content.statements] : content.statements);
};
exports.toTypeSource = toTypeSource;
const emitLoadedFile = (root, template, cacheStore, typePrefix) => {
const printer = (0, typescript_1.createPrinter)({ newLine: typescript_1.NewLineKind.LineFeed });
return async (file) => {
const outputFile = parseTemplate(root, template, file.path);
const directory = (0, path_1.dirname)(outputFile);
await mkdirAsync(directory, { recursive: true });
await writeFileAsync(outputFile, printer.printFile((0, exports.toTypeSource)(file, typePrefix)));
cacheStore.cacheFile(file.path);
};
};
exports.emitLoadedFile = emitLoadedFile;
//# sourceMappingURL=emit.js.map
{"version":3,"file":"emit.js","sourceRoot":"","sources":["../src/emit.ts"],"names":[],"mappings":";;;AAAA,2BAAsC;AACtC,+BAAiC;AACjC,+BAAgD;AAChD,2CAeoB;AACpB,8CAc0B;AAG1B,MAAM,UAAU,GAAG,IAAA,gBAAS,EAAC,UAAK,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,IAAA,gBAAS,EAAC,cAAS,CAAC,CAAC;AAE5C,MAAM,kBAAkB,GAAG,uBAAuB,CAAC;AAEnD,MAAM,aAAa,GAAG,CAAC,IAAY,EAAE,QAAgB,EAAE,IAAY,EAAU,EAAE,CAC7E,MAAM,CAAC,OAAO,CAAC,EAAE,GAAG,IAAA,YAAK,EAAC,IAAA,eAAQ,EAAC,IAAI,EAAE,IAAI,CAAC,CAA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sB,EAAE,UAAmB,EAAE,EAAE;IAC5G,MAAM,OAAO,GAAG,IAAA,0BAAa,EAAC,EAAE,OAAO,EAAE,wBAAW,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjE,OAAO,KAAK,EAAE,IAAgB,EAAiB,EAAE;QAC/C,MAAM,UAAU,GAAG,aAAa,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5D,MAAM,SAAS,GAAG,IAAA,cAAO,EAAC,UAAU,CAAC,CAAC;QAEtC,MAAM,UAAU,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACjD,MAAM,cAAc,CAAC,UAAU,EAAE,OAAO,CAAC,SAAS,CAAC,IAAA,oBAAY,EAAC,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC;QACpF,UAAU,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAClC,CAAC,CAAC;AACJ,CAAC,CAAC;AAVW,QAAA,cAAc,kBAUzB"}
/// <reference types="node" />
/// <reference types="node" />
import { Readable, Writable } from 'stream';
import { LoadContext, LoadedData, Logger, ParsedFile, ParsedTypescriptFile } from '@potygen/potygen';
import { ClientBase } from 'pg';
import { CacheStore } from './cache';
export declare class SqlRead extends Readable {
options: {
path: string;
root: string;
watch: boolean;
logger: Logger;
cacheStore: CacheStore;
};
source: Generator<string, void, unknown>;
watchedFiles: Set<string>;
constructor(options: {
path: string;
root: string;
watch: boolean;
logger: Logger;
cacheStore: CacheStore;
});
next(): ParsedFile | undefined;
watchFile(path: string): () => void;
_read(): void;
}
export declare class QueryLoader extends Writable {
options: {
db: ClientBase;
root: string;
template: string;
logger: Logger;
typePrefix?: string;
preload?: boolean;
cacheStore: CacheStore;
};
ctx: LoadContext;
data: LoadedData[];
constructor(options: {
db: ClientBase;
root: string;
template: string;
logger: Logger;
typePrefix?: string;
preload?: boolean;
cacheStore: CacheStore;
});
_writev(chunks: Array<{
chunk: ParsedFile;
encoding: BufferEncoding;
}>, callback: (error?: Error | null) => void): Promise<void>;
_write(file: ParsedTypescriptFile, encoding: BufferEncoding, callback: (error?: Error | null) => void): Promise<void>;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QueryLoader = exports.SqlRead = void 0;
const fs_1 = require("fs");
const stream_1 = require("stream");
const glob_1 = require("./glob");
const typescript_1 = require("typescript");
const path_1 = require("path");
const potygen_1 = require("@potygen/potygen");
const emit_1 = require("./emit");
const util_1 = require("util");
const toTemplateParent = (node) => (0, typescript_1.isCallExpression)(node.parent) ? toTemplateParent(node.parent) : node.parent;
const getTemplateTagQueries = (ast) => {
const queries = [];
let tagPropertyName = 'sql';
const visitor = (node) => {
if ((0, typescript_1.isImportDeclaration)(node) &&
(0, typescript_1.isStringLiteral)(node.moduleSpecifier) &&
node.importClause?.namedBindings &&
(0, typescript_1.isNamedImports)(node.importClause.namedBindings) &&
node.moduleSpecifier.text === '@potygen/potygen') {
tagPropertyName =
node.importClause?.namedBindings.elements.find(({ propertyName, name }) => (propertyName ?? name).text === 'sql')?.name.text ?? tagPropertyName;
}
else if ((0, typescript_1.isTaggedTemplateExpression)(node) &&
(0, typescript_1.isNoSubstitutionTemplateLiteral)(node.template) &&
(0, typescript_1.isIdentifier)(node.tag) &&
node.tag.text === tagPropertyName) {
const tag = {
name: toTemplateParent(node).getChildAt(0).getText(),
pos: node.template.pos + 1,
template: node.template.text,
};
try {
queries.push({ ...tag, queryInterface: (0, potygen_1.toQueryInterface)((0, potygen_1.parser)(node.template.text).ast) });
}
catch (error) {
throw new potygen_1.ParseError(tag, `Error parsing sql: ${error instanceof Error ? error.message : String(error)}`);
}
}
else {
node.forEachChild(visitor);
}
};
visitor(ast);
return queries;
};
const toParsedTypescriptFile = (path) => {
const sourceText = (0, fs_1.readFileSync)(path, 'utf-8');
const source = (0, typescript_1.createSourceFile)((0, path_1.basename)(path), sourceText, typescript_1.ScriptTarget.ES2021, true);
return { type: 'ts', source, path, queries: getTemplateTagQueries(source) };
};
const toParsedSqlFile = (path) => {
const content = (0, fs_1.readFileSync)(path, 'utf-8');
return { type: 'sql', path, content, queryInterface: (0, potygen_1.toQueryInterface)((0, potygen_1.parser)(content).ast) };
};
const toQueryInterfaces = (files) => files.flatMap((file) => file.type === 'ts' ? file.queries.map((query) => query.queryInterface) : file.queryInterface);
const loadDataFromParsedFiles = async (ctx, data, files) => (0, potygen_1.loadQueryInterfacesData)(ctx, toQueryInterfaces(files), data);
const isError = (error) => error instanceof potygen_1.LoadError || error instanceof potygen_1.ParseError;
const loadFile = (data) => (file) => {
if (file.type === 'sql') {
try {
return { ...file, loadedQuery: (0, potygen_1.toLoadedQueryInterface)(data)(file.queryInterface) };
}
catch (error) {
throw isError(error) ? new potygen_1.ParsedSqlFileLoadError(file, error) : error;
}
}
else {
return {
...file,
queries: file.queries.map((template) => {
try {
return { ...template, loadedQuery: (0, potygen_1.toLoadedQueryInterface)(data)(template.queryInterface) };
}
catch (error) {
throw isError(error) ? new potygen_1.ParsedTypescriptFileLoadError(file, template, error) : error;
}
}),
};
}
};
const parseFile = (path) => {
if (path.endsWith('.ts')) {
const file = toParsedTypescriptFile(path);
return file.queries.length > 0 ? file : undefined;
}
else {
return toParsedSqlFile(path);
}
};
class SqlRead extends stream_1.Readable {
constructor(options) {
super({ objectMode: true });
this.options = options;
this.watchedFiles = new Set();
this.source = (0, glob_1.glob)(options.path, options.root);
}
next() {
let path;
while (!(path = this.source.next()).done) {
if (this.options.cacheStore.shouldParseFile(path.value)) {
const file = parseFile(path.value);
if (file) {
return file;
}
}
}
return undefined;
}
watchFile(path) {
return () => {
const file = parseFile(path);
if (file) {
this.options.logger.info(`Processing ${(0, path_1.relative)(this.options.root ?? '.', path)}`);
this.push(file);
}
};
}
_read() {
const next = this.next();
if (next) {
if (this.options.watch && !this.watchedFiles.has(next.path)) {
this.watchedFiles.add(next.path);
(0, fs_1.watchFile)(next.path, this.watchFile(next.path));
}
this.options.logger.info(`Processing ${(0, path_1.relative)(this.options.root ?? '.', next.path)}`);
this.push(next);
}
else if (!this.options.watch) {
this.options.logger.info(`Done`);
this.push(null);
}
}
}
exports.SqlRead = SqlRead;
class QueryLoader extends stream_1.Writable {
constructor(options) {
super({ objectMode: true });
this.options = options;
this.data = [];
this.ctx = { db: options.db, logger: options.logger ?? console };
}
async _writev(chunks, callback) {
try {
const parsedFiles = chunks.map((file) => file.chunk);
this.ctx.logger.debug(`Parse files: ${(0, util_1.inspect)(parsedFiles.map((file) => `${(0, path_1.relative)(this.options.root, file.path)} (${file.type})`))}`);
this.data = this.options.preload
? this.data.length === 0
? await (0, potygen_1.loadAllData)(this.ctx, this.data)
: this.data
: await loadDataFromParsedFiles(this.ctx, this.data, parsedFiles);
await Promise.all(parsedFiles
.map(loadFile(this.data))
.map((0, emit_1.emitLoadedFile)(this.options.root, this.options.template, this.options.cacheStore, this.options.typePrefix)));
}
catch (error) {
this.options.logger.error(error instanceof Error ? String(error) : new Error(String(error)));
}
callback();
}
async _write(file, encoding, callback) {
try {
this.ctx.logger.debug(`Parse file: ${(0, path_1.relative)(this.options.root, file.path)} (${file.type})`);
this.data = this.options.preload
? this.data.length === 0
? await (0, potygen_1.loadAllData)(this.ctx, this.data)
: this.data
: await loadDataFromParsedFiles(this.ctx, this.data, [file]);
await (0, emit_1.emitLoadedFile)(this.options.root, this.options.template, this.options.cacheStore, this.options.typePrefix)(loadFile(this.data)(file));
}
catch (error) {
this.options.logger.error(error instanceof Error ? String(error) : new Error(String(error)));
}
callback();
}
}
exports.QueryLoader = QueryLoader;
//# sourceMappingURL=traverse.js.map
{"version":3,"file":"traverse.js","sourceRoot":"","sources":["../src/traverse.ts"],"names":[],"mappings":";;;AAAA,2BAA6C;AAC7C,mCAA4C;AAC5C,iCAA8B;AAC9B,2CAYoB;AACpB,+BAA0C;AAC1C,8CAmB0B;AAE1B,iCAAwC;AACxC,+BAA+B;AAG/B,MAAM,gBAAgB,GAAG,CAAC,IAAU,EAAQ,EAAE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