vatts 2.1.2 → 2.1.3-canary.1.0.1

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,54 @@
1
+ export declare enum DataType {
2
+ STRING = "VARCHAR(255)",
3
+ TEXT = "TEXT",
4
+ INT = "INT",
5
+ LONG = "BIGINT",
6
+ BOOLEAN = "BOOLEAN",
7
+ JSON = "JSON",
8
+ UUID = "VARCHAR(36)"
9
+ }
10
+ export interface SchemaColumn {
11
+ name: string;
12
+ type: DataType;
13
+ indexed?: boolean;
14
+ primaryKey?: boolean;
15
+ nullable?: boolean;
16
+ autoIncrement?: boolean;
17
+ }
18
+ export type DbConfig = {
19
+ type: 'mysql' | 'postgres' | 'sqlite';
20
+ host?: string;
21
+ port?: number;
22
+ user?: string;
23
+ password?: string;
24
+ database?: string;
25
+ filepath?: string;
26
+ };
27
+ interface DatabaseAdapter {
28
+ query<T>(sql: string, params?: any[]): Promise<T[]>;
29
+ execute(sql: string, params?: any[]): Promise<any>;
30
+ formatPlaceholder(index: number): string;
31
+ getAutoIncrementSyntax(): string;
32
+ }
33
+ export declare class DatabaseConnector {
34
+ adapter: DatabaseAdapter;
35
+ constructor(config: DbConfig);
36
+ }
37
+ export declare class BaseEntity<ID_TYPE, TData> {
38
+ data: TData;
39
+ constructor(data: TData);
40
+ toJSON(): TData;
41
+ }
42
+ export declare abstract class BaseTable<ID_TYPE, TEntity extends BaseEntity<ID_TYPE, any>, TData> {
43
+ abstract tableName: string;
44
+ protected abstract entityConstructor: new (data: TData) => TEntity;
45
+ abstract defineSchema(): SchemaColumn[];
46
+ protected connector: DatabaseConnector | undefined;
47
+ setConnector(connector: DatabaseConnector): void;
48
+ protected get adapter(): DatabaseAdapter;
49
+ create(data: Omit<TData, "id"> & Partial<TData>): Promise<TEntity>;
50
+ findMany(conditions: Partial<TData>): Promise<TEntity[]>;
51
+ findOne(conditions: Partial<TData>): Promise<TEntity | null>;
52
+ syncSchema(): Promise<void>;
53
+ }
54
+ export {};
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ // ==========================================
3
+ // 1. TIPOS E ENUMS GERAIS
4
+ // ==========================================
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BaseTable = exports.BaseEntity = exports.DatabaseConnector = exports.DataType = void 0;
7
+ var DataType;
8
+ (function (DataType) {
9
+ DataType["STRING"] = "VARCHAR(255)";
10
+ DataType["TEXT"] = "TEXT";
11
+ DataType["INT"] = "INT";
12
+ DataType["LONG"] = "BIGINT";
13
+ DataType["BOOLEAN"] = "BOOLEAN";
14
+ DataType["JSON"] = "JSON";
15
+ DataType["UUID"] = "VARCHAR(36)";
16
+ })(DataType || (exports.DataType = DataType = {}));
17
+ class MySQLAdapter {
18
+ pool;
19
+ constructor(config) {
20
+ const mysql = require('mysql2/promise');
21
+ this.pool = mysql.createPool({
22
+ host: config.host, port: config.port,
23
+ user: config.user, password: config.password,
24
+ database: config.database
25
+ });
26
+ }
27
+ async query(sql, params = []) {
28
+ const [rows] = await this.pool.query(sql, params);
29
+ return rows;
30
+ }
31
+ async execute(sql, params = []) {
32
+ const [result] = await this.pool.execute(sql, params);
33
+ return result;
34
+ }
35
+ formatPlaceholder(index) { return '?'; }
36
+ getAutoIncrementSyntax() { return 'AUTO_INCREMENT'; }
37
+ }
38
+ class PostgresAdapter {
39
+ pool;
40
+ constructor(config) {
41
+ const { Pool } = require('pg');
42
+ this.pool = new Pool({
43
+ host: config.host, port: config.port,
44
+ user: config.user, password: config.password,
45
+ database: config.database
46
+ });
47
+ }
48
+ async query(sql, params = []) {
49
+ const result = await this.pool.query(sql, params);
50
+ return result.rows;
51
+ }
52
+ async execute(sql, params = []) {
53
+ return await this.pool.query(sql, params);
54
+ }
55
+ formatPlaceholder(index) { return `$${index + 1}`; }
56
+ getAutoIncrementSyntax() { return 'SERIAL'; } // Simplificado, idealmente SERIAL é tipo, não constraint
57
+ }
58
+ class SQLiteAdapter {
59
+ db;
60
+ constructor(config) {
61
+ const sqlite3 = require('sqlite3').verbose();
62
+ this.db = new sqlite3.Database(config.filepath || ':memory:');
63
+ }
64
+ query(sql, params = []) {
65
+ return new Promise((resolve, reject) => {
66
+ this.db.all(sql, params, (err, rows) => {
67
+ if (err)
68
+ reject(err);
69
+ else
70
+ resolve(rows);
71
+ });
72
+ });
73
+ }
74
+ execute(sql, params = []) {
75
+ return new Promise((resolve, reject) => {
76
+ this.db.run(sql, params, function (err) {
77
+ if (err)
78
+ reject(err);
79
+ else
80
+ resolve(this);
81
+ });
82
+ });
83
+ }
84
+ formatPlaceholder(index) { return '?'; }
85
+ getAutoIncrementSyntax() { return 'AUTOINCREMENT'; }
86
+ }
87
+ // ==========================================
88
+ // 3. ENGINE PRINCIPAL E CLASSES BASE
89
+ // ==========================================
90
+ class DatabaseConnector {
91
+ adapter;
92
+ constructor(config) {
93
+ if (config.type === 'mysql')
94
+ this.adapter = new MySQLAdapter(config);
95
+ else if (config.type === 'postgres')
96
+ this.adapter = new PostgresAdapter(config);
97
+ else if (config.type === 'sqlite')
98
+ this.adapter = new SQLiteAdapter(config);
99
+ else
100
+ throw new Error("Database type not supported");
101
+ }
102
+ }
103
+ exports.DatabaseConnector = DatabaseConnector;
104
+ // Entidade Base - Representa uma linha no banco
105
+ class BaseEntity {
106
+ data;
107
+ constructor(data) {
108
+ this.data = data;
109
+ Object.assign(this, data);
110
+ }
111
+ // Exemplo de método de instância (pode ser expandido para .save(), .delete())
112
+ toJSON() {
113
+ return { ...this.data };
114
+ }
115
+ }
116
+ exports.BaseEntity = BaseEntity;
117
+ // Tabela Base - Representa o repositório e construtor de query
118
+ class BaseTable {
119
+ connector;
120
+ setConnector(connector) {
121
+ this.connector = connector;
122
+ }
123
+ get adapter() {
124
+ if (!this.connector || !this.connector.adapter)
125
+ throw new Error("Database not connected! Pass a valid DatabaseConnector instance.");
126
+ return this.connector.adapter;
127
+ }
128
+ // --- OPERAÇÕES CRUD ---
129
+ async create(data) {
130
+ const columns = Object.keys(data);
131
+ const values = Object.values(data);
132
+ const placeholders = columns.map((_, i) => this.adapter.formatPlaceholder(i)).join(', ');
133
+ const sql = `INSERT INTO ${this.tableName} (${columns.join(', ')}) VALUES (${placeholders})`;
134
+ await this.adapter.execute(sql, values);
135
+ return new this.entityConstructor(data);
136
+ }
137
+ async findMany(conditions) {
138
+ const keys = Object.keys(conditions);
139
+ const values = Object.values(conditions);
140
+ let sql = `SELECT * FROM ${this.tableName}`;
141
+ if (keys.length > 0) {
142
+ const whereClause = keys.map((k, i) => `${k} = ${this.adapter.formatPlaceholder(i)}`).join(' AND ');
143
+ sql += ` WHERE ${whereClause}`;
144
+ }
145
+ const rows = await this.adapter.query(sql, values);
146
+ return rows.map(row => new this.entityConstructor(row));
147
+ }
148
+ async findOne(conditions) {
149
+ const results = await this.findMany(conditions);
150
+ return results.length > 0 ? results[0] : null;
151
+ }
152
+ // --- SINCRONIZAÇÃO DE SCHEMA ---
153
+ async syncSchema() {
154
+ const schema = this.defineSchema();
155
+ const columnsSql = schema.map(col => {
156
+ let def = `${col.name} ${col.type}`;
157
+ if (col.primaryKey)
158
+ def += ` PRIMARY KEY`;
159
+ if (col.autoIncrement)
160
+ def += ` ${this.adapter.getAutoIncrementSyntax()}`;
161
+ if (!col.nullable && !col.primaryKey)
162
+ def += ' NOT NULL';
163
+ return def;
164
+ }).join(', ');
165
+ const createTableSql = `CREATE TABLE IF NOT EXISTS ${this.tableName} (${columnsSql})`;
166
+ await this.adapter.execute(createTableSql);
167
+ // Criação de index (Simples)
168
+ for (const col of schema) {
169
+ if (col.indexed) {
170
+ const indexName = `idx_${this.tableName}_${col.name}`;
171
+ const indexSql = `CREATE INDEX IF NOT EXISTS ${indexName} ON ${this.tableName}(${col.name})`;
172
+ // Em try/catch pois alguns bancos (como MySQL) dão erro se recriar index de forma diferente
173
+ try {
174
+ await this.adapter.execute(indexSql);
175
+ }
176
+ catch (e) { }
177
+ }
178
+ }
179
+ console.log(`Schema for ${this.tableName} synchronized.`);
180
+ }
181
+ }
182
+ exports.BaseTable = BaseTable;
@@ -0,0 +1,6 @@
1
+ import { BaseTable, DatabaseConnector, DbConfig } from "./OrmDatabase";
2
+ export default class Database {
3
+ db: DatabaseConnector;
4
+ constructor(config: DbConfig, databases: Array<BaseTable<any, any, any>>);
5
+ }
6
+ export * from './OrmDatabase';
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ const OrmDatabase_1 = require("./OrmDatabase");
18
+ class Database {
19
+ db;
20
+ constructor(config, databases) {
21
+ this.db = new OrmDatabase_1.DatabaseConnector(config);
22
+ // Inicializa as tabelas
23
+ for (const table of databases) {
24
+ table.setConnector(this.db);
25
+ table.syncSchema();
26
+ }
27
+ }
28
+ }
29
+ exports.default = Database;
30
+ __exportStar(require("./OrmDatabase"), exports);
@@ -0,0 +1,21 @@
1
+ import { BaseEntity, BaseTable, SchemaColumn } from "./OrmDatabase";
2
+ export interface AllocationData {
3
+ nodeId: string;
4
+ ip: string;
5
+ externalIp: string | null;
6
+ port: number;
7
+ assignedTo: string | null;
8
+ }
9
+ export declare class Allocation extends BaseEntity<string, AllocationData> {
10
+ nodeId: string;
11
+ ip: string;
12
+ externalIp: string | null;
13
+ port: number;
14
+ assignedTo: string | null;
15
+ isAssigned(): boolean;
16
+ }
17
+ export declare class AllocationTable extends BaseTable<string, Allocation, AllocationData> {
18
+ protected entityConstructor: typeof Allocation;
19
+ tableName: string;
20
+ defineSchema(): SchemaColumn[];
21
+ }
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AllocationTable = exports.Allocation = void 0;
7
+ // 1. Interface para os dados da Alocação
8
+ const OrmDatabase_1 = require("./OrmDatabase");
9
+ const index_1 = __importDefault(require("./index"));
10
+ // 2. Classe da Entidade Allocation (com tipagem inferida perfeita)
11
+ class Allocation extends OrmDatabase_1.BaseEntity {
12
+ // Métodos customizados da entidade
13
+ isAssigned() {
14
+ return this.assignedTo !== null;
15
+ }
16
+ }
17
+ exports.Allocation = Allocation;
18
+ // 3. Classe da Tabela de Alocações
19
+ class AllocationTable extends OrmDatabase_1.BaseTable {
20
+ entityConstructor = Allocation;
21
+ tableName = 'hAllocations';
22
+ defineSchema() {
23
+ return [
24
+ { name: 'nodeId', type: OrmDatabase_1.DataType.STRING, indexed: true, nullable: false },
25
+ { name: 'ip', type: OrmDatabase_1.DataType.STRING, nullable: false },
26
+ { name: 'externalIp', type: OrmDatabase_1.DataType.STRING, nullable: true },
27
+ { name: 'port', type: OrmDatabase_1.DataType.INT, indexed: true, nullable: false },
28
+ { name: 'assignedTo', type: OrmDatabase_1.DataType.STRING, indexed: true, nullable: true },
29
+ ];
30
+ }
31
+ }
32
+ exports.AllocationTable = AllocationTable;
33
+ async function main() {
34
+ const allocations = new AllocationTable();
35
+ new index_1.default({
36
+ type: 'sqlite',
37
+ database: ':memory:',
38
+ }, [
39
+ allocations
40
+ ]);
41
+ // 3. Criando dados COM TIPAGEM E AUTO-COMPLETE MÁXIMO!
42
+ console.log("Criando nova alocação...");
43
+ const novaAlocacao = await allocations.create({
44
+ nodeId: 'node-01',
45
+ ip: '192.168.1.100',
46
+ externalIp: null,
47
+ port: 25565,
48
+ assignedTo: null
49
+ });
50
+ console.log("Alocação criada:", novaAlocacao.ip);
51
+ console.log("Está assinalada?", novaAlocacao.isAssigned());
52
+ // 4. Buscando dados com tipagem
53
+ const buscarNode = await allocations.findMany({ nodeId: 'node-01' });
54
+ console.log(`Encontrados ${buscarNode.length} resultados para o node-01.`);
55
+ }
56
+ main();